spring+jpa+简单泛型dao

spring+jpa的整合

数据库文件


  /*
Navicat MySQL Data Transfer

Source Server         : mysql
Source Server Version : 50165
Source Host           : localhost:3306
Source Database       : testdb

Target Server Type    : MYSQL
Target Server Version : 50165
File Encoding         : 65001

Date: 2012-09-11 12:46:12
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `goods`
-- ----------------------------
DROP TABLE IF EXISTS `goods`;
CREATE TABLE `goods` (
  `goodsId` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `price` double(10,2) NOT NULL,
  `goodName` varchar(20) NOT NULL,
  PRIMARY KEY (`goodsId`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of goods
-- ----------------------------
INSERT INTO `goods` VALUES ('1', '1.54', '冰激凌');
INSERT INTO `goods` VALUES ('2', '3.60', '面包');
INSERT INTO `goods` VALUES ('7', '5200.00', 'thinkpad笔记本');
INSERT INTO `goods` VALUES ('8', '5200.00', 'thinkpad笔记本');




实体类

 package com.own.entity;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Goods implements Serializable {
    
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	public int getGoodsId() {
		return goodsId;
	}
	public void setGoodsId(int goodsId) {
		this.goodsId = goodsId;
	}
	
	public String getGoodName() {
		return goodName;
	}
	public void setGoodName(String goodName) {
		this.goodName = goodName;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	private int goodsId;
	private String goodName;
	private double price;
	
}




泛型dao


package com.own.dao;

import java.io.Serializable;

public interface GenericDao<T extends Serializable,PK extends Serializable> {
    
	/**
	 * 保存一个对象
	 * @param obj
	 */
	void saveObject(T obj);
	/**
	 * 删除一个对象
	 * @param obj
	 */
	void deleteObject(T obj);
	/**
	 * 更新一个对象
	 * @param ojb
	 */
	void updateObject(T ojb);
	/**
	 * 根据主键id找到一个对象
	 * @param id
	 */
	T findObject(PK id);
	
}




泛型dao的实现

   package com.own.dao.impl;

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



import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;



import com.own.dao.GenericDao;
public abstract  class GenericDaoImpl<T extends Serializable ,PK extends Serializable> implements GenericDao<T,PK>{
    
	@PersistenceContext
	protected EntityManager em;
    
	private Class<T> entityClass;
	
	
	@SuppressWarnings("unchecked")
	public GenericDaoImpl(){
	  /**
	   * 获取泛型的实际类型
	   */
	  ParameterizedType type =	(ParameterizedType) this.getClass().getGenericSuperclass();
	  entityClass = (Class<T>)type.getActualTypeArguments()[0];

	}
	
	@Override
	public void deleteObject(T obj) {
		// TODO Auto-generated method stub
		em.remove(em.merge(obj));
		
		
	}
	
	@Override
	public T findObject(PK id) {
		// TODO Auto-generated method stub
		return (T)em.find(entityClass,id);
	}
	
	@Override
	public void saveObject(T obj) {
		// TODO Auto-generated method stub
		em.persist(obj);
	}
	
	@Override
	public void updateObject(T obj) {
		// TODO Auto-generated method stub
		em.merge(obj);
	}

}

   



定义一个具体的dao继承泛型dao
  package com.own.dao;

import com.own.entity.Goods;

public interface GoodsDao extends GenericDao<Goods,Integer> {
   /**
    * 添加需要的方法
    */
}




GoodsDao的实现,这里继承泛型dao的实现

  package com.own.dao.impl;

import org.springframework.stereotype.Repository;

import com.own.dao.GoodsDao;
import com.own.entity.Goods;
@Repository("goodsDao")
public class GoodsDaoImpl extends GenericDaoImpl<Goods,Integer> implements GoodsDao {
  
}
 


GoodsService 代码

 
   package com.own.service;



import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.own.entity.Goods;


public interface GoodsService  {
   
   @Transactional(propagation=Propagation.REQUIRED,rollbackFor=RuntimeException.class)
   void saveGoods(Goods goods);
   @Transactional(propagation=Propagation.REQUIRED,rollbackFor=RuntimeException.class)
   void removeGoods(Goods goods);
   //查找方法不需要配置事务
   Goods getGoodsById(int id);
   /**
    * 配置事务
    * 
    */
   @Transactional(propagation=Propagation.REQUIRED,rollbackFor=RuntimeException.class)
   void updateGoods(Goods goods);
}



Goodsservice实现

  package com.own.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.own.dao.GoodsDao;
