woe*_*ann 25 java hibernate jpa
我有一个生成id的表,但在某些情况下我想自己设置它.我可以以某种方式强制Hibernate忽略@GeneratedValue吗?
它可能是一个矫枉过正,但你有没有考虑编写自己的CustomIDGenerator,它可能是子类说hibernate的AutoGenerator并公开了几个方法,你可以设置下一个类对象的id来生成,例如
class MyGenerator extends .... {
public void setIdForObject(Class clazz, Long id) {
//once you use this API, the next time an object of
//type clazz is saved the id is used
}
public void setIdForObject(Class clazz, Long id, Matcher matcher) {
//once you use this API, the next time an object of
//type clazz is saved and the matcher matches yes the id will be
//assigned. Your matcher can match properties like name, age etc
//to say the matched object
}
}
Run Code Online (Sandbox Code Playgroud)
这可能会变得复杂,但至少可以按照hibernate doco进行
小智 6
创建您自己的标识符生成器/序列生成器
public class FilterIdentifierGenerator extends IdentityGenerator implements IdentifierGenerator{
@Override
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException {
// TODO Auto-generated method stub
Serializable id = session.getEntityPersister(null, object)
.getClassMetadata().getIdentifier(object, session);
return id != null ? id : super.generate(session, object);
}
}
Run Code Online (Sandbox Code Playgroud)
将您的实体修改为:
@Id
@GeneratedValue(generator="myGenerator")
@GenericGenerator(name="myGenerator", strategy="package.FilterIdentifierGenerator")
@Column(unique=true, nullable=false)
private int id;
...
Run Code Online (Sandbox Code Playgroud)
并在保存而不是使用persist()
usemerge()
或update()
归档时间: |
|
查看次数: |
25548 次 |
最近记录: |