2017-02-25 76 views
0

我試圖讓一個對象的(Embeddable)複合標識最新持久化到數據庫。我用hibernate 4.3.5使用mysql(myisam)。如何獲取新持久實體的組合ID對象?

插入操作本身成功,但創建的java對象的category-id始終爲空,即使我刷新了對象並提交了事務。 但是這隻發生在複合id對象上。在單個id對象中,我總是會獲得新的id。

我忘記了什麼嗎?任何幫助表示讚賞。

預先感謝您

的JUnit:

@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; 

........ 

的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; 
    } 

AbstractDao的保存方法

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; 
    } 

回答

1

簡短的回答是,這是不支持的。

這是因爲@EmbeddedId標識符是要分配的,因此解釋了爲什麼您註釋的@GeneratedValue字段被忽略。

您可能可以使用某些JPA回調來設置on-insert的值,但開箱即用,Hibernate不會嘗試設置這些值。

相關問題