码迷,mamicode.com
首页 > 其他好文 > 详细

SSH系列:(7)编写通用Dao

时间:2016-08-08 19:31:49      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:ssh


因为这里写的是通用Dao功能,因此将它放置到core包里面。

技术分享


1、定义通用Dao中的方法


BaseDao.java

package com.rk.core.dao;

import java.io.Serializable;
import java.util.List;


public interface BaseDao<T> {
	void save(T entity);
	void update(T entity);
	void delete(Serializable id);
	T findById(Serializable id);
	List<T> findAll();
}



2、通用Dao的实现


需要注意的地方:

(1)BaseDaoImpl类继承自HibernateDaoSupport类,并实现了BaseDao接口

(2)在BaseDaoImpl构造方法中,我们通过反射获取了泛型T的真实类型

(3)在delete方法中,我们通过调用HibernateConfigurationUtils类的方法来获得实体类的主键属性。HibernateConfigurationUtils是一个自定义的类。


HibernateDaoSupport类


1、HibernateDaoSupport介绍


我们使用Hibernate进行数据库的访问,访问数据库的这一层代码称为DAO层。

spring帮开发者封装了一个HibernateDaoSupport类(位于org.springframework.orm.hibernate3.support包下),该类提供了获取HibernateTemplate的方法,而HibernateTemplate对象可以方便的进行数据库的CRUD操作,因此我们自己写的Dao层的代码可以继承HibernateDaoSupport类。


2、如何使用HibernateDaoSupport类?

这里有一个前提要注意一下:我们是Spring和Hibernate整合的情况下使用HibernateDaoSupport。

首先,我们需要为HibernateDaoSupport类提供一个SessionFactory对象。

其次,我们可以通过调用HibernateDaoSupport类的getHibernateTemplate()方法得到一个HibernateTemplate对象。

最后,我们使用HibernateTemplate对象进行数据库操作。


假设我们最终会写一个UserDaoImpl类,那么UserDaoImpl类继承自BaseDaoImpl类,而BaseDaoImpl类继承自HibernateDaoSupport类。



Convenient super class for Hibernate-based data access objects.


Requires a SessionFactory to be set, providing a HibernateTemplate based on it to subclasses through the getHibernateTemplate() method.  





BaseDaoImpl.java

package com.rk.core.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.rk.core.dao.BaseDao;
import com.rk.core.utils.HibernateConfigurationUtils;

public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {

	private Class<T> clazz;
	
	@SuppressWarnings("unchecked")
	public BaseDaoImpl() {
		ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
		Type[] args = pt.getActualTypeArguments();
		this.clazz = (Class<T>) args[0];
	}
	
	public void save(T entity) {
		getHibernateTemplate().save(entity);
	}

	public void update(T entity) {
		getHibernateTemplate().update(entity);
	}

	public void delete(Serializable id) {
		String identifierPropertyName = HibernateConfigurationUtils.getIdentifierPropertyName(clazz);
		Session session = getSession();
		session.createQuery("delete from " + clazz.getSimpleName() + " where " + identifierPropertyName + "=?")
			   .setParameter(0, id).executeUpdate();
	}

	public T findById(Serializable id) {
		return getHibernateTemplate().get(clazz, id);
	}

	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		Session session = getSession();
		Query query = session.createQuery("from " + clazz.getSimpleName());
		return query.list();
	}

}





3、HibernateConfigurationUtils


主键属性,通过反射来获取 

ApplicationContext对象-->Configuration对象-->PersistentClass对象-->获取类的主键属性


需要注意的是:

(1)HibernateConfigurationUtils 实现了 ApplicationContextAware 接口;ApplicationContextAware接口是位于org.springframework.context包下。

(2)HibernateConfigurationUtils类需要在bean-core.xml文件中进行注册,而bean-core.xml需要引入到applicationContext.xml文件中。

<bean class="com.rk.core.utils.HibernateConfigurationUtils"></bean>




ApplicationContextAware接口的定义如下:

package org.springframework.context;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.Aware;


public interface ApplicationContextAware extends Aware
{

    public abstract void setApplicationContext(ApplicationContext applicationcontext)
        throws BeansException;
}


我们可以看到ApplicationContextAware接口只有一个方法,它的作用是:让实现了ApplicationContextAware接口的类能够访问到ApplicationContext对象。

Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.





HibernateConfigurationUtils.java

package com.rk.core.utils;

import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.PersistentClass;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;

