使用Criteria Hibernate查询对象

时间:2016-05-23 05:19:25

标签: java hibernate

我正在使用Criteria在Hibernate中尝试一个示例。 以下是我的表格:

CREATE TABLE  test.college (
  collegeId int(11) NOT NULL AUTO_INCREMENT,
  collegeName varchar(255) DEFAULT NULL,
  PRIMARY KEY (collegeId)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

CREATE TABLE  test.student (
  studentId int(11) NOT NULL AUTO_INCREMENT,
  studentName varchar(255) DEFAULT NULL,
  college_id int(11) DEFAULT NULL,
  PRIMARY KEY (studentId),
  KEY FKF3371A1B11FE0A03 (college_id),
  CONSTRAINT FKF3371A1B11FE0A03 FOREIGN KEY (college_id) REFERENCES college (collegeId)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

所以我的实体类是:

College.Java

package com.hibernate.onetomany;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class College {

    private int collegeId;
    private String collegeName;
    private List<Student> students;

    @Id
    @GeneratedValue
    public int getCollegeId() {
        return collegeId;
    }
    public void setCollegeId(int collegeId) {
        this.collegeId = collegeId;
    }
    public String getCollegeName() {
        return collegeName;
    }
    public void setCollegeName(String collegeName) {
        this.collegeName = collegeName;
    }
    @OneToMany(targetEntity=Student.class,mappedBy="college",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
    public List<Student> getStudents() {
        return students;
    }
    public void setStudents(List<Student> students) {
        this.students = students;
    }
}

我的 Student.java

package com.hibernate.onetomany;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;


@Entity
public class Student {

    private int studentId;
    private String studentName;
    private College college;

    @Id
    @GeneratedValue
    public int getStudentId() {
        return studentId;
    }
    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }
    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    @ManyToOne
    @JoinColumn(name="college_id")
    public College getCollege() {
        return college;
    }
    public void setCollege(College college) {
        this.college = college;
    }

}

在上面的例子中,我使用了一对多关联。

以下是我的主要方法:

TestStudent.java

package com.hibernate.onetomany;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;

public class TestStudent {

    public static void main(String[] args){
            readRecords();
    }

    private static void readRecords() {
        SessionFactory factory = new Configuration().configure().buildSessionFactory(); 
        Session session = factory.openSession();
        session.beginTransaction();

        //Criteria cr = session.createCriteria(College.class,"college").createAlias("college.collegeId", "abc", JoinType.FULL_JOIN);
        Criteria cr = session.createCriteria(College.class).add(Restrictions.eq("collegeId", 2));


        List<College> collegeList = cr.list();

        for(College college : collegeList){
            System.out.println("CollegeID : " + college.getCollegeId());
            System.out.println("CollegeName : " + college.getCollegeName());
            List<Student> studentList = college.getStudents();
            for(Student student : studentList){
                System.out.println("StudentID : " + student.getStudentId());
                System.out.println("StudentName : " + student.getStudentName());
            }
        }
    }
}

我的 hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE hibernate-configuration PUBLIC
      "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
      "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">
            com.mysql.jdbc.Driver</property>
        <property name="connection.url">
            jdbc:mysql://localhost:3306/world</property>
        <property name="connection.username">user1</property>
        <property name="connection.password">password</property>
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <mapping class="com.hibernate.onetomany.College" /> 
        <mapping class="com.hibernate.onetomany.Student" />
    </session-factory>
</hibernate-configuration>

现在上面的例子运行顺畅而完美。但我有一个小要求。 我必须传递一个过滤条件: 获取studentName所在的结果集:ABC 所以我想使用学生名称来过滤结果集。

简而言之,我想使用下面的代码来获得结果: 的 Criteria cr = session.createCriteria(College.class).add(Restrictions.eq("studentName", "ABC"));

如何使用相同的OneToMany方法达到上述要求?

期待您的解决方案。 提前谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用@NamedQuery@NamedNativeQuery

@Entity
@NamedNativeQueries({
    @NamedNativeQuery(
        name = "college.findByStudentName",
        query = "SELECT * from test.college WHERE collegeId IN (SELECT college_id from test.student WHERE studentName = (:name))",
        resultClass = College.class
    )
)}
public class College {

    ...

}

编辑

这是如何使用命名查询:

List colleges = session.getNamedQuery("college.findByStudentName")
        .setString("name", "Linda Berry")
        .list();