【java】实体类中 Set<对象> 按照对象的某个字段对set排序
Java利用hibernate进行一对多查询时,把另一张表作为一个属性存进这张表的字段中,返回的类型是set类型,要对返回的set类型进行排序
user表
package onlyfun.caterpillar; public class User { private Long id; private String name; public User() {} public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
room表:
package onlyfun.caterpillar; import java.util.Set; public class Room { private Long id; private String address; private Set<User> users = new HashSet<User>(); private List<User> user; public Room() {} public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Set getUsers() { return users; } public void setUsers(Set users) { this.users = users; } @Transient public List<User> getUser() { user= new ArrayList<User>(users); Collections.sort(user, new Comparator<User>() { @Override public int compare(User o1, User o2) { return o1.getId()<o2.getId() ? -1 :1; } }); return user; } public void setUser(List<User> user) { this.user= user; } }
在room实体中加一个List<User>用来装将Set按照自己的想法排序之后的结果在使用的地方直接取List里面的值即可。
把private Set<User> users = new HashSet<User>();查询出来的数据放到List<User>