[英]@Id @GeneratedValue but set own ID value
我有一個帶有生成ID的表,但是在某些情況下,我想自行設置它。 我可以以某種方式強制Hibernate忽略@GeneratedValue嗎?
可能是一個矯kill過正,但您是否考慮過編寫自己的CustomIDGenerator,它的子類可能表示休眠的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
}
}
這可能會變得復雜,但至少每個冬眠doco都有可能
盡管這個問題是很久以前提出的,但我在@lOranger的這篇文章中找到了完美的答案,並希望與大家分享。
該提議檢查對象的當前ID是否設置為null
以外的其他null
,如果是,則使用它,否則,它將使用默認(或配置的)生成策略來生成它。
這很簡單,簡單,解決了@Jens提出的無法檢索對象當前ID的問題。
我剛剛實現了它(通過擴展UUIDGenerator),它的工作原理很像:-D
創建自己的identifiergenerator / sequencegenerator
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);
}
}
將您的實體修改為:
@Id
@GeneratedValue(generator="myGenerator")
@GenericGenerator(name="myGenerator", strategy="package.FilterIdentifierGenerator")
@Column(unique=true, nullable=false)
private int id;
...
並且在保存而不是使用persist()
使用merge()
或update()
對於您的用例,您可以手動添加此no用戶。 一種方法是將插入操作放在名為“ ./import.sql”的文件中(在您的類路徑中)。 當SessionFactory啟動時,Hibernate將執行這些語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.