gpt4 book ai didi

JPA : @SequenceGenerator is not generating the sequence

转载 作者:行者123 更新时间:2023-12-05 05:28:12 24 4
gpt4 key购买 nike

我的应用程序已将 JPA 与 Hibernate 供应商和 Oracle 11G DB 一起使用。

在这里,我在我的 MST_EMP 表上使用 native 查询,如下所示。

  Query query  = this.entityManager.createNativeQuery("INSERT  INTO MST_EMP emp (" +
"EMP_NAME,EMP_MAIL_ID) VALUES ('dasdas',?)");
query.setParameter(1,"dhrumil");
query.executeUpdate();

这是我的 MST_EMP 实体详细信息..

@Table(name = "MST_EMP")
public class MstEmp implements Serializable, IsEntity {

private static final long serialVersionUID = 1L;

@Id
@Column(name = "EMP_CODE")
@SequenceGenerator( name = "EMP_CODE_SEQ", sequenceName = "EMP_CODE_SEQ")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EMP_CODE_SEQ")
private String empCode;


@Column(name="EMP_MAIL_ID")
private String empMailId;


@Column(name="EMP_NAME")
private String empName;

public MstEmp() {
}

public String getEmpCode() {
return this.empCode;
}

public void setEmpCode(String empCode) {
this.empCode = empCode;
}

public String getCreatedBy() {
return this.createdBy;
}


public void setEmpMailId(String empMailId) {
this.empMailId = empMailId;
}



public String getEmpName() {
return this.empName;
}

public void setEmpName(String empName) {
this.empName = empName;
}

}

据我了解,我们不需要在 native 查询中为 EMP_CODE 赋值。因为序列与它相关联。

但是这个查询给我这样的错误..

SEVERE: ORA-01400: cannot insert NULL into ("PERK"."MST_EMP"."EMP_CODE")

SEVERE: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute native bulk manipulation query
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1179)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1112)

谁能告诉我,我们需要在 native 查询中提供 EMP_CODE 吗?

会不会原生查询,不引用Entity中自动声明的sequence?

谢谢。

最佳答案

JPA 仅在您通过 EntityManager.persist() 方法持久化新对象时自动生成序列:

例如

EntityManager em = \\ ...  Initialise
MstEmp newMstEmp = new MstEmp();
newMstEmp.setEmpCode(...);
newMstEmp.setEmpMailId(...);
newMstEmp.setEmpName(...);
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(newMstEmp);
tx.commit();

当您将 JPQL 直接应用于数据库(通过 entityManager.createQuery())或将原始 SQL 直接应用于数据库(通过 entityManager.createNativeQuery())时 - 正如您在这里做),你必须插入你自己的序列:

Query query  = this.entityManager.createNativeQuery("INSERT  INTO MST_EMP emp (" +
"EMP_CODE,EMP_NAME,EMP_MAIL_ID) VALUES (EMP_CODE_SEQ.nextval,'dasdas',?)");
query.setParameter(1,"dhrumil");
query.executeUpdate();

关于JPA : @SequenceGenerator is not generating the sequence,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13189401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com