1、创建实体类
public class User {
private int uid;
private String username;
private String password;
private String address;
//省略get和set方法
}
2、创建实体类配置文件
该配置文件命名规范是实体类名+hbm.xml
该文件存放的位置是任意的,
<?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>
<class name="com.winney.entiity.User" table="t_user">
<id name="uid" column="uid">
<!-- 该id作为主键并且自增加1 -->
<generator class="native"></generator>
</id>
<property name="username" column="username"></property>
<property name="password" column="password"></property>
<property name="address" column="address"></property>
</class>
</hibernate-mapping>
3、创建核心配置文件
主要是配置数据库信息、配置hibernate信息以及实体类配置文件的配置
该文件的命名是固定的:hibernate.cfg.xml,文件的路径是固定放在src下:
<?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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///hibernate_db</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!-- 配置hibernate信息 -->
<property name="hibernate.show_sql">true</property>
<property name="hibernare.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 把映射文件放到核心配置文件中 -->
<mapping resource="com/winney/entiity/user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
4、实现过程:
package com.winney.hibernateTest;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import com.winney.entiity.User;
public class UserTest {
@Test
public void testAdd() {
// 1、加载hibernate核心文件
Configuration cfg = new Configuration();
cfg.configure();
// 2、创建SessionFactory对象
SessionFactory sessionFactory = cfg.buildSessionFactory();
//3、创建session
Session session = sessionFactory.openSession();
// 4、开启事务
Transaction ts = session.beginTransaction();
// 5、进行crud操作
User user = new User();
user.setUsername("wuzilong");
user.setPassword("123456");
user.setAddress("GZ");
session.save(user);
// 6、提交事务
ts.commit();
// 7、关闭资源
session.close();
sessionFactory.close();
}
}