一、SessionFactory作用?
应用程序从sessionFactory中获得session实例,它在多个应用线程之间进行共享。
sessionFactory是线程安全的,可以让多个执行线程同时存取sessionFactory而不会有数据共享问题。
sessionFactory缓存了生成的SQL语句和Hibernate在运行时使用的映射元数据。
一般情况下,一个项目通常只需要一个sessionFactory就够(单例模式),当需要操作多个数据库时,可以为每个数据库指定一个sessionFactory。
创建一个对象并配置
public class User {
private int id;
private String name;
private int age;
public User() {
}
public User( String name, int age) {
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.allwinter.pojo">
<class name="User" table="t_user">
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="name" column="name"/>
<property name="age" column="age"/>
</class>
</hibernate-mapping>
单例模式创建SessionFactory
package com.allwinter.utils;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionfactory;
static {
try{
//实例化SessionFactory;
sessionfactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable e){
System.err.println("SessionFactory 创建失败!" + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionfactory(){
return sessionfactory;
}
}
测试查询
Query<User> query = session.createQuery("from User");
List<User> resultList = query.getResultList();
resultList.forEach(System.out::println);
结果