`
H.Z
  • 浏览: 16744 次
  • 来自: 长沙
社区版块
存档分类
最新评论

spring之spring data jpa(入门三) 扩展spring data jpa

 
阅读更多

在编写spring data jpa的dao时,只需在接口中按规约提供方法的声明即可.而有些业务实现无法通过声明方法或编写简单的SQL实现,这就需要扩展Spring Data JPA.

 1.为某一个特定的Repositrory添加自定义方法.

     注意:默认情况下,Spring Data 会在base-package中查找"接口名Impl"做为实现类,也可以通过 repository-impl-postfix声明后缀.

 

       示例:

       1. 准备领域对象

        

@Entity
public class Employee {
 
    @Id
    @GeneratedValue
    private Integer id;
 
    @Column
    private String name;
// 省略get/set方法...
}

 

    2.定义一个接口,声明要添加的方法. 

public interface EmployeeDao {
 
    void method();
       
}

         

        3.提供该接口的实现类,类名需要符合EntityNameRepositoryImpl格式,并提供实现方法.

 

public class EmployeeRepositoryImpl implements EmployeeDao {
 
    //获取当前线程的EntityManager实例
    @PersistenceContext
    private EntityManager entityManager;
 
    public void method() {
        System.out.println("method..."+entityManager);
    }
}

          
       4.声明一个Repository接口,并继承EmplyeeDao接口.

public interface EmployeeRepository extends JpaRepository<Employee, Integer>,EmployeeDao{
 
}

 

        5.使用

@ContextConfiguration("classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class AppTest {
    @Autowired
    EmployeeRepository employeeRepository;
 
    @Test
    public void test02(){
        employeeRepository.method();
    }
}

 

2.为所有的Repositrory添加自定义方法. 

        示例:

        1.声明一个接口,在该接口中声明需要自定义的方法,该接口需要继承spring data 的Repository接口或           其子接口.

@NoRepositoryBean
public interface BaseRepository<T,ID extends Serializable> extends JpaRepository<T,ID> {
    //全局共享的自定义方法
    void method();
}

        

        2.提供BaseRepository的实现类,且继承SimpleJpaRepository,并提供方法的实现.注意:全局的扩展实         现类不要用RepositoryImpl作为后缀名,或为全局扩展接口添加@NoRepositoryBean注解告Spring           data:该实现类不是一个Repository.

//实现类simpleBaseRepository
public class SimpleBaseRepository<T,ID extends Serializable> extends SimpleJpaRepository<T, ID> implements BaseRepository<T, ID> {
 
 
    private final EntityManager entityManager;
 
 
    public SimpleBaseRepository(JpaEntityInformation<T, ?> entityInformation,
            EntityManager entityManager) {
        super(entityInformation, entityManager);
        this.entityManager=entityManager;
    }
 
    public SimpleBaseRepository(Class<T> domainClass, EntityManager em) {
        super(domainClass, em);
        this.entityManager=em;
    }
 
    //实现了全局自定义方法
    public void method() {
        System.out.println("--hello--");
    }
 
}

 

        3.定义一个RepositoryFactory工厂,生产BaseRepository的实现类SimpleBaseRepository的对象.           该工厂需要继承spring data jpa提供的JpaRepositoryFactory. 

 

public class SimpleBaseRepositoryFactory extends JpaRepositoryFactory {
 
    private final EntityManager em;
 
    public SimpleBaseRepositoryFactory(EntityManager entityManager) {
        super(entityManager);
        this.em=entityManager;
    }
 
    @Override
    @SuppressWarnings({"rawtypes","unchecked"})
    protected Object getTargetRepository(RepositoryMetadata metadata) {
        if(BaseRepository.class.isAssignableFrom(metadata.getRepositoryInterface())){
            JpaEntityInformation<?,Serializable> entityInformation = getEntityInformation(metadata.getDomainType());
            SimpleBaseRepository<?,Serializable> repository = new SimpleBaseRepository(entityInformation, em);
            return repository;
        }
        return super.getTargetRepository(metadata);
    }
 
    @Override
    protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
        if(BaseRepository.class.isAssignableFrom(metadata.getRepositoryInterface())){
            return SimpleBaseRepository.class;
        }
        return super.getRepositoryBaseClass(metadata);
    }
 
}

 

        4.定义JpaRepositoryFactoryBean的实现类,由它生成SimpleBaseRepositoryFactory工厂实例,从而生产SimpleBaseRepository的实例对象.

 

public class SimpleBaseRepositoryFactoryBean<T extends Repository<S,ID>,S,ID extends Serializable> extends JpaRepositoryFactoryBean<T, S, ID> {
 
    @Override
    protected RepositoryFactorySupport createRepositoryFactory(
            EntityManager entityManager) {
        return new SimpleBaseRepositoryFactory(entityManager);
    }
}

 

 

        5.最后需要在配置文件中指定<jpa:repositroies>中的factory-class属性指                                                  定 SimpleBaseRepositoryFactoryBean,交由spring管理.                

 

<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.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.1.xsd">
 
    <description>Spring 应用配置</description>
 
    <!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->
    <context:component-scan base-package="com.zt.*"/>
 
    <!-- 数据源配置 -->
    <context:property-placeholder ignore-unresolvable="true" location="classpath*:/dataAccess.properties" />
 
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- Connection Info -->
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
 
    <!-- Jpa Entity Manager 配置 -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" p:database="${jpa.database}"
                p:showSql="${jpa.showSql}" p:generateDdl="true" />
        </property>
        <property name="packagesToScan" value="com.zt" />
    </bean>
 
    <!-- Jpa 事务配置 -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>
 
    <!-- 使用annotation定义事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
 
    <!-- Spring Data Jpa配置 -->
    <jpa:repositories base-package="com.zt.**.repository" repository-impl-postfix="Impl"
        factory-class="com.zt.common.repository.support.SimpleBaseRepositoryFactoryBean" transaction-manager-ref="transactionManager"
        entity-manager-factory-ref="entityManagerFactory" />
 
</beans>

  

        6.测试

        首先,准备实体对象.

        

@Entity
@Table(name="t_t_user")
public class User {
    @Id
    @GeneratedValue
    private Integer id;
    @Column
    private String name;
    //省略get/set方法
}

 

        然后定义UserRepositroy接口.

    

public interface UserRepository extends BaseRepository<User, Integer>{
}
 

        Junit测试:

@ContextConfiguration("classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class AppTest {
 
    //userRepository最后由spring注入进来的是SimpleBaseRepository.
    @Autowired
    private UserRepository userRepository;
    @Test
    public void test() {
        userRepository.method();
    }
}

        

分享到:
评论

相关推荐

    spring注解+spring data jpa文档+JPA文档.rar

    Spring框架的核心特性包括依赖注入(DI)和面向切面编程(AOP),并且它还提供了对数据库操作的支持,这主要通过Spring Data JPA和Java Persistence API(JPA)实现。 Spring注解是Spring框架中的一大特色,它极大...

    Spring Data JPA从入门到精通

    'SpringDataJPA从入门到精通'分为12章 内容包括整体认识JPA、JPA基础查询方法、定义查询方法、注解式查询方法、@Entity实例里面常用注解详解、JpaRepository扩展详解、JPA的MVC扩展REST支持、DataSource的配置、乐观...

    Spring Data JPA API(Spring Data JPA 开发文档).CHM

    Spring Data JPA API。 Spring Data JPA 开发文档。 官网 Spring Data JPA API。

    Spring Data JPA 笔记

    Spring Data JPA则是在JPA之上构建的一层抽象,它扩展了JPA的功能,提供了更多的便利。例如,Spring Data JPA支持自动化的查询生成,只需定义Repository接口,无需编写任何实现代码,就可以执行CRUD(创建、读取、...

    Spring Data JPA中文文档[1.4.3]_springdatajpa_erlang_waitxpf_

    1. **Repository Abstraction**:这是 Spring Data JPA 的核心特性之一。它提供了一种声明式的数据访问接口,允许开发者定义自定义的查询方法,而不需要手动编写 SQL 或者 HQL(Hibernate Query Language)。例如,...

    spring data jpa入门实例

    【Spring Data JPA 入门实例】 Spring Data JPA 是 Spring 框架的一个模块,它简化了数据库访问层(DAO)的开发,通过提供自动化的 Repository 实现,使得开发者无需编写大量的 CRUD(创建、读取、更新、删除)代码...

    Spring Data JPA入门项目02

    在本项目"Spring Data JPA入门项目02"中,我们将深入探讨如何使用Spring Data JPA进行查询操作,包括排序和分页。Spring Data JPA是Spring Framework的一个模块,它为Java Persistence API (JPA) 提供了一种更加便捷...

    Spring Boot整合SpringDataJPA

    Spring Data JPA是Spring生态系统中的一个重要组件,它为开发者提供了与JPA(Java Persistence API)交互的简化接口,极大地提高了数据访问的效率。本教程将深入探讨如何在Spring Boot项目中整合Spring Data JPA,...

    spring data jpa 入门例子

    本入门例子将帮助你理解并掌握Spring Data JPA的核心概念和常用功能。 1. **什么是Spring Data JPA** Spring Data JPA是Spring框架的一部分,它为JPA提供了一种声明式的方法来处理数据访问层。通过使用Spring Data...

    Spring Data JPA.zip

    **Spring Data JPA 深度解析** Spring Data JPA 是 Spring Framework 的一个重要模块,它为 Java Persistence API (JPA) 提供了便捷的数据访问层。这个框架简化了数据库操作,使得开发人员能够以声明式的方式处理...

    spring Data Jpa入门

    Spring Framework对JPA的支持本身就很强大,我们不用理会EntityManager的创建,事务处理等等.Spring又进步了,只需要声明一下方法接口,Spring Data JPA可以帮你完成数据访问层的实现代码,开发者把更多的心思放在业务...

    Spring Data JPA入门项目01

    在这个"Spring Data JPA入门项目01"中,我们将探讨如何利用Spring Data JPA来实现基本的CRUD(创建、读取、更新和删除)功能。 首先,我们需要在项目中引入Spring Data JPA的相关依赖。这通常在Maven或Gradle的配置...

    Spring-data-jpa常用教程.pdf

    #### 三、Spring-data-jpa 的基本使用方式 1. **定义实体类**: - 实体类需要使用 `@Entity` 注解标注,并定义主键、字段等属性。 2. **创建 Repository 接口**: - 继承 `JpaRepository, ID&gt;` 接口,其中 `T` ...

    Spring Data JPA的优点和难点.pdf

    Spring Data JPA是Spring生态中的一个强大ORM框架,它极大地提高了Java开发者在处理数据库操作时的效率。Spring Data JPA的主要优点在于其高度的开发效率、成熟的语法结构以及与Spring框架的紧密集成。 1. **开发...

    spring学习:spring data jpa

    Spring Data JPA是Spring框架的一个模块,主要目的是简化Java企业级应用中数据访问层的开发。这个框架构建在JPA(Java Persistence API)之上,提供了一种声明式的方式来操作数据库,使得开发者无需编写大量的SQL...

    Spring+Spring MVC+SpringData JPA整合完成增删改查,翻页实例.zip

    在这个"Spring+Spring MVC+SpringData JPA整合完成增删改查,翻页实例"中,我们将深入探讨这三个组件如何协同工作,实现高效的数据管理与用户交互。 首先,Spring MVC是Spring框架的一个模块,专门用于构建Web应用...

    spring data jpa 教程

    整个教程贯穿了 Spring Data JPA 的学习路径,从最基本的入门知识,到方法命名约定查询、自定义扩展 Repository 接口,再到复杂查询的 Specifications 的使用,为 Java 开发者提供了一套系统化的学习路线。...

    SpringMVC+Spring+Spring Data JPA+Maven

    技术架构:SpringMVC3+Spring3.1.2+Spring Data JPA+Maven 声明:该应用仅仅是技术研究:Spring Data JPA的配置和常见api的使用&maven构建项目,其他技术不在此研究 内涵sql和各种Spring Data JPA测试和案例,导入&...

Global site tag (gtag.js) - Google Analytics