我正在尝试创建一个服装IdentityGenerator。如果id为null,则生成else赋值。我发现了这个:Bypass GeneratedValue in Hibernate (merge data not in db?)
但我一直得到java.sql.SQLException:字段' id'没有默认值。
我的实体:
@Entity
public class TestEntity extends AbstractEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY, generator = "IdOrGenerated")
@GenericGenerator(name = "IdOrGenerated", strategy = "com.xxx.service.UseIdOrGenerate")
protected Long id;
@Column(length = 64)
private String name;
public TestEntity(String name) {
super();
this.name = name;
}
public TestEntity(Long id, String name) {
super();
this.id = id;
this.name = name;
}
public TestEntity() {
super();
}
}
我的自定义生成器:
public class UseIdOrGenerate extends IdentityGenerator {
@Override
public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
Serializable id = session.getEntityPersister(null, object).getClassMetadata().getIdentifier(object, session);
id = id != null ? id : super.generate(session, object);
return id;
}
}
答案 0 :(得分:0)
返回未分配的变量/字段会导致错误。需要为字段id
分配一个默认值,只要它有一个默认值就无关紧要。
protected Long id = new Long(0);