Hibernate 如何获取新持久化实体的复合ID对象?
我正在尝试获取新持久化到DB的对象的(可嵌入的)复合id。我在Hibernate4.3.5中使用mysql(myisam) 插入操作本身成功,但创建的java对象的类别id始终为空,即使我刷新了对象并提交了事务。 但这只发生在复合id对象上。在单id对象中,我总是将新id取回 我忘了什么吗?感谢您的帮助 先谢谢你 本 朱尼特:Hibernate 如何获取新持久化实体的复合ID对象?,hibernate,jpa,flush,persist,composite-id,Hibernate,Jpa,Flush,Persist,Composite Id,我正在尝试获取新持久化到DB的对象的(可嵌入的)复合id。我在Hibernate4.3.5中使用mysql(myisam) 插入操作本身成功,但创建的java对象的类别id始终为空,即使我刷新了对象并提交了事务。 但这只发生在复合id对象上。在单id对象中,我总是将新id取回 我忘了什么吗?感谢您的帮助 先谢谢你 本 朱尼特: @Test public void _1testInsertCombinedEntity() { CategoryDao catDao = new Categor
@Test
public void _1testInsertCombinedEntity() {
CategoryDao catDao = new CategoryDao();
Category cat = new Category();
CategoryId catId = new CategoryId();
catId.setCategoryCustomerId(1l);
cat.setCategoryId(catId);
cat.setCategoryName(catName);
cat.setCategoryDescr("Hello World. This is a test");
cat.setCategoryPrintable(true);
cat.setCategoryBookable(true);
cat = catDao.save(cat);
Assert.assertNotNull(cat.getCategoryId().getCategoryId());
}
类别:
@Entity
@Table(name = "category")
public class Category implements ICombinedIdEntity {
@EmbeddedId
private CategoryId categoryId;
........
类别
@Embeddable
public class CategoryId implements Serializable, ICombinedId<Long, Long> {
/**
*
*/
private static final long serialVersionUID = -7448052477830797280L;
@Column(name = "category_id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long categoryId;
@Column(name = "category_customer_id", nullable = false)
private Long categoryCustomerId;
public Long getCategoryId() {
return this.categoryId;
}
public void setCategoryId(Long categoryId) {
this.categoryId = categoryId;
}
public Long getCategoryCustomerId() {
return this.categoryCustomerId;
}
public void setCategoryCustomerId(Long categoryCustomerId) {
this.categoryCustomerId = categoryCustomerId;
}
简而言之,这是不受支持的 这是因为
@EmbeddedId
标识符意味着要分配,因此解释了为什么忽略带注释的@GeneratedValue
字段
您可能可以使用一些JPA回调来设置insert上的值,但在开箱即用的情况下,Hibernate不会尝试设置这些值
protected T saveEntity(T entity) {
startTransaction();
System.out.println("Trying to save " + entity);
this.persistenceEngine.getEntityManager().persist(entity);
this.persistenceEngine.getEntityManager().flush();
commitCurrentTransaction();
clear();
return entity;
}