【Hibernate】搭建一个Hibernate环境,开发步骤

来源:互联网 发布:钢铁雄心3 知乎 编辑:程序博客网 时间:2024/04/27 23:06

搭建一个Hibernate环境,开发步骤:

1. 下载源码

版本:hibernate-distribution-3.6.0.Final

2. 引入jar文件

hibernate3.jar核心  +  required 必须引入的(6个) +  jpa 目录  + 数据库驱动包

3. 写对象以及对象的映射

Employee.java            对象

Employee.hbm.xml        对象的映射 (映射文件)

4. src/hibernate.cfg.xml  主配置文件

-à 数据库连接配置

-à 加载所用的映射(*.hbm.xml)

5. App.java  测试

Employee.java     对象

//一、 对象public class Employee {private int empId;private String empName;private Date workDate;}

Employee.hbm.xml  对象的映射

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="cn.lfsenior.a_hello"><class name="Employee" table="employee"><!-- 主键 ,映射--><id name="empId" column="id"><generator class="native"/></id><!-- 非主键,映射 --><property name="empName" column="empName"></property><property name="workDate" column="workDate"></property></class></hibernate-mapping>

hibernate.cfg.xml    主配置文件

<!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:///hib_demo</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><!-- 加载所有映射 --><mapping resource="cn/lfsenior/a_hello/Employee.hbm.xml"/></session-factory></hibernate-configuration>

App.java   测试类

public class App {@Testpublic void testHello() throws Exception {// 对象Employee emp = new Employee();emp.setEmpName("班长");emp.setWorkDate(new Date());// 获取加载配置文件的管理类对象Configuration config = new Configuration();config.configure();  // 默认加载src/hibenrate.cfg.xml文件// 创建session的工厂对象SessionFactory sf = config.buildSessionFactory();// 创建session (代表一个会话,与数据库连接的会话)Session session = sf.openSession();// 开启事务Transaction tx = session.beginTransaction();//保存-数据库session.save(emp);// 提交事务tx.commit();// 关闭session.close();sf.close();}}

原创粉丝点击