在Hibernate中如何实现DAO模型(笔记)
首先,我们来看下目录结构
接下来,我们看下具体的代码实现:
UserDAO.java的代码如下:
- package cn.javass.h4.crud.dao.dao;
- import java.util.List;
- import cn.javass.h4.vo.UserModel;
- import cn.javass.h4.vo.UserQueryModel;
- public interface UserDAO {
- public void create(UserModel um);
- public void update(UserModel um);
- public void delete(UserModel um);
- public UserModel getByUuid(String uuid);
- public List<UserModel> getAll();
- public List<UserModel> getByCondition(UserQueryModel uqm);
- }
建立一个接口类型的DAO模型,用来定义我们将来要实现的具体功能。它的具体实现方法通过UserImpl来实现。具体如下:
- package cn.javass.h4.crud.dao.impl;
- import java.util.ArrayList;
- import java.util.List;
- import org.hibernate.Query;
- import org.hibernate.Session;
- import org.hibernate.Transaction;
- import cn.javass.h4.crud.dao.dao.UserDAO;
- import cn.javass.h4.crud.util.H4Util;
- import cn.javass.h4.vo.UserModel;
- import cn.javass.h4.vo.UserQueryModel;
- public class H4Impl implements UserDAO {
- @Override
- public void create(UserModel um) {
- Session s = null;
- Transaction t = null;
- try {
- s = H4Util.getSF().openSession();
- t = s.beginTransaction();
- s.save(um);
- t.commit();
- } catch (Exception e) {
- e.printStackTrace();
- t.rollback();
- } finally {
- s.close();
- }
- }
- @Override
- public void update(UserModel um) {
- Session s = null;
- Transaction t = null;
- try {
- s = H4Util.getSF().openSession();
- t = s.beginTransaction();
- s.update(um);
- t.commit();
- } catch (Exception e) {
- e.printStackTrace();
- t.rollback();
- } finally {
- s.close();
- }
- }
- @Override
- public void delete(UserModel um) {
- Session s = null;
- Transaction t = null;
- try {
- s = H4Util.getSF().openSession();
- t = s.beginTransaction();
- s.delete(um);
- t.commit();
- } catch (Exception e) {
- e.printStackTrace();
- t.rollback();
- } finally {
- s.close();
- }
- }
- @Override
- public UserModel getByUuid(String uuid) {
- UserModel um = null;
- Session s = null;
- Transaction t = null;
- try {
- s = H4Util.getSF().openSession();
- t = s.beginTransaction();
- um = (UserModel) s.load(UserModel.class, uuid);
- t.commit();
- } catch (Exception e) {
- e.printStackTrace();
- t.rollback();
- } finally {
- s.close();
- }
- return um;
- }
- @Override
- public List<UserModel> getAll() {
- List<UserModel> list = new ArrayList<UserModel>();
- Session s = null;
- Transaction t = null;
- try {
- s = H4Util.getSF().openSession();
- t = s.beginTransaction();
- Query q = s.createQuery("select o from UserModel o");
- list = q.list();
- t.commit();
- } catch (Exception e) {
- e.printStackTrace();
- t.rollback();
- } finally {
- s.close();
- }
- return list;
- }
- @Override
- public List<UserModel> getByCondition(UserQueryModel uqm) {
- List<UserModel> list = new ArrayList<UserModel>();
- Session s = null;
- Transaction t = null;
- try {
- s = H4Util.getSF().openSession();
- t = s.beginTransaction();
- String hql = "select o from UserModel o where 1=1 ";
- hql = this.preparedHql(hql, uqm);
- Query q = s.createQuery(hql);
- this.setHqlValue(q, uqm);
- list = q.list();
- t.commit();
- } catch (Exception e) {
- e.printStackTrace();
- t.rollback();
- } finally {
- s.close();
- }
- return list;
- }
- private void setHqlValue(Query q, UserQueryModel uqm) {
- if (uqm.getUuid() != null && uqm.getUuid().trim().length() > 0) {
- q.setString("uuid", uqm.getUuid());
- }
- if (uqm.getName() != null && uqm.getName().trim().length() > 0) {
- q.setString("name", "%" + uqm.getName() + "%");
- }
- if (uqm.getAge() > 0) {
- q.setInteger("age", uqm.getAge());
- }
- if (uqm.getAge2() > 0) {
- q.setInteger("age2", uqm.getAge2());
- }
- }
- private String preparedHql(String hql, UserQueryModel uqm) {
- StringBuffer buffer = new StringBuffer(hql);
- if (uqm.getUuid() != null && uqm.getUuid().trim().length() > 0) {
- buffer.append(" and o.uuid = :uuid");
- }
- if (uqm.getName() != null && uqm.getName().trim().length() > 0) {
- buffer.append(" and o.name like :name");
- }
- if (uqm.getAge() > 0) {
- buffer.append(" and o.age >= :age");
- }
- if (uqm.getAge2() > 0) {
- buffer.append(" and o.age <= :age2");
- }
- return buffer.toString();
- }
- }
然后建立一个工厂UserDAOFactory,方便外部程序的调用。具体代码如下:
- package cn.javass.h4.crud.dao.factory;
- import cn.javass.h4.crud.dao.dao.UserDAO;
- import cn.javass.h4.crud.dao.impl.H4Impl;
- public class UserDAOFactory {
- private UserDAOFactory(){
- }
- public static UserDAO getUserDAO(){
- return new H4Impl();
- }
- }
这个时候我们就初步的实现了DAO模型,当然这里忘记了UserModel、UserQueryModel以及相对应的ORMapping文件
UserModel:
- package cn.javass.h4.vo;
- public class UserModel implements java.io.Serializable {
- private String uuid;
- private int age;
- private int version;
- private String name;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getVersion() {
- return version;
- }
- public void setVersion(int version) {
- this.version = version;
- }
- public String getUuid() {
- return uuid;
- }
- public void setUuid(String uuid) {
- this.uuid = uuid;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((uuid == null) ? 0 : uuid.hashCode());
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- UserModel other = (UserModel) obj;
- if (uuid == null) {
- if (other.uuid != null)
- return false;
- } else if (!uuid.equals(other.uuid))
- return false;
- return true;
- }
- public String toString() {
- return "uuid=" + uuid + ", name=" + name + ", age=" + age;
- }
- }
UserQueryModel:
- package cn.javass.h4.vo;
- public class UserQueryModel extends UserModel{
- private int age2 = 0;
- public int getAge2() {
- return age2;
- }
- public void setAge2(int age2) {
- this.age2 = age2;
- }
- }
UserModel对应的Mapping文件UserModel.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>
- <class name="cn.javass.h4.vo.UserModel" table="user_tbl" lazy="false">
- <id name="uuid">
- <generator class="assigned"/>
- </id>
- <!--
- <version name="version" column="version"/>
- -->
- <property name="name" />
- <property name="age"/>
- </class>
- </hibernate-mapping>
这里最后在补上SRC文件根目录下的hibernate.cfg.xml的配置文件
- <?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>
- <!-- Database connection settings -->
- <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
- <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
- <property name="connection.username">root</property>
- <property name="connection.password">root</property>
- <!-- JDBC connection pool (use the built-in) -->
- <property name="connection.pool_size">1</property>
- <property name="c3p0.mix_size">5</property>
- <property name="c3p0.max_size">20</property>
- <property name="cep0.timeout">180</property>
- <property name="c3p9.max_statements">50</property>
- <!-- SQL dialect -->
- <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
- <!-- Echo all executed SQL to stdout -->
- <property name="show_sql">true</property>
- <property name="format_sql">true</property>
- <mapping resource="cn/javass/h4/vo/UserModel.hbm.xml"/>
- </session-factory>
- </hibernate-configuration>
关于相关的LIB文件以及对应的数据库表就不写了。
下面写个Client类对相关的东西进行测试
- package cn.javass.h4.crud;
- import java.util.List;
- import org.hibernate.Query;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.hibernate.cfg.Configuration;
- import cn.javass.h4.crud.dao.factory.UserDAOFactory;
- import cn.javass.h4.vo.UserModel;
- import cn.javass.h4.vo.UserQueryModel;
- public class Client {
- public static void main(String[] args) {
- //测试新增
- // UserModel um = new UserModel();
- // um.setUuid("04");
- // um.setAge(1);
- // um.setName("ccc");
- // UserDAOFactory.getUserDAO().create(um);
- //测试update
- // UserModel um = new UserModel();
- // um.setUuid("01");
- // um.setName("adf");
- // um.setAge(1);
- // UserDAOFactory.getUserDAO().update(um);
- //测试delete
- // UserModel um = new UserModel();
- // um.setUuid("01");
- // UserDAOFactory.getUserDAO().delete(um);
- //测试getByUuid
- //这里特别注意下!!!!!
- //如果UserModel.hbm.xml中lazy="false",没有添加的话,会抛出异常
- // UserModel um = UserDAOFactory.getUserDAO().getByUuid("02");
- // System.out.println(um);
- //测试获取全部数据
- // List<UserModel> list = UserDAOFactory.getUserDAO().getAll();
- // for (UserModel um : list){
- // System.out.println("um==" + um);
- // }
- //测试精确查询
- // UserQueryModel uqm = new UserQueryModel();
- // uqm.setUuid("02");
- // List<UserModel> list = UserDAOFactory.getUserDAO().getByCondition(uqm);
- // for (UserModel um : list){
- // System.out.println("um==" + um);
- // }
- //模糊查询
- // UserQueryModel uqm = new UserQueryModel();
- // uqm.setName("b");
- // List<UserModel> list = UserDAOFactory.getUserDAO().getByCondition(uqm);
- // for (UserModel um : list){
- // System.out.println("um==" + um);
- // }
- //测试年龄的区间查询
- // UserQueryModel uqm = new UserQueryModel();
- // uqm.setAge(15);
- // uqm.setAge2(40);
- // List<UserModel> list = UserDAOFactory.getUserDAO().getByCondition(uqm);
- // for (UserModel um : list){
- // System.out.println("um==" + um);
- // }
- }
- }