public class HibernateConfigurationUtils implements ApplicationContextAware {
    // 1、ApplicationContext对象
    private static ApplicationContext applicationContext;
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        HibernateConfigurationUtils.applicationContext = applicationContext;
    }
     
    // 2、Configuration对象
    private static Configuration configuration;
    public static Configuration getConfiguration()
    {
        if(configuration == null)
        {
            // 取sessionFactory的时候要加上&  
            LocalSessionFactoryBean factory = (LocalSessionFactoryBean) applicationContext.getBean("&sessionFactory");
            configuration = factory.getConfiguration();
        }
        return configuration;
    }
    public static void setConfiguration(Configuration configuration)
    {
        HibernateConfigurationUtils.configuration = configuration;
    }
 
    // 3、PersistentClass对象
    private static <T> PersistentClass getPersistentClass(Class<T> clazz)
    {
        synchronized(HibernateConfigurationUtils.class)
        {
            PersistentClass pc = getConfiguration().getClassMapping(clazz.getSimpleName());
            if(pc == null)
            {
                configuration = configuration.addClass(clazz);
                pc = configuration.getClassMapping(clazz.getName());
            }
            return pc;
        }
    }
     
    // 4、获取映射信息
    // 4.1、获取类信息-主键属性
    public static <T> String getIdentifierPropertyName(Class<T> clazz)
    {
        return getPersistentClass(clazz).getIdentifierProperty().getName();
    }


}



4、使用通用Dao


User.java

package com.rk.tax.entity;

import java.util.Date;

public class User {
	private String id;
	private String dept;
	private String account;
	private String name;
	private String password;
	
	private String headImg;
	private boolean gender;
	private String state;
	private String mobile;
	private String email;
	private Date birthday;
	private String memo;
	
	//用户状态
	public static String USER_STATE_VALID = "1";//有效
	public static String USER_STATE_INVALID = "0";//无效
	public User() {
	}
	public User(String id, String dept, String account, String name,
			String password, String headImg, boolean gender, String state,
			String mobile, String email, Date birthday, String memo) {
		this.id = id;
		this.dept = dept;
		this.account = account;
		this.name = name;
		this.password = password;
		this.headImg = headImg;
		this.gender = gender;
		this.state = state;
		this.mobile = mobile;
		this.email = email;
		this.birthday = birthday;
		this.memo = memo;
	}
	// {{ Properties
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getDept() {
		return dept;
	}
	public void setDept(String dept) {
		this.dept = dept;
	}
	public String getAccount() {
		return account;
	}
	public void setAccount(String account) {
		this.account = account;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getHeadImg() {
		return headImg;
	}
	public void setHeadImg(String headImg) {
		this.headImg = headImg;
	}
	public boolean isGender() {
		return gender;
	}
	public void setGender(boolean gender) {
		this.gender = gender;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getMemo() {
		return memo;
	}
	public void setMemo(String memo) {
		this.memo = memo;
	}
	// }}
	
}

User.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!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.rk.tax.entity" auto-import="true">
	<class name="User" table="T_Users">
		<id name="id" column="id" type="string" length="32">
			<generator class="uuid.hex"></generator>
		</id>
		<property name="name" column="name" type="string" length="20" not-null="true"></property>
		<property name="dept" column="dept" type="string" length="20" not-null="true"></property>
		<property name="account" column="account" type="string" length="50" not-null="true"></property>
		<property name="password" column="password" type="string" length="50" not-null="true"></property>
		<property name="headImg" column="headImg" type="string" length="100"></property>
		<property name="gender" column="gender" type="boolean" not-null="true"></property>
		<property name="email" column="email" type="string" length="50"></property>
		<property name="mobile" column="mobile" type="string" length="20"></property>
		<property name="birthday" column="birthday" type="date" length="10" ></property>
		<property name="state" column="state" type="string" length="1"></property>
		<property name="memo" column="memo" type="string" length="200"></property>
	</class>

</hibernate-mapping>

UserDao.java

package com.rk.tax.dao;

import com.rk.core.dao.BaseDao;
import com.rk.tax.entity.User;

public interface UserDao extends BaseDao<User> {

}

UserDaoImpl.java

package com.rk.tax.dao.impl;

import com.rk.core.dao.impl.BaseDaoImpl;
import com.rk.tax.dao.UserDao;
import com.rk.tax.entity.User;

public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao {

}
























SSH系列:(7)编写通用Dao

标签:ssh

原文地址:http://lsieun.blog.51cto.com/9210464/1835776

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!