【问题标题】:How to get Composite ID object of new persisted entity?如何获取新持久实体的复合 ID 对象?
【发布时间】:2017-02-25 12:11:20
【问题描述】:

我正在尝试获取新持久保存到数据库的对象的(可嵌入)复合 ID。我正在使用带有休眠 4.3.5 的 mysql (myisam)。

插入操作本身成功,但是即使我刷新了对象并提交了事务,创建的 java 对象的类别 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;

 ........

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

【问题讨论】:

    标签: hibernate jpa flush persist composite-id


    【解决方案1】:

    简短的回答是不支持。

    这是因为要分配 @EmbeddedId 标识符,因此解释了为什么您的带注释的 @GeneratedValue 字段被忽略。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-08
      • 2020-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多