JPQL連結表クエリー、結果を返して連結表の2つのエンティティの結果を統合する
3807 ワード
sqlコード
package com.sys.service;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sys.entity.GradeStudent;
@Service
@Transactional
public class CommentService {
@PersistenceContext
EntityManager em;
@SuppressWarnings("unchecked")
public List getGradeStudents() {
String sql = "select new com.sys.entity.GradeStudent(s.name,s.idCard,g.gradeName) "
+ "from Student s,Grade g where s.idGrade=g.id order by g.gradeName";
Query query = em.createQuery(sql);
List list = query.getResultList();
return list;
}
}
Student
package com.sys.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Student {
private int id;
private String name;
private String idCard;
private int idGrade;
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* @return the idCard
*/
public String getIdCard() {
return idCard;
}
/**
* @param idCard the idCard to set
*/
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public int getIdGrade() {
return idGrade;
}
public void setIdGrade(int idGrade) {
this.idGrade = idGrade;
}
}
Grade
package com.sys.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Grade {
private int id;
private String gradeName;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGradeName() {
return gradeName;
}
public void setGradeName(String gradeName) {
this.gradeName = gradeName;
}
}
:
package com.sys.entity;
//@Entity
public class GradeStudent {
private int id;
private String name;
private String idCard;
private String gradeName;
public GradeStudent() {
}
public GradeStudent(String name, String idCard, String gradeName) {
super();
this.name = name;
this.idCard = idCard;
this.gradeName = gradeName;
}
/*@Id
@GeneratedValue*/
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public String getGradeName() {
return gradeName;
}
public void setGradeName(String gradeName) {
this.gradeName = gradeName;
}
}
:
@Entity 、@Id , 。
JPQL
select new com.sys.entity.GradeStudent(s.name,s.idCard,g.gradeName) from Student s,Grade g where s.idGrade=g.id order by g.gradeName
com.sys.entity.GradeStudent(s.name,s.idCard,g.gradeName)