質問

I am trying to sort the Faculty entity by using the JPQL below but I am retrieving too many faculty of the same id.

@NamedQuery(
        name = "Faculty.findFacultySortedByPreferredTime",
        query = "SELECT f FROM Faculty f JOIN f.preferredTimes p ORDER BY p.day, p.startTime"
),

Here is my Faculty entity I am working

public class Faculty implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String firstName;
private String middleName;
private String lastName;

@OneToMany(cascade = CascadeType.PERSIST)
@OrderBy(value = "day, startTime")
private List<PreferredTime> preferredTimes;

// some codes removed

Am I doing it wrong?

役に立ちましたか?

解決

For the most part, JPA returns an entity for each row you've selected from the database, so when joining to a 1:M or M:M relationship, you will get more than one instance of an object back. In this case, a Faculty has many preferredTimes. If faculty1 has preferredTimeA and preferredTimeC while faculty2 has preferredTimeB and preferredTimeD, you would get an ordered list of (faculty1, faculty2, faculty1, faculty2) because of the join and ordering you specified.

The DISTINCT keyword is used to filter out non-distinct entities/rows:

"SELECT DISTINCT f FROM Faculty f JOIN f.preferredTimes p ORDER BY p.day, p.startTime"
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top