- 数据库和表
create database user_db;
user_db;
create table t_user(
id int auto_increment primary key,
username varchar(50),
password varchar(30)
);
- 编写核心配置文件
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!-- SessionFactory,相当于之前学习连接池配置 -->
<session-factory>
<!-- 1 基本4项 -->
<propertyname="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///h_day01_db</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1234</property>
<!-- 添加映射文件 -->
<mapping resource="com/test/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
-测试.
@Test
public void demo01(){
User user = new User();
user.setUsername("伟哥哥");
user.setPassword("1234");
//1 加载配置文件获得核心配置对象
Configuration config = new Configuration().configure();
//2 获得工厂 SessionFactory,相当于连接池
SessionFactory factory = config.buildSessionFactory();
//3获得会话session,相当于链接Connection
Session session = factory.openSession();
//4 开启事务
Transaction transaction = session.beginTransaction();
//操作
session.save(user);
//5 提交事务 | 回滚事务
transaction.commit();
//6 释放资源--关闭session
session.close();
//7 释放资源--关闭工厂factory
factory.close();
}