欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

项目中DAO的结构实现

程序员文章站 2022-06-08 10:42:14
...

 

 

首先是定义基础DAO接口:

 

 

package com.tch.test.ssh.dao;

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

public interface BaseDao<E, PK extends Serializable> {
	/**
	 *  Created on 2013-9-16 
	 * <p>DiscripEion:保存对象</p>
	 * @reEurn void
	 */
	void save(E entity);
	/**
	 *  Created on 2013-9-16 
	 * <p>DiscripEion:更新对象</p>
	 * @reEurn void
	 */
	void update(E entity);
	/**
	 *  Created on 2013-9-16 
	 * <p>DiscripEion:删除对象</p>
	 * @reEurn void
	 */
	void delete(E entity);
	/**
	 *  CreaEed on 2013-9-16 
	 * <p>DiscripEion:根据id查询对象</p>
	 * @reEurn void
	 */
	E get(PK id);
	/**
	 *  Created on 2013-9-16 
	 * <p>DiscripEion:查询全部对象</p>
	 * @reEurn void
	 */
	List<E> getAll();
	
}

 

 

以及配置sessionFactory的基础类:

 

package com.tch.test.ssh.dao;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class CommomDao extends HibernateDaoSupport{

	@Resource(name="sessionFactory")//这里由于父类中的setSessionFactory()方法是final的,不能重写,所以要换个方法名字,在方法里面调用父类的setSessionFactory()方法
	public void setSuperSessionFactory(SessionFactory sessionFactory){
		this.setSessionFactory(sessionFactory);
	}
	
}

 

 实体类以及映射文件:

 

 

package com.tch.test.ssh.entity;
// default package

import java.util.Date;


/**
 * MyTime entity. @author MyEclipse Persistence Tools
 */

public class MyTime  implements java.io.Serializable {


    // Fields    

     private static final long serialVersionUID = 1L;
     private Integer id;
     private Date addTime;


    // Constructors

    /** default constructor */
    public MyTime() {
    }

    
    /** full constructor */
    public MyTime(Date addTime) {
        this.addTime = addTime;
    }

   
    // Property accessors

    public Integer getId() {
        return this.id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }

    public Date getAddTime() {
        return this.addTime;
    }
    
    public void setAddTime(Date addTime) {
        this.addTime = addTime;
    }

}

 

 

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.tch.test.ssh.entity.MyTime" table="t_times" catalog="test">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="native"></generator>
        </id>
        <property name="addTime" type="java.util.Date">
            <column name="addTime" length="8" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

 

然后是基础DAO实现类:

 

 

package com.tch.test.ssh.dao;

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

public class BaseDaoImpl<E, PK extends Serializable> extends CommomDao implements BaseDao<E,PK>{

	private Class<E> clazz;
	
	@SuppressWarnings("unchecked")
	public BaseDaoImpl(){
		this.clazz = (Class<E>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];//反射方式获取子类泛型的实际类型
	}
	
	@Override
	public void delete(E entity) {
		getHibernateTemplate().delete(entity);
	}

	@SuppressWarnings("unchecked")
	@Override
	public E get(PK id) {
		return (E)getHibernateTemplate().get(clazz, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<E> getAll() {
		return getHibernateTemplate().loadAll(clazz);
		/*String hql = "from "+clazz.getName();
		System.out.println("hql: "+hql);
		return getSession().createQuery(hql).list();*/
	}

	@Override
	public void save(E entity) {
		getHibernateTemplate().save(entity);
	}

	@Override
	public void update(E entity) {
		getHibernateTemplate().update(entity);
	}

}

 

接下来是接口演示:

 

 

 

package com.tch.test.ssh.dao;

import com.tch.test.ssh.entity.MyTime;

public interface TimeDao extends BaseDao<MyTime, Integer>{

	
}

 

 

实现类演示(只需要继承BaseDaoImpl类,就含有了基本的增删改查等方法):

 

 

 

package com.tch.test.ssh.dao;

import org.springframework.stereotype.Repository;

import com.tch.test.ssh.entity.MyTime;
@Repository("TimeDao")
public class TimerDaoImpl extends BaseDaoImpl<MyTime, Integer> implements TimeDao{

}

 

 

最近贴上applicationContext.xml的内容:

 

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	<!-- 启动注入功能 -->
	<context:annotation-config />
	<!-- 启动扫描component功能 -->
	<context:component-scan base-package="com.tch.test" />
	<!-- 启动注解实物配置功能 -->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
	<!-- 数据源 -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
	</bean>
	<!-- 事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<!--读取数据库配置文件  -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<property name="mappingLocations">
			 <value>classpath:com/tch/test/ssh/entity/*.hbm.xml</value>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>
</beans>

 

 加上测试类:

 

package test;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.tch.test.ssh.dao.TimeDao;
import com.tch.test.ssh.entity.MyTime;

public class TestSpring {

	public static void main(String[] args) throws Exception {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		TimeDao dao = (TimeDao) context.getBean("TimeDao");
		List<MyTime> entities = dao.getAll();
		for(MyTime entity:entities){
			System.out.println(entity.getId()+" , "+entity.getAddTime());
		}
	}
	
}