简体   繁体   English

Hibernate实体排序列配置

[英]Hibernate Entity sort column configuration

Is there a Hibernate configuration (hopefully an annotation on a classes mapped @Column field) that would let me sort a collection of entities associated with the loaded entity by a given column of that entity when a session.load(Entity.class, Id) is called? 是否有一个Hibernate配置(希望在映射到@Column的类上有注释),当session.load(Entity.class,Id)时,该配置可让我按该实体的给定列对与该加载的实体相关联的实体的集合进行排序叫做?

For example if I had an EntityA that contained a OneToMany association to an EntityB. 例如,如果我有一个EntityA包含一个与EntityB的OneToMany关联。

@Entity
public class EntityA {
    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY) 
    private Set<EntityB> headlines = new TreeSet<Entity>();

}

I want EntityB to be sorted in the Set that is returned from Hibernate. 我希望EntityB在从Hibernate返回的Set中排序。

session.load() loads a single entity instance. session.load()加载单个实体实例。 No sorting is involved. 不涉及排序。

Update (based on question edit): 更新 (基于问题编辑):

@OrderBy("column_name") can be used to sort collection elements within entity by given column; @OrderBy("column_name")可用于按给定的列对实体内的集合元素进行排序; however that only makes sense for collections that maintain their order (eg List, not Set): 但是,这仅对保持其顺序的集合有意义(例如,列表,而不是集合):

@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY) 
@OrderBy("name")
private List<EntityB> headlines = new ArrayList<Entity>();

Session.load does not load a list, only a single object. Session.load不加载列表,仅加载单个对象。

You can sort a list of entities when you retrieve them from the database by using the addOrder() method on the criteria. 通过使用条件上的addOrder()方法,可以在从数据库中检索实体时对它们进行排序。

If you have a parent class with a list of children, you can order the children with the @OrderBy annotation (see Hibernate Annotations - Collections 如果您有一个带有孩子列表的父类,则可以使用@OrderBy批注对孩子进行排序(请参见Hibernate Annotations-Collections)。

I used @Sort and a SortedSet collection to map my association which required that my Entity implement Comparable interface (int compareTo(T) method). 我使用@Sort和SortedSet集合来映射我的关联,这要求我的实体实现Comparable接口(int compareTo(T)方法)。

@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
@Sort(type=SortType.NATURAL)    
private SortedSet<Entity> headlines = new TreeSet<Entity>();

不能。您只能选择在收集级别(@OrderBy)或通过hql或条件api进行订购。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM