我尝试了很多次使用下面的代码在我的表中插入 id 值,但它总是抛出 org.hibernate.id.IdentifierGenerationException:必须在调用 save() 之前手动分配此类的 id:com.app.entites.LDetails
以下是实体类中的代码
@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;
}
}