我正在尝试保存一个有参考usuari和对rol的引用的usuarirol。我检查了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);
}
}
}
我可以推断出的问题是Hibernate的会话无法跟踪您的子对象。从一个会话中加载并保存在另一个会话中的实体可能会引起问题。
因此,为了解决此问题。
- 开始会话和交易
- 获取子对象
- 保存父对象
- 然后提交
在上述所有过程中使用相同的会话。