2016-05-23 158 views
1

我正在嘗試使用條件在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"));

我如何能實現使用相同的一對多方式上述要求?

期待您的解決方案。 在此先感謝。

+0

你問如何創建一個標準的查詢與加入?如果是這樣,也許http://stackoverflow.com/questions/3424696/jpa-criteria-api-how-to-add-join-clause-as-general-sentence-as-possible –

+0

感謝您的答覆。但是onomanomany只是在做連接。我只想使用學生姓名 – Roy

回答

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(); 
+0

篩選加入查詢的結果感謝FaNaj的快速回復。執行時出現異常:線程「main」中的異常org.hibernate.QueryException:無法解析屬性:名稱:com.hibernate.onetomany.College和我傳遞的限制是:Criteria cr = session.createCriteria (College.class)。新增(限制。eq(「name」,「Linda Berry」)); – Roy

+0

我能夠運行您建議的上述示例。但我沒有得到具體的結果。 – Roy

+0

@羅伊不客氣。請看更新。 – FaNaJ