1 加载相应的jar包
2创建和数据库对应的Java实体类
3创建Hibernate的核心配置类
<?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_test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 是否显示sql语句 -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- hibernate 的hbm2ddl(数据定义语言) -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- hibernate 加载映射 -->
<mapping resource="cn./itcast/domain/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
4 在实体类包中创建对应的映射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属性类中的全路经
table 属性 表名(如果类名和表明试一致的那么他变了书香客户省略)
catalog 数据库名称,可以省略-->
<class name="cn.itcast.domain.Customer" table="cst_customer">
<id name="cust_id" column="cust_id">
<!-- 主键生成策略 -->
<generator class="native"/>
</id>
<property name="cust_name" column="cust_name"/>
<property name="cust_source" column="cust_source"/>
<property name="cust_industry" column="cust_industry"/>
<property name="cust_phone" column="cust_phone"/>
<property name="cust_mobile" column="cust_mobile"/>
</class>
</hibernate-mapping>
5,编写使用类
package cn.itcast.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import cn.itcast.domain.Customer;
public class HibernateDemo {
public void demo() {
//加载配置文件
Configuration cfg=new Configuration().configure();
//创建一个sessionFactory
SessionFactory sessionFactory=cfg.buildSessionFactory();
//创建Session对象,Session对象 类似Connection
Session session=sessionFactory.openSession();
//开启事务
Transaction tx=session.beginTransaction();
//操作
Customer customer=new Customer();
customer.setCust_name("王耀爽");
customer.setCust_source("网络推荐");
session.save(customer);
//事务提交
tx.commit();
//释放资源
session.close();
}
}
过程含义:首先创建Configuration类的实例,并通过它来读取配置文件hibernate.cfg.xml文件,然后创建SessionFactory读取解析映射文件信息,并将Configuration对象中的所有的配置信息拷贝至session factory的内存中,接下来,打开session让sessionfactory提供连接,并开启一个事务之后,创建对象,向对象中添加数据,通过session。save()方法完成向数据库中保存数据的操作,然后提交事务,并关闭资源。