简体   繁体   English

Hibernate命令外键表

[英]Hibernate order foreign key table

I have a REST API ( Spring REST with Hibernate ), which is the access point for all my data. 我有一个REST API( 带有Hibernate的Spring REST ),它是我所有数据的访问点。 A client application ( Cordova and AngularJS ) connect to this API for the data feed. 客户端应用程序( Cordova和AngularJS )连接到此API以获取数据馈送。

My versions in the REST API are: 我在REST API中的版本是:

Spring: 4.2.3.RELEASE 春天: 4.2.3.RELEASE

Hibernate: 4.3.11.Final Hibernate: 4.3.11.Final


Problem 问题

In the client application I require an ordered list. 在客户端应用程序中,我需要一个有序列表。 When I request a list from the REST API, the list is sorted differently almost every time. 当我从REST API请求列表时,几乎每次都对列表​​进行不同的排序。 This is quite annoying, since some text from the list is displayed on the screen and now it seems like it is jumping around. 这非常令人讨厌,因为列表中的某些文本会显示在屏幕上,现在看起来它似乎正在四处跳跃。


Hibernate 过冬

In my project I have the following Hibernate setup: 在我的项目中,我有以下Hibernate设置:

Company 公司

@OneToMany(fetch = FetchType.LAZY, mappedBy = "companyId", cascade = {CascadeType.ALL})
@JsonBackReference
private Set<Employee> employees= new HashSet<Employee>();

Employee 雇员

@NotNull
@Column(name = "companyId", nullable = false)
private int companyId;

A company can have many employees, but an employee can only work at one company at a time. 公司可以拥有许多员工,但员工一次只能在一家公司工作。


Hibernate Repository Hibernate存储库

Due to questions if I am using queries or not, here is my repository (using Criteria / Let hibernate do the job): 由于问题我是否使用查询,这里是我的存储库(使用Criteria /让hibernate完成工作):

public Employee findById(int id) {
   Criteria criteria = getSession().createCriteria(Employee.class);
   criteria.add(Restrictions.eq("id", id));
   return (Employee) criteria.uniqueResult();
}

Spring 弹簧

For better data handling I am making use of serialization models. 为了更好的数据处理,我正在使用序列化模型。 I implemented this one as follows (in my RestController ): 我按如下方式实现了这个(在我的RestController中 ):

Company company = companyManager.findCompanyWithEmployees(companyName);

Set<Employee> types = company.getEmployees();
Set<EmployeeList> list = new HashSet<EmployeeList>();

for (IncidentType item : types) {
    EmployeeList newItem = new EmployeeList();
    newItem.setId(item.getId())
           .setParent(item.getParent())
           .setChildren(item.getChildren())
           .setTitle(item.getTitle())
           .setImage(item.getImage());

     list.add(newItem);
}

This code creates a List of EmployeeList items, which I return and handle in my AngularJS code. 此代码创建一个EmployeeList项列表,我将在AngularJS代码中返回并处理。


I Tried 我试过了

  • I tried adding a Criteria in the Employee repository (findById), but It seems like Hibernate does not use the repository when getting a table via a foreign key. 我尝试在Employee存储库(findById)中添加Criteria,但看起来Hibernate在通过外键获取表时不使用存储库。

  • Tried adding an annotation, but Hibernate does not have annotation support for order by. 尝试添加注释,但Hibernate没有对order by的注释支持。


Extra information 额外的信息

Due to the fact that I use LAZY loading (for performance reasons), I use the following code in my repository: 由于我使用LAZY加载(出于性能原因),我在我的存储库中使用以下代码:

public Company findCompanyWithInterface(String companyName) {
   Company company = this.findByName(companyName);

   if (company == null) {
       return null;
   }
   //activate hibernate to load the employees (is LAZY loaded)
   Hibernate.initialize(company.getEmployees());

   return company;
}

My question 我的问题

Is there any way to tell Hibernate to order the list of Employees it gets via the company entity? 有没有办法告诉Hibernate订购通过公司实体获得的员工名单? I know I can order it in my code, but that is quite bad for the performance. 我知道我可以在我的代码中订购它,但这对性能来说非常糟糕。 So It would be nice if Hibernate could order the items. 所以如果Hibernate可以订购商品会很好。

Order by ID should be fine. 按ID排序应该没问题。 I can always change that if I want something else. 如果我想要别的东西,我总能改变它。

Anyone knows how I can achieve this without affecting the performance to bad? 任何人都知道如何在不影响性能的情况下实现这一目标?


Solution

Hibernate does not have a specific annotation for order by . Hibernate没有针对order by的特定注释。 javax.persistence does have an annotation for ordering ( @OrderBy() ). javax.persistence确实有一个用于排序的注释( @OrderBy() )。 Hibernate checks this annotation and orders the result. Hibernate检查此批注并对结果进行排序。

You need to use an ArrayList for this, so that the order is preserved (answer is below). 您需要为此使用ArrayList,以便保留顺序(如下所示)。

Credits to Benjamin Bau for the answer . 致Benjamin Bau的答案

Add the @OrderBy annotation to your employees. 将@OrderBy注释添加到您的员工。 Change the field from a set to a list so that order is preserved. 将字段从集更改为列表,以便保留顺序。

@OneToMany(fetch = FetchType.LAZY, mappedBy = "companyId", cascade = {CascadeType.ALL})
@OrderBy("id")
@JsonBackReference
private List<Employee> employees = new ArrayList<Employee>();

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

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