单例模式的SessionFactory
在这个工具类Hibernate.java中写一个通过静态代码块生成唯一的SessionFactory,通过一个方法返回一个SessionFactory
import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static Configuration cfg; private static SessionFactory sessionFactory; static { try { cfg = new Configuration().configure(); sessionFactory = cfg.buildSessionFactory(); }catch (Exception e) { e.printStackTrace(); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }
线程安全的session
一、获取session
在学习中已经知道有两种方法可以获取session
1.openSession()
2.getCurrentSession()
在这里,这两种方法的区别:
采用getCurrentSession()创建的Session会绑定到当前的线程中去、而采用OpenSession()则不会。
采用getCurrentSession()创建的Session在commit或rollback后会自动关闭,采用OpenSession()必须手动关闭。
二、这里使用线程安全的Session
Configuration configuration = new Configuration.configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.getCurrentSession()
三、演示实例
1.User类及配置
package com.domain; public class User { private Integer id; private String username; private String password; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + ", age=" + age + "]"; } }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <!-- name: 完整类名 table:数据库表名 --> <class name="com.domain.User" table="user"> <!-- id配置表的主键 name代表表中属性 --> <id name="id" column="id"> <!-- 主键生成策略 --> <generator class="native"></generator> </id> <property name="username" column="username" type="string"></property> <property name="password" column="password" type="string"></property> <property name="age" column="age" type="integer"></property> </class> </hibernate-mapping>
2.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> <!-- 指定方言 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 数据库驱动 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 数据库url --> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate02_1514010311</property> <!-- 数据库连接用户名 --> <property name="hibernate.connection.username">root</property> <!-- 数据库连接密码 --> <property name="hibernate.connection.password">0x3137</property> <!-- 将hibernate生成的sql语句打印到控制台 --> <property name="hibernate.show_sql">true</property> <!-- 将hibernate生成的sql语句格式化(语法缩进) --> <property name="hibernate.format_sql">true</property> <!-- 配置getCurrentSession --> <property name="hibernate.current_session_context_class">thread</property> <mapping resource="com/domain/User.hbm.xml" /> </session-factory> </hibernate-configuration>
3.HibernateUtil.java
package com.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static Configuration cfg;
private static SessionFactory sessionFactory;
static {
try {
cfg = new Configuration().configure();
sessionFactory = cfg.buildSessionFactory();
}catch (Exception e) {
e.printStackTrace();
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
4.测试
package com.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;
import com.domain.User;
import com.util.HibernateUtil;
public class TestUser {
@Test
public void saveUser() {
SessionFactory sessionFactory = null;
Session session = null;
Transaction transaction = null;
User user = new User();
user.setUsername("三哥无邪");
user.setPassword("1514010311");
user.setAge(21);
try {
sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.getCurrentSession();
transaction = session.beginTransaction();
session.save(user);
transaction.commit();
} catch (Exception e) {
if (transaction!=null) {
transaction.rollback();
}
e.printStackTrace();
}
}
@Test
public void updateUser() {
SessionFactory sessionFactory = null;
Session session = null;
Transaction transaction = null;
try {
sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.getCurrentSession();
transaction = session.beginTransaction();
User user = session.get(User.class, 1);
user.setUsername("三哥无邪啊");
user.setPassword("1514010311");
user.setAge(21);
session.update(user);
transaction.commit();
} catch (Exception e) {
if (transaction!=null) {
transaction.rollback();
}
e.printStackTrace();
}
}
@Test
public void queryUser() {
SessionFactory sessionFactory = null;
Session session = null;
Transaction transaction = null;
try {
sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.getCurrentSession();
transaction = session.beginTransaction();
User user = session.get(User.class, 2);
System.out.println("ID:"+user.getId()+" 用户名:"+user.getUsername()+" 密码:"+user.getPassword());
transaction.commit();
} catch (Exception e) {
if (transaction!=null) {
transaction.rollback();
}
e.printStackTrace();
}
}
@Test
public void deleteUser() {
SessionFactory sessionFactory = null;
Session session = null;
Transaction transaction = null;
try {
sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.getCurrentSession();
transaction = session.beginTransaction();
User user = session.get(User.class, 1);
session.delete(user);
transaction.commit();
} catch (Exception e) {
if (transaction!=null) {
transaction.rollback();
}
e.printStackTrace();
}
}
}
测试saveUser方法