开发环境搭建
- hibernate环境下载https://sourceforge.net/projects/hibernate/files/hibernate-orm/5.0.7.Final/hibernate-release-5.0.7.Final.zip/download
- 将必须的jar包导入到项目中 将目录 hibernate-release-5.0.7.Final\lib\required 下的所有jar包导入到项目中,导入log4j相关的jar包,以及数据库驱动包
- 编写配置文件
a. 编写核心配置文件 hibernate.cfg.xml
b.编写映射配置文件 实体名.hbm.xml
配置文件编写
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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="cn/wcl/pojo/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
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="cn.wcl.pojo.User" table="user">
<id name="uid" column="uid">
<generator class="native"></generator>
</id>
<property name="uname" column="uname"></property>
<property name="ugender" column="ugender"></property>
<property name="upwd" column="upwd"></property>
</class>
</hibernate-mapping>
测试代码
public class Demo_01 {
/**
* 增加
*/
@Test
public void run1(){
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction ts = session.beginTransaction();
User user = new User();
user.setUname("jack");
user.setUgender("男");
user.setUpwd("123456");
Serializable id = session.save(user);
System.out.println(id);
ts.commit();
session.close();
factory.close();
}
/**
* 查询get()/load()
*/
@Test
public void run2(){
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction ts = session.beginTransaction();
User user = session.get(User.class, 1L);
System.out.println(user);
ts.commit();
session.close();
factory.close();
}