Hibernate HelloWorld案例
搭建一个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
package com.xuli.test;
public class Employee {
//一.对象
private int empId;
private String empName;
private String data;
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 String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
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="com.xuli.test">
<!-- 主键,映射 -->
<class name="Employee" table="employee">
<id name = "empId" column="id">
<generator class="assigned"/>
</id>
<!-- 非主键,映射 -->
<property name="empName" column="empName"></property>
<property name="data" column="workDate"></property>
</class>
</hibernate-mapping>
Employee.hbm.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="com/xuli/test/Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
测试类
<!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="com/xuli/test/Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>