Spring Data Jpa 配置

 

使用 Spring Data JPA 进行持久层开发需要的四个步骤:

1.配置 Spring 整合 JPA

2.在 Spring 配置文件中配置 Spring Data,让 Spring 为声明的接口创建代理对象。配置了 <jpa:repositories> 后,Spring 初始化容器时将会扫描 base-package  指定的包目录及其子目录,为继承Repository 或其子接口的接口创建代理对象,并将代理对象注册为 Spring Bean,业务层便可以通过 Spring 自动封装的特性来直接使用该对象。

3.声明持久层的接口,该接口继承  Repository,Repository 是一个标记型接口,它不包含任何方法,如必要,Spring Data 可实现 Repository 其他子接口,其中定义了一些常用的增删改查,以及分页相关的方法。

4.在接口中声明需要的方法。Spring Data 将根据给定的策略(具体策略稍后讲解)来为其生成实现代码。

 

搭建环境

同时下载 Spring Data Commons 和 Spring Data JPA 两个发布包:
Commons 是 Spring Data 的基础包
并把相关的依赖 JAR 文件加入到 CLASSPATH 中
在 Spring 的配置文件中配置 Spring Data

 

项目结构如图:

具体代码如下:

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>  
<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:jpa="http://www.springframework.org/schema/data/jpa"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">  
  
    <!-- 配置自动扫描的包 -->  
    <context:component-scan base-package="com.atguigu.springdata"></context:component-scan>  
  
    <!-- 1. 配置数据源 -->  
    <context:property-placeholder location="classpath:db.properties"/>  
  
    <bean id="dataSource"  
        class="com.mchange.v2.c3p0.ComboPooledDataSource">  
        <property name="user" value="${jdbc.user}"></property>  
        <property name="password" value="${jdbc.password}"></property>    
        <property name="driverClass" value="${jdbc.driverClass}"></property>  
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>  
          
        <!-- 配置其他属性 -->  
    </bean>  
  
    <!-- 2. 配置 JPA 的 EntityManagerFactory -->  
    <bean id="entityManagerFactory"   
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">  
        <property name="dataSource" ref="dataSource"></property>  
          
        <!-- 配置 JPA 提供商的适配器. 可以通过内部 bean 的方式来配置 -->  
        <property name="jpaVendorAdapter">  
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>  
        </property>  
          
        <!-- 配置实体类所在的包 -->  
        <property name="packagesToScan" value="com.atguigu.springdata"></property>  
        <property name="jpaProperties">  
            <props>  
                <!-- 二级缓存相关 -->  
                <!--    
                <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>  
                <prop key="net.sf.ehcache.configurationResourceName">ehcache-hibernate.xml</prop>  
                -->  
                <!-- 生成的数据表的列的映射策略 -->  
                <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>  
                <!-- 配置 JPA 的基本属性. 例如 JPA 实现产品的属性 -->  
                <!-- hibernate 基本属性 -->  
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>  
                <prop key="hibernate.show_sql">true</prop>  
                <prop key="hibernate.format_sql">true</prop>  
                <prop key="hibernate.hbm2ddl.auto">update</prop>  
            </props>  
        </property>  
    </bean>  
      
      
    <!-- 3. 配置事务管理器 -->  
    <bean id="transactionManager"  
        class="org.springframework.orm.jpa.JpaTransactionManager">  
        <property name="entityManagerFactory" ref="entityManagerFactory"></property>      
    </bean>  
  
    <!-- 4. 配置支持注解的事务 -->  
    <tx:annotation-driven transaction-manager="transactionManager"/>  
  
    <!-- 5. 配置 SpringData -->  
    <!-- 加入  jpa 的命名空间 -->  
    <!-- base-package: 扫描 Repository Bean 所在的 package -->  
    <jpa:repositories base-package="com.atguigu.springdata"  
        entity-manager-factory-ref="entityManagerFactory"></jpa:repositories>  
          
</beans>  

 

 


接口代码:

package com.atguigu.springdata;  
  
import org.springframework.data.jpa.repository.JpaRepository;  
  
/** 
 * 1. Repository 是一个空接口. 即是一个标记接口 
 * 2. 若我们定义的接口继承了 Repository, 则该接口会被 IOC 容器识别为一个 Repository Bean. 
 * 纳入到 IOC 容器中. 进而可以在该接口中定义满足一定规范的方法.  
 *  
 * 3. 实际上, 也可以通过 @RepositoryDefinition 注解来替代继承 Repository 接口 
 */  
/** 
 * 在 Repository 子接口中声明方法 1. 不是随便声明的. 而需要符合一定的规范 2. 查询方法以 find | read | get 开头 3. 
 * 涉及条件查询时,条件的属性用条件关键字连接 4. 要注意的是:条件属性以首字母大写。 5. 支持属性的级联查询. 若当前类有符合条件的属性, 则优先使用, 
 * 而不使用级联属性. 若需要使用级联属性, 则属性之间使用 _ 进行连接. 
 */  
// @RepositoryDefinition(domainClass=Person.class,idClass=Integer.class)  
public interface PersonRepsotory extends JpaRepository<Person, Integer> {  
  
    // 根据 lastName 来获取对应的 Person  
    Person getByLastName(String lastName);  
  
}

 


测试代码:

 

package com.atguigu.springdata.test;  
  
import java.sql.SQLException;  
  
import javax.sql.DataSource;  
  
import org.junit.Test;  
import org.springframework.context.ApplicationContext;  
import org.springframework.context.support.ClassPathXmlApplicationContext;  
  
import com.atguigu.springdata.Person;  
import com.atguigu.springdata.PersonRepsotory;  
  
public class SpringDataTest {  
    private ApplicationContext ctx = null;  
    private PersonRepsotory personRepsotory = null;  
  
    {  
        ctx = new ClassPathXmlApplicationContext("applicationContext.xml");  
        personRepsotory = ctx.getBean(PersonRepsotory.class);  
  
    }  
  
    @Test  
    public void testSpringData() {  
  
        Person person = personRepsotory.getByLastName("ppl");  
        System.out.println(person);  
    }  
  
    @Test  
    public void testJpa() {  
  
    }  
  
    @Test  
    public void testDataSource() throws SQLException {  
        DataSource dataSource = ctx.getBean(DataSource.class);  
        System.out.println(dataSource.getConnection());  
    }  
  
} 

 

 
 
 
参考
http://www.icoolxue.com/play/9080
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 posted on 2017-01-09 22:14  布鲁布鲁sky  阅读(282)  评论(0编辑  收藏  举报