1
其映射到DTO的時候我有一個實體,稱爲學生實體中獲取集合使用變形金剛
@Entity
@Table(name = "students")
public class Student implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "STUDENT_ID")
private Integer studentId;
@Column(name = "STUDENT_NAME", nullable = false, length = 100)
private String studentName;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "student", cascade = CascadeType.ALL)
private List<Note> studentNotes;
// Some other instance variables that are not relevant to this question
/* Getters and Setters */
}
,並稱爲注意
@Entity
@Table(name = "notes")
public class Note implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "NOTE_ID")
private Integer noteId;
@Column(name = "NOTE_CONTENT")
private String noteText;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "STUDENT_ID")
private Student student;
/* Getters and Setters */
}
實體正如你所看到的關係決定了一個學生可以有多個音符。
爲了在特定頁面上顯示關於學生的一些信息,我只需要studentName,筆記數量和所有筆記。 我創建了一個StudentDTO,它看起來是這樣的:
public class StudentDTO {
private Long count;
private String name;
private List<Note> notes;
/* Getters and setters */
}
,我使用下面的代碼映射學生和註釋從DB
private static void testDTO() {
Session session = getSessionFactory().openSession();
String queryString = "SELECT count(n) as count, s.studentName as name, s.studentNotes as notes " +
"from Student s join s.studentNotes n where s.id = 3";
Query query = session.createQuery(queryString);
List<StudentDTO> list = query.setResultTransformer(Transformers.aliasToBean(StudentDTO.class)).list();
for (StudentDTO u : list) {
System.out.println(u.getName());
System.out.println(u.getCount());
System.out.println(u.getNotes().size());
}
}
以上恢復到StudentDTO代碼在查詢中提取了筆記時失敗,但是如果我刪除筆記並只獲取名稱並且計數工作正常。
時的注意事項包括在查詢中,這是由休眠射出的錯誤:
select
count(studentnot2_.NOTE_ID) as col_0_0_,
. as col_3_0_,
studentnot3_.NOTE_ID as NOTE_ID1_2_,
studentnot3_.NOTE_CONTENT as NOTE_CON2_2_,
studentnot3_.STUDENT_ID as STUDENT_3_2_
from
students studentx0_
inner join
notes studentnot2_
on studentx0_.STUDENT_ID=studentnot2_.STUDENT_ID
inner join
notes studentnot3_
on studentx0_.STUDENT_ID=studentnot3_.STUDENT_ID
where
studentx0_.STUDENT_ID=3;
這是錯誤消息,我得到:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'as col_3_0_, studentnot3_.NOTE_ID as NOTE_ID1_2_, studentnot3_.NOTE_CONTENT as N' at line 1
現在我可以看到查詢是錯誤的,但是它是由Hibernate生成的,而不是我控制的東西。有什麼我需要改變我的查詢字符串,以實現我需要的結果。
我不想要的結果手動映射到我的DTO,是沒有辦法,我可以在我的Student.java studentNotes直接映射到音符StudentDTO.java
但是這打敗了DTO的目的。我將不得不手動填充StudentDTO的字段 –