import com.own.entity.Goods;
import com.own.service.GoodsService;
@Service("goodsService")
public class GoodsServiceImpl implements GoodsService {
   
	@Resource(name="goodsDao")
	private GoodsDao goodsDao;
	@Override
	public Goods getGoodsById(int id) {
		// TODO Auto-generated method stub
		return goodsDao.findObject(id);
	}

	@Override
	public void removeGoods(Goods goods) {
		// TODO Auto-generated method stub
		goodsDao.deleteObject(goods);
	}

	@Override
	public void saveGoods(Goods goods) {
		// TODO Auto-generated method stub
		goodsDao.saveObject(goods);
	}

	@Override
	public void updateGoods(Goods goods) {
		// TODO Auto-generated method stub
		goodsDao.updateObject(goods);
	}

}



测试代码

   
package com.own.service;

import static org.junit.Assert.*;

import javax.annotation.Resource;


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


import com.own.entity.Goods;
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class GoodsServiceTest {
    
	@Resource(name="goodsService")
	private GoodsService goodsService;
 
	@Test
	public void testSaveGoods() {
		Goods goods = new Goods();
		goods.setGoodName("电视机");
		goods.setPrice(2300);
		goodsService.saveGoods(goods);
	}

	@Test 
	public void testRemoveGoods() {
	Goods goods = new Goods();
		goods.setGoodsId(2);
		//Goods good = (Goods)goodsService.getGoodsById(1);
		goodsService.removeGoods(goods);
	}

	@Test 
	public void testGetGoodsById() {
		Goods good = (Goods)goodsService.getGoodsById(1);
		String name = good.getGoodName();
		System.out.println(good.getGoodName());
		assertEquals("冰激凌",name);
		
	}

	@Test
	public void testUpdateGoods() {
	    Goods good = new Goods();
	    good.setGoodsId(7);
		good.setGoodName("巧克力");
		goodsService.updateGoods(good);
	}

}




spring的配置文件
<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" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="  
             http://www.springframework.org/schema/beans 
             http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
             http://www.springframework.org/schema/context
        	 http://www.springframework.org/schema/context/spring-context-3.0.xsd
             http://www.springframework.org/schema/aop 
             http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
             http://www.springframework.org/schema/tx 
             http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

  <!-- 配置连接池   -->
  <bean id="dataSource"  class="org.apache.commons.dbcp.BasicDataSource"  destroy-method="close"    >
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
        <property name="url" value="jdbc:mysql://localhost:3306/shopping?useUnicode=true&amp;characterEncoding=UTF-8" />  
        <property name="username"  value="root" ></property>  
        <property name="password"  value="zyp"  ></property>  
        <property name="maxActive" value="20"  ></property>  
        <property name="initialSize" value="3"  >  </property>  
        <property name="maxWait" value="60000"  ></property>  
        <property name="maxIdle"><value>20</value></property>  
        <property name="minIdle"><value>0</value></property>  
   </bean>
   
   <!-- 配置jap实现提供商的特性  -->
   <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"  >
         <property name="database" value="MYSQL" ></property> 
   </bean>
  
  <!-- 持久化提供商   -->
  <bean id="persistenceProvider" class="org.hibernate.ejb.HibernatePersistence"/>
  
  <!--配置spring对jpa的支持 -->
  <bean id="entityManagerFactory"  class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
     <property name="dataSource">
        <ref bean="dataSource" />
     </property>
      <!-- 持久化单原名称 -->
     <property name="persistenceUnitName"  value="zyp"  />
     
     <!-- 持久化提供商  -->
     <property name="persistenceProvider" >
        <ref bean="persistenceProvider" />
     </property>
     <!-- 特性提供商配置 -->
     <property name="jpaVendorAdapter" >
        <ref bean="jpaVendorAdapter" />
     </property>
     <!-- jpa 属性配置 -->
     <property name="jpaProperties">
        <props>
         <prop key="hibernate.show_sql">true</prop>
         <prop key="hibernate.max_fetch_depth">3</prop>
         <prop key="hibernate.hbm2ddl.auto">false</prop>
	     <prop key="hibernate.jdbc.fetch_size"  >18</prop>
	     <prop key="hibernate.jdbc.batch_size" >10</prop>
	     <prop key="hibernate.format_sql"  >true</prop> 
        </props>
    </property>
  </bean>

	<context:component-scan base-package="com.own" />		
   
      
    <!-- 配置事物管理 -->
   <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
   </bean>  
  
   <tx:annotation-driven transaction-manager="transactionManager"/>
  
</beans>

 


你可能感兴趣的:(spring)