Customer。hbm。xml中的配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!--
class:建立javabean和表之间的关系
name:对应的javabean的完整路径
table:表名
-->
<class name="cn.itcast.hibernate.domain.Customer" table="customer">
<!--
property:带映射的持久化类中属性
name:持久化类中属性名
type:property:name='name' name属性:customer类中是String
column name=“nmae” name字段名,customers表中是varchar
type:是hibernate中的数据类型 该数据类型是java类型和数据库中的类型的桥梁
column:持久化类中的属性对应的表中的字段
name:表示表中的字段名
-->
<id name="id" type="integer">
<!--
id:用于映射表的主键 配置主键生成策略 获取表中的最大值+1
-->
<column name="id"></column>
</id>
<property name="name" type="string">
<column name="name"></column>
</property>
<property name="age" type="integer">
<column name="age"></column>
</property>
<property name="des" type="text">
<column name="des"></column>
</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://hibernate.sourceforge.net/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://localhost:3306/hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1111</property>
<!-- 配置数据库方言 通过方言知道连接到那个数据库 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<mapping resource="cn/itcast/hibernate/domain/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
测试类
package cn.itcast.hibernate.domain;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class App {
public static void main(String[] args) {
/*
* 加载hibernate.cfg.xml映射文件
* 获取sessionFactory
* 获取session
* 开始事务
* 实例customer对象
* 保存
* 提交
* 关闭session
*/
//加载hibernate。cfg。xml文件
Configuration config=new Configuration();
config.configure();
/*
* 获取sessionFactory
* 利用config保存的信息创建SessionFactory
* SessionFactory 保存了连接数据库的信息和映射文件的配置信息 预定义sql语句
* SessionFactory是线程安全的 最后有一个SessionFactory
*/
SessionFactory sf=config.buildSessionFactory();
Session s=sf.openSession();
//开启事务
Transaction ts=s.beginTransaction();
//实例化Customer对象
Customer c=new Customer();
c.setName("liu");
c.setAge(23);
c.setDes("haoren");
c.setId(1);
//保存
s.save(c);
//提交
ts.commit();
s.close();
}
}