Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Hibernate说';idRol';不能为空_Hibernate_Jpa_Null_Primary Key - Fatal编程技术网

Hibernate说';idRol';不能为空

Hibernate说';idRol';不能为空,hibernate,jpa,null,primary-key,Hibernate,Jpa,Null,Primary Key,我试图保存一个引用了usuari和rol的usuariRol。 我检查Usuari对象和Rol对象是否有它们的id,但是hibernate告诉我idRol不能为null 映射有问题吗 表t_usuariRol @Entity @Table(name = "t_usuariRol" , uniqueConstraints = @UniqueConstraint(columnNames = {"idUsuari", "idRol"})) public class UsuariRol

我试图保存一个引用了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;
@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;
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");
 }
表a\u rol

@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;
@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;
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");
 }
UsuariBean.saveUsuariRol

@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;
@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;
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
@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);
        }
    }
}
RolManager

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
@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);
        }
    }
}
@无状态
公开课经理{
受保护的记录器=Logger.getLogger(getClass().getName());
@PersistenceContext(unitName=“dbPU”)
受保护的实体管理器em;
公共Rol findById(内部id){
返回此.em.find(Rol.class,id);
}
公共列表全部(){
返回这个.em.createNamedQuery(Rol.findAll,Rol.class)。
getResultList();
}
公共Rol保存(Rol Rol){
if(rol.getId()==null){
这个。em。persist(rol);
返回rol;
}否则{
返回此.em.merge(rol);
}
}
公共无效删除(int-id){
试一试{
Rol reference=this.em.getReference(Rol.class,id);
本.em.remove(参考);
}捕获(EntityNotFounde异常){
//我们想删除它
logger.error(“未找到实体验证:”,e);
}
}
}

我可以推断出的问题是hibernate的会话无法跟踪您的子对象。从一个会话加载并保存在另一个会话中的实体可能会导致问题

所以为了解决这个问题

  • 启动会话和事务
  • 获取子对象
  • 保存父对象
  • 然后提交

  • 对上述所有过程使用相同的会话。

    如何
    rolMgr.findById(2)是否将此对象返回给您?它是通过hibernate DAO还是其他一些类变量返回的?我添加了类管理器,您可以在其中看到您所要求的内容。UsuariRolManager中的保存方法类似。来自管理器的每个方法都获得em注入。是否该实体没有从entityManager分离对象Rol?。我只是findById和save方法中的open and close entityManager。这通常在不保存依赖对象时发生。这就是为什么建议在保存父实体之前先保存它们。在您的情况下,当数据库中没有
    rol
    时,如果在
    UsuariRol
    类中添加级联参数,如
    @ManyToOne(cascade=CascadeType.ALL)
    on
    private rol-rol字段,那么它能解决您的问题吗?这是一个很好的解决方案,但我会继续寻找最佳解决方案