Chinaunix首页 | 论坛 | 博客
  • 博客访问: 366710
  • 博文数量: 28
  • 博客积分: 455
  • 博客等级: 下士
  • 技术积分: 445
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-09 11:10
文章分类

全部博文(28)

文章存档

2016年(5)

2014年(1)

2013年(10)

2011年(7)

2010年(5)

我的朋友

分类: Java

2016-01-27 20:47:32

1、why?
为什么既要用HibernateJpa又要用SpringDataJpa呢?
传统的Dao层开发的时候,对于每一个实体类需要一个接口,还需要一个实现类,
这些一个个的Dao里面有很多功能是相似的(例如增删改查什么的)
Spring Data Jpa就把这些功能抽象成接口,在开发的时候甚至都不需要实现类,只要按照它给定的方法来编写接口方法即可。

2、步骤
1)、首先新建一个java工程
2)、加入需要的jar包
hibernate必须的jar包
hibernate jpa的包
使用二级缓存,hibernate和ehcache整合的包
spring的jar包
spring data jpa的包
mysql jdbc驱动
log4j日志包



3)、编写spring配置文件,以下文件都放在src根目录下
首先建立一个db.properties文件,定义一些连接数据库的属性

点击(此处)折叠或打开

  1. jdbc.username=root
  2. jdbc.password=password
  3. jdbc.url=jdbc:mysql:///test
  4. jdbc.driverClassName=com.mysql.jdbc.Driver

然后把log4j.properties和ehcache.xml从hibernate的包里copy出来直接使用
下面就是最主要的Spring IOC配置文件,内容如下:


点击(此处)折叠或打开

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns=""
  3.     xmlns:xsi=""
  4.     xmlns:context=""
  5.     xmlns:tx=""
  6.     xmlns:jpa=""
  7.     xsi:schemaLocation=" /spring-beans.xsd
  8.          /spring-context-4.2.xsd
  9.          /spring-jpa-1.8.xsd
  10.          /spring-tx-4.2.xsd">

  11.     <!-- 配置自动扫描的包(包括其下子包) -->
  12.     <context:component-scan base-package="com.blank.integrate.spring.hibernate"/>
  13.     
  14.     <!-- 配置数据源 -->
  15.     <!-- 简单搭建先不用连接池了,一般会把数据库配置文件单独放在一个properties文件 -->
  16.     <context:property-placeholder location="classpath:db.properties"/>
  17.     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  18.         <property name="username" value="${jdbc.username}"/>
  19.         <property name="password" value="${jdbc.password}"/>
  20.         <property name="url" value="${jdbc.url}"/>
  21.         <property name="driverClassName" value="${jdbc.driverClassName}"/>
  22.     </bean>
  23.     
  24.     <!-- 配置JPA的EntityManagerFactory -->
  25.     <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  26.         <property name="dataSource" ref="dataSource"/>
  27.         <property name="jpaVendorAdapter">
  28.             <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
  29.         </property>
  30.         <!-- jpa扫描entity的包 -->
  31.         <property name="packagesToScan" value="com.blank.integrate.spring.hibernate.entity"/>
  32.         <property name="jpaProperties">
  33.             <props>
  34.                 <!-- 二级缓存 -->
  35.                 <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
  36.                 <prop key="net.sf.ehcache.configurationResourceName">ehcache.xml</prop>
  37.                 <!-- 生成的数据表的列的映射策略 -->
  38.                 <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
  39.                 <!-- hibernate 基本属性 -->
  40.                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
  41.                 <prop key="hibernate.show_sql">true</prop>
  42.                 <prop key="hibernate.format_sql">true</prop>
  43.                 <prop key="hibernate.hbm2ddl.auto">update</prop>
  44.             </props>
  45.         </property>
  46.     </bean>
  47.     
  48.     <!-- 配置事务管理器 -->
  49.     <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  50.         <property name="entityManagerFactory" ref="entityManagerFactory"/>
  51.     </bean>
  52.     
  53.     <!-- 配置支持注解的事务 -->
  54.     <tx:annotation-driven transaction-manager="transactionManager"/>
  55.     
  56.     <!-- 配置SpringData ,也就是扫描Repository的包-->
  57.     <jpa:repositories base-package="com.blank.integrate.spring.hibernate.dao"
  58.         entity-manager-factory-ref="entityManagerFactory">
  59.     </jpa:repositories>
  60. </beans>


4)、新建一个实体类,简单点,顺便试用一下hibernate提供的uuid生成的主键方式

