import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final ThreadLocal<Session> lock = new ThreadLocal<Session>();
private static final SessionFactory factory = buildFactory();
private static SessionFactory buildFactory() {
Configuration cfg = new Configuration().configure();
return cfg.buildSessionFactory();
}
public static Session getSession() {
Session session = lock.get();
if (session == null) {
session = factory.openSession();
lock.set(session);
}
return session;
}
public static void closeSession() {
Session session = lock.get();
if (session != null) {
session.close();
lock.set(null);
}
}
}
配置
<?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>
实现
import java.util.List;
import org.hibernate.*;
import com.itnba.maya.model.Toy;
import com.itnba.maya.model.HibernateUtil;
public class toy {
public static void main(String[] args) {
Fruit data = new Fruit();
data.setIds("001");
data.setName("car");
data.setSource("unknow");
data.setPrice(998);
data.setNumbers(100);
data.setImage("null");
Session session=null;
try{
session=HibernateUtil.getSession();
session.beginTransaction();
session.save(data);
session.getTransaction().commit();
}catch (Exception e) {
session.getTransaction().rollback();
}finally {
HibernateUtil.closeSession();
}
}
}