Hibernate中Criteria查询简单例子新手上路第一案例

使用Hibernate中的Criteria来写一个简单的例子,例子中有三个类,分别是Student、Teacher、JavaTest三了类,其中teacher和student是一对多的关系。

首先列出需要的Jar文件:

Hibernate中Criteria查询简单例子新手上路第一案例_第1张图片

然后是最基础的hibernate.cfg.xml配置文件:



<hibernate-configuration>
    <session-factory>
        
        <property name="connection.driver_class">com.mysql.jdbc.Driverproperty>
        <property name="connection.url">jdbc:mysql://localhost/magicproperty>
        <property name="connection.username">rootproperty>
        <property name="connection.password">rootproperty>
        
        <property name="dialect">org.hibernate.dialect.MySQLDialectproperty>
        
        <property name="show_sql">trueproperty>
        
        <property name="current_session_context_class">threadproperty>
        
        <property name="hbm2ddl.auto">updateproperty>
        
        <mapping class="com.model.Student"/>
        <mapping class="com.model.Teacher"/>
    session-factory>
hibernate-configuration>

我写了一个HibernateUtil工具类,该工具类主要用于创建Session :

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory(){
        try{
            Configuration config = new Configuration().configure();
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
            return config.buildSessionFactory(serviceRegistry);
        }catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    // 该方法获取的是一个Session工厂
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    // 该方法过去的是一个Session
    public static Session getSession(){
        return sessionFactory.getCurrentSession();
    }
}

下面是两个实体类的代码:

package com.model;

import javax.persistence.*;

@Entity
@Table(name = "t_student")
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private String stuName;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "teacherId")
    private Teacher myTeacher; // 在学生类中持有老师的对象,即many方只有one方的对象;

    // 省略 getter和setter
}
package com.model;

import org.hibernate.annotations.Fetch;
import javax.persistence.*;
import java.util.List;

@Entity
@Table(name = "t_teacher")
public class Teacher {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private  int id;

    private String tchName;

    //@OneToMany(mapped=“由One的一方指向Many的一方,并且,这个属性应该等于Many的一方中含有One类的属性的属性名,否则会出错啦 ”)
    @OneToMany(cascade = CascadeType.ALL,mappedBy = "myTeacher" )
    private List students;  // 老师类中持有学生类的集合 , 即one方持有many方的集合

    // 省略 getter和setter
}

最后就是测试类了:

package com.text;

import com.model.MyUser;
import com.model.Student;
import com.model.Teacher;
import com.util.HibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import java.util.Iterator;
import java.util.List;

public class JavaTest {
    public static void main(String[] args) throws Exception{
        save();
//      getStudents();
//      getStudentsByName();

    }

    public static void save(){
        Session session = HibernateUtil.getSession();
        Transaction tx = session.beginTransaction();
        Teacher t = new Teacher();
        t.setTchName("guangTouQiang");

        Student s1 = new Student();
        s1.setStuName("xiongDa");
        s1.setTeacher(t);
        session.save(s1);

        Student s2 = new Student();
        s2.setStuName("xiongEr");
        s2.setTeacher(t);
        session.save(s2);

        tx.commit();

    }

    public static void getStudents(){
        Session session = HibernateUtil.getSession();
        session.beginTransaction();

        Criteria criteria = session.createCriteria(Student.class,"s");
        List list = criteria.list();

        Iterator iterator = list.iterator();
        while(iterator.hasNext()){
            Student s  = iterator.next();
            System.out.println( s.getId()+"***"+ s.getStuName()+"***"+s.getTeacher().getTchName());
        }
    }

    public static void getStudentsByName(){
        Session session = HibernateUtil.getSession();
        session.beginTransaction();
        Criteria criteria = session.createCriteria(Student.class);
        // 精准查询
        List list = criteria.add(Restrictions.eq("stuName","xiongDa")).list();
        //模糊查询
      //List list = criteria.add(Restrictions.like("stuName","xiong%")).list();
        Iterator iterator = list.iterator();
        while(iterator.hasNext()){
            Student s  = iterator.next();
            System.out.println( s.getId()+"***"+ s.getStuName()+"***"+s.getTeacher().getTchName());
        }
    }
}

关于更过Criteria高级查询用法,请参见:http://blog.csdn.net/qq_28082757/article/details/68938941

踏实一些,不要着急,你想要的,岁月都会给你。

你可能感兴趣的:(Hibernate)