我正在尝试保存一个usuariRol,它引用了usuari和rol的引用。 我检查Usuari对象和Rol对象是否有它们的id但是hibernate告诉我idRol不能为null。
映射是否有问题?
表t_usuariRol
@Entity
@Table(name = "t_usuariRol"
, uniqueConstraints = @UniqueConstraint(columnNames = {"idUsuari", "idRol"}))
public class UsuariRol implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
@JoinColumn(name = "idUsuari")
private Usuari usuari;
@ManyToOne
@JoinColumn(name = "idRol")
private Rol rol;
表a_rol
@Entity
@Table(name = "a_rol")
public class Rol implements Serializable {
private static final long serialVersionUID = -1979744578967968079L;
static final String PREFIX = "pia.entity.Rol.";
public static final String findAll = PREFIX + "findAll";
public static final String findById = PREFIX + "findById";
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(length = 45)
private String nom;
UsuariBean.saveUsuariRol
public void saveUsuariRol(){
UsuariRol urol;
Usuari usuari = usuariMgr.findById(1);
Rol rol = rolMgr.findById(2); //rol is not null has id and nom
urol = new UsuariRol(usuari, rol);
try {
usuariRolMgr.save(urol);
} catch (Exception e) {
System.out.println("error usuarirol with id");
}
}
错误
Hibernate:
/* insert UsuariRol /
insert
into
t_usuariRol
(idRol, idUsuari, version)
values
(?, ?, ?)
10:25:39,184 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-52) SQL Error: 1048, SQLState: 23000
10:25:39,186 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-52) Column 'idRol' cannot be null
...
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
...
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'idRol' cannot be null
RolManager
@Stateless
public class RolManager {
protected Logger logger = Logger.getLogger(getClass().getName());
@PersistenceContext(unitName = "dbPU")
protected EntityManager em;
public Rol findById(int id) {
return this.em.find(Rol.class, id);
}
public List<Rol> all() {
return this.em.createNamedQuery(Rol.findAll, Rol.class).
getResultList();
}
public Rol save(Rol rol) {
if (rol.getId() == null) {
this.em.persist(rol);
return rol;
} else {
return this.em.merge(rol);
}
}
public void delete(int id) {
try {
Rol reference = this.em.getReference(Rol.class, id);
this.em.remove(reference);
} catch (EntityNotFoundException e) {
//we want to remove it
logger.error("Entity not found exeption: ", e);
}
}
}
答案 0 :(得分:1)
我可以推断的问题是hibernate的会话无法跟踪你的子对象。从一个会话加载并保存在另一个会话中的实体可能会导致问题。
所以为了解决这个问题。
对上述所有过程使用相同的会话。