案例分析
1.引入jar包
hibernate3.jar + required + jpa目录 + 数据库驱动包
2.写对象以及对象的映射
对象.java
package com.cx.hello; import java.util.Date; /** * Created by cxspace on 16-7-16. */ public class Employee { private int empId; private String empName; private Date workDate; public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public Date getWorkDate() { return workDate; } public void setWorkDate(Date workDate) { this.workDate = workDate; } }
对象.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="com.cx.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>
3.src/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:///learnstruts</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">33269456.cx</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <!--加载所有映射--> <mapping resource="com/cx/hello/Employee.hbm.xml"></mapping> </session-factory> </hibernate-configuration>
测试类
package com.cx.hello; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.junit.Test; import java.util.Date; /** * Created by cxspace on 16-7-16. */ public class App { @Test public void testHello() { //对象 Employee emp = new Employee(); emp.setEmpName("小华"); emp.setWorkDate(new Date()); //获取加载配置文件的管理类对象 Configuration config = new Configuration(); config.configure(); //加载主配置文件 // 创建session的工厂对象 SessionFactory sf = config.buildSessionFactory(); //创建session,代表与数据库连接的会话 Session session = sf.openSession(); //开启事务 Transaction tx = session.beginTransaction(); //保存-数据库 session.save(emp); //提交事物 tx.commit(); //关闭 session.close(); sf.close(); } }