实体类:Employee.java
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;
}
@Override
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName + ", workDate=" + 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">
<!-- package:要映射的对象所在的包(可选) -->
<hibernate-mapping package="xxx">
<!--
class 映射某一个对象的(一般情况,一个对象写一个映射文件,即一个class节点)
name 指定要映射的对象的类型
table 指定对象对应的表;
如果没有指定表名,默认与对象名称一样
-->
<class name="Employee" table="employee">
<!-- 主键 ,映射-->
<id name="empId" column="empId">
<generator class="native"/>
</id>
<!--
普通字段映射
property
name 指定对象的属性名称
column 指定对象属性对应的表的字段名称,如果不写默认与对象属性一致。
length 指定字符的长度, 默认为255
type 指定映射表的字段的类型,如果不指定会匹配属性的类型
java类型: 必须写全名
hibernate类型: 直接写类型,都是小写
-->
<!-- 非主键,映射 -->
<property name="empName" column="empName"></property>
<property name="workDate" column="workDate"></property>
<!-- 如果列名称为数据库关键字,需要用反引号或改列名。 -->
<property name="desc" column="`desc`" type="java.lang.String"></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节点代表一个数据库 -->
<session-factory>
<!-- 1. 数据库连接配置 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!--
数据库方法配置, hibernate在运行的时候,会根据不同的方言生成符合当前数据库语法的sql
-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 2. 其他相关配置 -->
<!-- 2.1 显示hibernate在运行时候执行的sql语句 -->
<property name="hibernate.show_sql">true</property>
<!-- 2.2 格式化sql
<property name="hibernate.format_sql">true</property>
-->
<!-- 2.3 自动建表 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 3. 加载所有映射 -->
<mapping resource="a_hello/Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
工具类:hibernateUtils.java
public class HibernateUtils {
private static SessionFactory sf;
static {
// 加载主配置文件, 并创建Session的工厂
sf = new Configuration().configure().addClass(Employee.class).buildSessionFactory();
}
// 创建Session对象
public static Session getSession(){
return sf.openSession();
}
}
dao接口设计
IEmployeeDao.java
public interface IEmployeeDao {
void save(Employee emp);
void update(Employee emp);
Employee findById(Serializable id);
List<Employee> getAll();
List<Employee> getAll(String employeeName);
List<Employee> getAll(int index, int count);
void delete(Serializable id);
}
EmployeeDao.java
public class EmployeeDaoImpl implements IEmployeeDao{
@Override
public Employee findById(Serializable id) {
Session session = null;
Transaction tx = null;
try {
// 获取Session
session = HibernateUtils.getSession();
// 开启事务
tx = session.beginTransaction();
// 主键查询
return (Employee) session.get(Employee.class, id);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
tx.commit();
session.close();
}
}
@SuppressWarnings("unchecked")
@Override
public List<Employee> getAll() {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtils.getSession();
tx = session.beginTransaction();
// HQL查询
Query q = session.createQuery("from Employee");
return q.list();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
tx.commit();
session.close();
}
}
@SuppressWarnings("unchecked")
@Override
public List<Employee> getAll(String employeeName) {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtils.getSession();
tx = session.beginTransaction();
Query q =session.createQuery("from Employee where empName=?");
// 注意:参数索引从0开始
q.setParameter(0, employeeName);
// 执行查询
return q.list();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
tx.commit();
session.close();
}
}
@SuppressWarnings("unchecked")
@Override
public List<Employee> getAll(int index, int count) {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtils.getSession();
tx = session.beginTransaction();
Query q = session.createQuery("from Employee");
// 设置分页参数
q.setFirstResult(index); // 查询的其实行
q.setMaxResults(count); // 查询返回的行数
List<Employee> list = q.list();
return list;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
tx.commit();
session.close();
}
}
@Override
public void save(Employee emp) {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtils.getSession();
tx = session.beginTransaction();
// 执行保存操作
session.save(emp);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
tx.commit();
session.close();
}
}
@Override
public void update(Employee emp) {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtils.getSession();
tx = session.beginTransaction();
session.update(emp);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
tx.commit();
session.close();
}
}
@Override
public void delete(Serializable id) {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtils.getSession();
tx = session.beginTransaction();
// 先根据id查询对象,再判断删除
Object obj = session.get(Employee.class, id);
if (obj != null) {
session.delete(obj);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
tx.commit();
session.close();
}
}
}
实现类:App.java
public class App {
private EmployeeDaoImpl empDao = new EmployeeDaoImpl();
@Test
public void testFindById() {
System.out.println(empDao.findById(1));
}
@Test
public void testGetAll() {
System.out.println(empDao.getAll());
}
@Test
public void testGetAllString() {
System.out.println(empDao.getAll("3"));
}
@Test
public void testGetAllIntInt() {
System.out.println(empDao.getAll(4, 2));
}
@Test
public void testSave() {
empDao.save(new Employee());
}
@Test
public void testUpdate() {
Employee emp = new Employee();
emp.setEmpId(1);
emp.setEmpName("new jack");
empDao.update(emp);
}
@Test
public void testDelete() {
empDao.delete(23);
}
}
配置工具类:App_dll
public class App_ddl {
// 自动建表
@Test
public void testCreate() throws Exception {
// 创建配置管理类对象
Configuration config = new Configuration();
// 加载主配置文件
config.configure();
// 创建工具类对象
SchemaExport export = new SchemaExport(config);
// 建表
// 第一个参数: 是否在控制台打印建表语句
// 第二个参数: 是否执行脚本
export.create(true, true);
}
}