【问题标题】:Typesafe Primary Key in Hibernate/JPAHibernate/JPA 中的类型安全主键
【发布时间】:2010-02-05 19:09:43
【问题描述】:

我正在寻找一种在 Hibernate 中使用泛型为我的实体提供类型安全主键的方法。而不是这样做

@Entity
public class User{

@PrimaryKey
Long id

}

我正在考虑这样做......

@Entity
public class User{

@PrimaryKey
PrimaryKey<User,Long> id

}

或者更进一步地进行类型推断......

有什么想法吗?以前有人试过吗?你会通过使你的类 PrimaryKey 可嵌入来做到这一点吗?

@Entity
public class User extends MyEntity<Long>//Primary key type{

@PrimaryKey
PrimaryKey<User> id;

}

【问题讨论】:

  • 可以使用类型转换器代替嵌入式类型。但还没有测试方法
  • 7 年过去了,@Benju 能否请您分享一下经验,您最终是否使用过它,它有帮助吗?

标签: java hibernate generics orm jpa


【解决方案1】:

虽然可以使用 PK 类并将其用作具有 @EmbeddedId 的实体的成员,但这通常会使您的所有 JQL 查询和 Java 代码更加冗长:

select a.addressKey.id from Address a

AddressKey addressKey = new AddressKey();
addressKey.setCountry("USA");
addressKey.setId(634);
Address a = entityManager.find(Address.class, addressKey);    

所以我个人只会将它用于真正的复合键(即不具有单个属性)。

实际上,我真的很想知道您要解决什么问题,因为最后,无论如何您都必须处理Long。我并没有真正看到单个属性类型安全主键的附加值。

【讨论】:

    【解决方案2】:

    如果您正在寻找一种类型安全的方式来识别实体,那么使用它的 LazyLoadingProxy 怎么样?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-18
      • 2012-09-02
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      • 2018-02-02
      • 1970-01-01
      相关资源
      最近更新 更多