栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

使用Spring Data轻松操作数据库

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Spring Data轻松操作数据库

一、Spring Data简介

Spring Data官网:https://spring.io/projects/spring-data

Spring Data是Spring的一个子项目,它是为了简化数据库的操作访问而生的,为开发者提供了统一的,一致性的操作数据库的接口。

Spring Data又包含多个子项目,常用的有:

Spring Date JPA: 目的是为了减少数据层的开发量,提供了操作数据库的接口。 

Spring Date MongoDB:为操作MongoDB数据库提供了接口支持,在大数据层用的比较多。 

Spring Date Redis:为操作Redis数据库提供了相关的接口支持。

Spring Date Solr:提供对Solr的接口支持。Solr是一个高性能,具有搜索功能 ,对查询性能优化的一个全文搜索引擎。

二、如何使用Spring Data

maven地址:https://mvnrepository.com/search?q=Spring+Data

在项目的pom.xml文件引入如下依赖即可:

(1)JPA:


    org.springframework.data
    spring-data-jpa
    2.1.10.RELEASE



    org.hibernate
    hibernate-entitymanager
    5.4.2.Final

(2)MongoDB


    org.springframework.data
    spring-data-mongodb
    2.1.10.RELEASE

(3)Redis


    org.springframework.data
    spring-data-redis
    2.1.10.RELEASE

三、Spring Data提供的相关接口

(1) Repository:

Repository接口是Spring Data的核心接口,它不提供任何方法,是一个空接口。

我们定义的接口 xxxRepository extends Repository,表示此接口纳入spring管理,需按一定规则定义方法。

如果我们不想继承Repository接口,可以通过注解来实现同样的功能,如下:

@RepositoryDefinition(domainClass = 实体类名.class,idClass=实体类的主键封装类型.class)

Repository接口的源码如下:

package org.springframework.data.repository;

import org.springframework.stereotype.Indexed;

@Indexed
public interface Repository {

}


(2)CrudRepository:

CrudRepository接口继承Repository,实现了CURD相关的方法 ,具体如图。


(3)JpaRepository

JpaRepository接口继承PagingAndSortingRepository,实现JPA规范相关的方法 ,具体如下:


(4)PagingAndSortingRepository

PagingAndSortingRepository接口继承CrudRepository,实现了分布排序相关方法。

该接口包含分页和排序功能。

带排序的查询:findAll(Sort sort)。

带排序的分页查询:findAll(Pageable pageable)。


CRUDRepository 继承Repository 

PagingAndSortingRepository 继承CRUDRepository

JpaRepository 继承PagingAndSortingRepository 

意味着只需继承接口JpaRepository, 便有了以上所有接口的功能 。

四、实战应用

1. 项目结构

2. pom.xml文件配置


    
    
        mysql
        mysql-connector-java
        8.0.11
    
    
        junit
        junit
        4.11
    
    
    
        org.hamcrest
        hamcrest-core
        1.3
        test
    

    
    
        org.springframework
        spring-jdbc
        5.1.5.RELEASE
    
    
    
        org.springframework
        spring-context
        5.1.5.RELEASE
    

    
    
        org.springframework.data
        spring-data-jpa
        2.1.10.RELEASE
    
    
    
        org.hibernate
        hibernate-entitymanager
        5.4.2.Final
    

3. db.properties配置:

#数据库配置信息
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
jdbc.username=root
jdbc.password=root

4. beans.xml配置:






    

    
       

        
        
        
        
    

    
        
    

    
        
    

5. beans-new.xml配置:





    

    
    
        

        
        
        
        
    

    
    
        
        
            
        
        

        
        
            
                org.hibernate.cfg.ImprovedNamingStrategy
                org.hibernate.dialect.MySQL5InnoDBDialect
                true
                true
                update  
            
        

    

    
    
        
    

    
    

    
    

    

6. EmployeeRepository.java接口

package com.lhf.spring.repository;

import com.lhf.spring.domain.Employee;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.RepositoryDefinition;
import org.springframework.data.repository.query.Param;

import java.util.List;



@RepositoryDefinition(domainClass = Employee.class, idClass = Integer.class)
public interface EmployeeRepository { //extends Repository{

    public Employee findByName(String name);

    
    public List findByNameStartingWithAndAgeLessThan(String name, Integer age);

    
    public List findByNameEndingWithAndAgeLessThan(String name, Integer age);

    
    public List findByNameInOrAgeLessThan(List name, Integer age);

    
    public List findByNameInAndAgeLessThan(List name, Integer age);

    
    @Query("select o from Employee o where id=(select max(id) from Employee t1)")
    public Employee getEmployeeByMaxId();

    
    @Query("select o from Employee o where o.name=?1 and o.age=?2")
    public List queryParams1(String name, Integer age);

    
    @Query("select o from Employee o where o.name=:name or o.age=:age")
    public List queryParams2(@Param("name") String name, @Param("age") Integer age);

    
    @Query("select o from Employee o where o.name like %?1%")
    public List queryLike1(String name);

    @Query("select o from Employee o where o.name like %:name%")
    public List queryLike2(@Param("name")String name);

    
    @Query("select count(*) from Employee")
    public long getCount();

    @Query(nativeQuery = true, value = "select count(1) from Employee")
    public long getCount1();

    
    @Modifying
    @Query("update Employee o set o.age = :age where o.id = :id")
    public void update(@Param("id")Integer id, @Param("age")Integer age);
}

7. EmployeeCrudRepository.java接口:

package com.lhf.spring.repository;

import com.lhf.spring.domain.Employee;
import org.springframework.data.repository.CrudRepository;


public interface EmployeeCrudRepository extends CrudRepository {
}

8. EmployeeJpaRepository.java接口

package com.lhf.spring.repository;

import com.lhf.spring.domain.Employee;
import org.springframework.data.jpa.repository.JpaRepository;


public interface EmployeeJpaRepository extends JpaRepository {

}

9. EmployeePagingAndSortingRespsitory.java接口

package com.lhf.spring.repository;

import com.lhf.spring.domain.Employee;
import org.springframework.data.repository.PagingAndSortingRepository;


public interface EmployeePagingAndSortingRespsitory extends PagingAndSortingRepository {

}

10. EmployeeJpaSpecificationExecutorRepository.java接口

package com.lhf.spring.repository;

import com.lhf.spring.domain.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;


public interface EmployeeJpaSpecificationExecutorRepository extends JpaRepository,
        JpaSpecificationExecutor {
}

由于篇幅问题,其他相关代码不在展示了,源码见github:

https://github.com/JavaCodeMood/spring-data-study.git

分享就到这里,感兴趣的读者自行下载源码,记得Star一下,感谢诸君的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/239081.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号