package hibernate_day01;
public class User {
private int uid;
private String username;
private String password;
private String address;
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
映射配置文件User.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="hibernate_day01.User" table="t_user">
<id name="uid" column="uid">
<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>
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操作过程中,只会加载核心配置文件,其他文件不会加载 -->
<hibernate-configuration>
<session-factory>
<!-- 第一部分:配置数据库信息 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///user?characterEncoding=utf-8</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<!-- 第二部分:配置hibernate信息 -->
<property name="hibernate.show_sql ">true</property>
<property name="hibernate.format_sql ">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 第三部分:把映射文件放到核心配置文件中 -->
<mapping resource="hibernate_day01/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
测试代码:
package hibernate.test;
import hibernate_day01.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
public class HibernateTest {
@Test
public void add(){
//第一步 加载hibernate核心配置文件
Configuration cfg = new Configuration();
cfg.configure();
//第二步 创建SessionFactory对象
SessionFactory sessionFactory = cfg.buildSessionFactory();
//第三步 使用SessionFactory创建session对象
Session session = sessionFactory.openSession();
//第四步 开启事务
Transaction transaction = session.beginTransaction();
//第五步 写具体逻辑 crud操作
User user = new User();
user.setUsername("咘咘");
user.setPassword("123456");
user.setAddress("台北");
session.save(user);
//第六步 提交事务
transaction.commit();
//第七步 关闭资源
session.close();
sessionFactory.close();
}
}