简体   繁体   中英

How to Sort element with object null in Spring Data Jpa

I have two entity below:

@Entity
public class Task {
...
@ManyToOne
private User user;
...
}

@Entity
public class User {
private String firstName;
private String lastName;
@OneToMany(mappedBy = "task")
private Set<Task> task;
...
}

How can I using Sort to Sort Task by firstName of User with User is null on top?

I have try Sort.by(Sort.Order.asc("user.firstName").nullsFirst()); But I got the error: NullpointerException

You can create something like this.

Criteria criteria = ...;
criteria.addOrder( Order.asc( "firstName" ).nulls(NullPrecedence.FIRST) );

for more information you can check this documentation.

NullPrecedence

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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