【问题标题】:Hibernate: mapping collection property with alternate join columnHibernate:使用备用连接列映射集合属性
【发布时间】:2014-07-07 15:55:36
【问题描述】:

场景:Hibernate 3.6 与基于 xml 的映射、Java7、Postgresql 8.3。

我目前正在重构一个应用程序,其中我有这个数据库场景:

main_table
 id integer
 other_field string 
 (id) PK


secondary_table
 other_field string
 value string
 (other_field, value) PK

基本上,有一个辅助表,其中包含一个与主表匹配的“other_field”;我需要提取 main_table 中某条记录的所有值并映射它们。

在 SQL 中,我会使用如下查询:

SELECT value FROM secondary table INNER JOIN main_table ON secondary_table.other_field == main_table.other_field where main_table.id = 1;

但我不明白如何使用这样的查询将一组基本类型(字符串)映射到 Java 中的 Main 对象(或者如果我建议的查询对休眠不友好,则使用类似的查询),以便我可以在我的映射对象上有一个“值”属性,它应该是一个 Set

【问题讨论】:

    标签: java hibernate postgresql hibernate-mapping


    【解决方案1】:

    我想这就是你要找的:

    @Entity
    public class Primary { // Main table
      @Id
      @Column(name="EMP_ID")
      private long id;
      ...
      @ElementCollection
      @CollectionTable(
            name="PRIMARY_SECONDARY",
            joinColumns=@JoinColumn(name="PRIMARY_ID")
      )
      private Set<Secondary> phones;
      ...
    }
    
    @Embeddable
    public class Secondary {  // Secondary table
      private String value;
      ...
    }
    

    Full example and further details.

    【讨论】:

    • 那不依赖secondary table 有一个primary_id 数字列加入吗?或者这也可以是string
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 2011-06-22
    • 1970-01-01
    • 2011-03-01
    相关资源
    最近更新 更多