gpt4 book ai didi

java - org.hibernate.id.IdentifierGenerationException : ids for this class must be manually assigned before calling save(): com. app.entities.Details

转载 作者:行者123 更新时间:2023-12-02 10:16:56 24 4
gpt4 key购买 nike

我多次尝试使用下面的代码在表中插入 id 值,但它总是抛出 org.hibernate.id.IdentifierGenerationException: 此类的 ids 必须在调用 save() 之前手动分配:com.app.entites。 L详情

以下是实体类中的代码

@Column(name="LID")
@GenericGenerator(name="generatedId", strategy="com.app.common.IdGenerator")
@GeneratedValue(generator="generatedId", strategy=GenerationType.SEQUENCE)
@NotNull
private String lId;

我已经使用 IdentifierGenerator 实现了 id 生成器,如下所示

public class IdGenerator implements IdentifierGenerator{

private static String id;

@Override
public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
Connection con = session.connection();
try {
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery("select count(ID) from L_DETAILS");
if(rs.next()) {
int i = rs.getInt(1)+1;
this.id="ll"+i;
System.out.println("generated id is "+id);
return "l"+i;
}
}catch(SQLException e) {
e.printStackTrace();
}
return null;
}

}

最佳答案

使用以下方法在实体类中自动生成主键:-

 import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Entity;

@Entity
@Table(name = "your_table_name")
public class YourEntityClass{

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long id;

//other column names

// setter & getter methods

}

此后,每当您在表中保存新记录时,都不必生成新的 ID

关于java - org.hibernate.id.IdentifierGenerationException : ids for this class must be manually assigned before calling save(): com. app.entities.Details,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54624961/

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