如何获取新的持久化实体的复合ID对象?

时间:2017-02-25 12:11:20

标签: hibernate jpa flush persist composite-id

我正在尝试将新持久化的对象的(Embeddable)复合id添加到数据库中。我正在使用mysql(myisam)和hibernate 4.3.5。

插入操作本身成功,但是创建的java对象的category-id始终为null,即使我刷新了对象并提交了事务。 但这只发生在复合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;

 ........

类别ID

@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 个答案:

答案 0 :(得分:1)

简短的回答是不支持。

这是因为要分配@EmbeddedId个标识符,从而解释了为什么会忽略带注释的@GeneratedValue字段。

您可以使用一些JPA回调来设置插入值,但开箱即用,Hibernate不会尝试设置这些值。