java - 使用 Criteria Hibernate 查询对象

标签 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 方法实现上述要求?

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

最佳答案

您可以使用@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();

关于java - 使用 Criteria Hibernate 查询对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37383089/

相关文章:

java - java socket程序中的多线程

java - 如何禁用JComponents进程

java - C++ 和 Java 应用程序的最佳数据库

java - 如何使用 hibernate 检索表的所有主键?

java - 没有主键的表的 Hibernate 映射

java - 数据库时区问题

java - json 和空值

java - JPA + Spring 异常后回滚事务

java - 读取模式时 Hibernate 配置错误

java - 我们必须关闭 session 对象吗?