点击(此处)折叠或打开

  1. package com.blank.integrate.spring.hibernate.entity;

  2. import javax.persistence.Column;
  3. import javax.persistence.Entity;
  4. import javax.persistence.GeneratedValue;
  5. import javax.persistence.Id;
  6. import javax.persistence.Table;

  7. import org.hibernate.annotations.GenericGenerator;

  8. @Entity
  9. @Table(name="spring_Customer")
  10. public class Customer {

  11.     @Override
  12.     public String toString() {
  13.         return "Customer [id=" + id + ", name=" + name + "]";
  14.     }

  15.     @Id
  16.     @GeneratedValue(generator="uuidGenerator")
  17.     @GenericGenerator(name="uuidGenerator", strategy="uuid")
  18.     @Column(length=40)
  19.     private String id;
  20.     
  21.     @Column(length=40)
  22.     private String name;

  23.     public String getId() {
  24.         return id;
  25.     }

  26.     public void setId(String id) {
  27.         this.id = id;
  28.     }

  29.     public String getName() {
  30.         return name;
  31.     }

  32.     public void setName(String name) {
  33.         this.name = name;
  34.     }

  35.     
  36. }

5)、新建一个接口,继承自JpaRepository和JpaSpecificationExecutor
继承JpaSpecificationExecutor是为了以后扩展其他功能,比如带查询条件的分页
其中JpaRepository泛型的一个参数是实体类,第二个是主键的类型
在该接口中定义一个方法getByName,不需要实现,就是这么简单

点击(此处)折叠或打开

  1. package com.blank.integrate.spring.hibernate.dao;

  2. import org.springframework.data.jpa.repository.JpaRepository;
  3. import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

  4. import com.blank.integrate.spring.hibernate.entity.Customer;

  5. public interface CustormerDao extends JpaRepository<Customer, String>,
  6.     JpaSpecificationExecutor<Customer> {

  7.     public Customer getByName(String name);
  8. }

6)、定义一个Service,测试几个简单的新增、查询、修改操作

点击(此处)折叠或打开

  1. package com.blank.integrate.spring.hibernate.service;

  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Service;
  4. import org.springframework.transaction.annotation.Transactional;

  5. import com.blank.integrate.spring.hibernate.dao.CustormerDao;
  6. import com.blank.integrate.spring.hibernate.entity.Customer;

  7. @Service
  8. public class CustomerService {
  9.     @Autowired
  10.     private CustormerDao customerDao;
  11.     
  12.     @Transactional
  13.     public void save(Customer customer){
  14.         customerDao.save(customer);
  15.     }
  16.     
  17.     @Transactional
  18.     public void getAndUpdate(String id, String newName){
  19.         Customer customer = customerDao.getOne(id);
  20.         System.out.println(customer);
  21.         customer.setName(newName);
  22.         customerDao.saveAndFlush(customer);
  23.     }
  24.     
  25.     @Transactional
  26.     public Customer getByName(String name){
  27.         return customerDao.getByName(name);
  28.     }
  29. }

7)、测试类


点击(此处)折叠或打开

  1. package com.blank.integrate.spring.hibernate.service;

  2. import org.junit.Before;
  3. import org.junit.Test;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;

  6. import com.blank.integrate.spring.hibernate.entity.Customer;

  7. public class CustomerServiceTest {

  8.     private ApplicationContext ctx = null;
  9.     private CustomerService customerService = null;
  10.     
  11.     @Before
  12.     public void before(){
  13.         ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
  14.         customerService = (CustomerService) ctx.getBean("customerService");
  15.     }
  16.     
  17.     @Test
  18.     //测试新增
  19.     public void testSave(){
  20.         Customer customer = new Customer();
  21.         customer.setName("张三");
  22.         customerService.save(customer);
  23.     }
  24.     
  25.     @Test
  26.     public void testGetAndUpdate(){
  27.         
  28.         customerService.getAndUpdate("402895815282fb9e015282fba1ee0000","小张三");
  29.         
  30.     }
  31.     
  32.     @Test
  33.     public void testGetByName(){
  34.         System.out.println(customerService.getByName("小张三"));
  35.     }
  36.         

  37. }

首先,测试新增,测试成功后,数据库中会有一张表spring_customer,并且插入了记录,主键是hibernate帮忙生成的uuid



然后,按照这个uuid测试查询和修改,完成后发现姓名修改了


最后,再测试按照name来查询,输出结果正常

点击(此处)折叠或打开

  1. Customer [id=402895815282fb9e015282fba1ee0000, name=小张三]

8)、当然Spring Data Jpa还提供了很多强大的功能,可以上官方网站,照着官方文档测试其他强大的功能




阅读(5737) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~