使用本机SQL将外部列连接到Hibernate实体

时间:2016-04-08 10:02:22

标签: java hibernate postgresql nativequery

我有一个(简化的)表结构,看起来像这样:

客户表:

id       name
-------------------
 1       customer1

别名表:

customer_id       alias
-------------------------------
 1                 customer one
 1                 customer uno

当我运行以下查询时,我很容易得到每个客户的别名列表:

select * from customer_alias where customer_id=1;

我想在我的hibernate中使用此查询来填充类型String的列表。我尝试使用@Formula,如下所示:

@Entity
@Table(name = "customer")
public class Customer {
      @Id
      @Column(name = "id")
      @GeneratedValue(strategy= GenerationType.AUTO)
      private Long id;

      @Column(name="name")
      private String name;

      @Formula("(select alias from customer_alias where customer_id = id)")
      private List<String> aliases;

      // Getters, setters, etc...
}

它没有用,我得到了这个例外:

 Could not determine type for: java.util.List, at table: customer, for columns: [org.hibernate.mapping.Formula( (select alias from customer_alias where customer_id = id) )]

反正有没有实现这个目标?当然不一定是@Formula。任何合理的方式都会很棒。

以下是我的示例的SQLFiddle

2 个答案:

答案 0 :(得分:1)

您可以使用@ElementCollection来获取相关别名列表,而无需映射整个实体:

@ElementCollection
@CollectionTable(name = "customer_alias", joinColumns = @JoinColumn(name = "customer_id") )
@Column(name = "alias")
private List<String> aliases;

另见:

答案 1 :(得分:1)

我认为您不想使用@ElementCollection注释,因为第二个表只是一个字符串列表,您希望找到更优雅的字符串,而不需要我创建另一个实体。

您可以使用@Entity @Table(name="college") class College implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name="college_id") @GeneratedValue(strategy=GenerationType.IDENTITY) private int collegeId; @Column(name="name") private String collegeName; @ElementCollection @CollectionTable(name="student", joinColumns=@JoinColumn(name="college_id")) @Column(name="student_name") private Set<String> students; public College() { } public Set<String> getStudents() { return students; } public void setStudents(Set<String> students) { this.students = students; } public int getCollegeId() { return collegeId; } public void setCollegeId(int collegeId) { this.collegeId = collegeId; } public String getCollegeName() { return collegeName; } public void setCollegeName(String collegeName) { this.collegeName = collegeName; } @Override public String toString() { return "College [collegeId=" + collegeId + ", collegeName=" + collegeName + ", students=" + students + "]"; } ,如下所示:

@Formula

}

我认为variable1注释不支持集合,它只能应用于单值属性。不能说是否存在任何调整。