使用Hibernate中的Criteria来写一个简单的例子,例子中有三个类,分别是Student、Teacher、JavaTest三了类,其中teacher和student是一对多的关系。
首先列出需要的Jar文件:
然后是最基础的hibernate.cfg.xml配置文件:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/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/magic</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- SQL 方言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 显示SQL语句 -->
<property name="show_sql">true</property>
<!-- 使用本地事物(JDBC事物) -->
<property name="current_session_context_class">thread</property>
<!-- 自动生成表 -->
<property name="hbm2ddl.auto">update</property>
<!-- 配置实体类的映射 -->
<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<Student> 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<Student> 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<Student> 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
踏实一些,不要着急,你想要的,岁月都会给你。