标签:
有A、B表和A_B中间表,A_B中间表只有A、B表的id,想让A中的bs以date列排序:
@Entity @Table(name="A") public class A implements java.io.Serializable { private Set<B> bs = new HashSet<B>(0); @ManyToMany(fetch=FetchType.LAZY) @JoinTable(name="A_B", joinColumns = { @JoinColumn(name="a_id", nullable=false, updatable=false) }, inverseJoinColumns = { @JoinColumn(name="b_id", nullable=false, updatable=false) }) @OrderBy(clause = "date desc") public Set<B> getBs() { return this.bs; } } @Entity @Table(name="B") public class B implements java.io.Serializable { @Column(name="date", nullable=false, length=29) private Date date; /* setters and getters */ }
以上代码中的@OrderBy是org.hibernate.annotations.OrderBy,如果使用A_B中间表中没有的列进行排序会出错,改成javax.persistence.OrderBy的@OrderBy就行了:
@ManyToMany(fetch=FetchType.LAZY) @JoinTable(name="A_B", joinColumns = { @JoinColumn(name="a_id", nullable=false, updatable=false) }, inverseJoinColumns = { @JoinColumn(name="b_id", nullable=false, updatable=false) }) @javax.persistence.OrderBy(value = "date desc") public Set<B> getBs() { return this.bs; }
org.hibernate.annotations.OrderBy把clause中的列名(date)当作是A_B表的列名,而javax.persistence.OrderBy把value中的列名(date)当作B表列名。
另:@OrderBy是在内存中排序,在db中不见得是有序的,@OrderColumn是数据在db中就是有序的
标签:
原文地址:http://www.cnblogs.com/drizzlewithwind/p/5800461.html