hibernate别名Alias

实体:考试,成绩,学生,班级
关系:成绩与考试多对一,成绩与学生多对一,学生与班级多对一.
需求:要根据考试id和班级id查询学生成绩.

Score
@Entity  
public class Score {  
  
    private int id;  
  
    private Student student;  
  
    private Exam exam;  
  
    private int score;  
  
    @Id  
    @GeneratedValue(strategy = GenerationType.IDENTITY)  
    public int getId() {  
        return id;  
    }  
  
    public void setId(int id) {  
        this.id = id;  
    }  
  
    @ManyToOne  
    @JoinColumn(name = "studentid", referencedColumnName = "id")  
    public Student getStudent() {  
        return student;  
    }  
  
    public void setStudent(Student student) {  
        this.student = student;  
    }  
  
    @ManyToOne  
    @JoinColumn(name = "examid", referencedColumnName = "id")  
    public Exam getExam() {  
        return exam;  
    }  
  
    public void setExam(Exam exam) {  
        this.exam = exam;  
    }  
  
    public int getScore() {  
        return score;  
    }  
  
    public void setScore(int score) {  
        this.score = score;  
    }  
  
}  


Student
private int id;  
  
    private Grade grade;  
  
    private String name;  
    @Id  
    @GeneratedValue(strategy = GenerationType.IDENTITY)  
    public int getId() {  
        return id;  
    }  
  
    public void setId(int id) {  
        this.id = id;  
    }  
  
    @ManyToOne  
    @JoinColumn(name = "gradeid", referencedColumnName = "id")  
    public Grade getGrade() {  
        return grade;  
    }  
  
    public void setGrade(Grade grade) {  
        this.grade = grade;  
    }  
  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  


Exam和Grade略

下面是查询代码.
ScoreDao:
@SuppressWarnings("unchecked")  
    public List<Score> getList(int examid, int gradeid) {  
        Criteria c = getSession().createCriteria(Score.class);  
        c.setFetchMode("exam", FetchMode.JOIN);  
        c.add(Restrictions.eq("exam.id", examid));  
        c.createAlias("student.grade", "grade");  
        c.add(Restrictions.eq("grade.id", gradeid));  
  
        return c.list();  
    }  


转自:http://www.verydemo.com/demo_c146_i2502.html

你可能感兴趣的:(Hibernate)