Spring Data JPA 使用总结

/ Java / 0 条评论 / 789浏览

Spring Data JPA 基本使用

大体内容

一、 创建SpringDataJPA项目
    1   导入依赖
    2   配置数据源信息
    3   编写Dao
    4   user
    5   编写测试代码
二、 Spring Data JPA 的接口继承结构
三、 Spring Data JPA 的运行原理
四、 Repository 接口
    1 方法名称命名规则查询
    2 基于@Query 注解的查询
        2.1通过 JPQL 语句查询
        2.2通过 SQL 语句查询
    3 通过@Query 注解完成数据更新
五、 CrudRepository 接口
六、 PagingAndSortingRepository 接口
    1 分页处理
    2 排序的处理
七、 JpaRepository 接口
八、 JpaSpecificationExecutor 接口
    1 单条件查询
    2 多条件查询
        2.1给定查询条件方式一
        2.2 给定查询条件方式二
    3 分页
    4 排序
    5 分页与排序
九、 用户自定义Repository接口
十、 关联映射操作 
    1 一对一的关联关系
    2 一对多的关联关系
    3 多对多的关联关系

Spring Data JPA:

Spring Data JPA 是 spring data 项目下的一个模块。提供了一套基于 JPA标准操作数据库的简化方案。底层默认的是依赖 Hibernate JPA 来实现的。

Spring Data JPA 的技术特点:

我们只需要定义接口并集成 Spring Data JPA 中所提供的接口就可以了。不需要编写接口实现类。

一、 创建SpringDataJPA项目

1 导入依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

2 配置数据源信息

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useSSL=false
spring.datasource.username=root
spring.datasource.password=tianya
spring.jpa.hibernate.ddl-auto=none
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
server.port=8010
logging.level.org.springframework=error
#spring.jpa.generate-ddl=
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.type=trace
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.properties.hibernate.jdbc.batch_size=50
logging.level.org.hibernate.type.descriptor.sql=trace

3 编写Dao

public interface UsersDao extends JpaRepository<Users, Integer> {}

4 User

import java.io.Serializable;

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

@Entity @Table(name="t_users") public class Users implements Serializable{

<span class="hljs-meta">@Id</span>
<span class="hljs-meta">@GeneratedValue</span>(strategy=GenerationType.IDENTITY)<span class="hljs-comment">//strategy=GenerationType.IDENTITY 自增长</span>
<span class="hljs-meta">@Column</span>(name=<span class="hljs-string">&quot;userid&quot;</span>)
<span class="hljs-keyword">private</span> Integer userid;

<span class="hljs-meta">@Column</span>(name=<span class="hljs-string">&quot;username&quot;</span>)
<span class="hljs-keyword">private</span> String username;

<span class="hljs-meta">@Column</span>(name=<span class="hljs-string">&quot;userage&quot;</span>)
<span class="hljs-keyword">private</span> Integer userage;

<span class="hljs-function"><span class="hljs-keyword">public</span> Integer <span class="hljs-title">getUserid</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">return</span> userid;
}

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setUserid</span><span class="hljs-params">(Integer userid)</span> </span>{
    <span class="hljs-keyword">this</span>.userid = userid;
}

<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getUsername</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">return</span> username;
}

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setUsername</span><span class="hljs-params">(String username)</span> </span>{
    <span class="hljs-keyword">this</span>.username = username;
}

<span class="hljs-function"><span class="hljs-keyword">public</span> Integer <span class="hljs-title">getUserage</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">return</span> userage;
}

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setUserage</span><span class="hljs-params">(Integer userage)</span> </span>{
    <span class="hljs-keyword">this</span>.userage = userage;
}

<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;Users [userid=&quot;</span> + userid + <span class="hljs-string">&quot;, username=&quot;</span> + username + <span class="hljs-string">&quot;, userage=&quot;</span> + userage + <span class="hljs-string">&quot;]&quot;</span>;
}

}

5 编写测试代码

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class UsersDaoImplTest {
@Autowired
private UsersDao usersDao;
/**
* 添加用户
*/
@Test
@Transactional// 在测试类对于事务提交方式默认的是回滚。
@Rollback(false)//取消自动回滚
public void testInsertUsers(){
Users users = new Users();
users.setUserage(24);
users.setUsername("张三");
this.usersDao.save(users);
}

}

二、 Spring Data JPA 的接口继承结构

三、 Spring Data JPA 的运行原理

@PersistenceContext(name="entityManagerFactory")
private EntityManager em;
@Test
public void test1(){
//org.springframework.data.jpa.repository.support.SimpleJpaRepositor y@fba8bf
//System.out.println(this.usersDao);
//class com.sun.proxy.$Proxy29 代理对象 是基于 JDK 的动态代理方式创建的
//System.out.println(this.usersDao.getClass());
JpaRepositoryFactory factory = new JpaRepositoryFactory(em);
//getRepository(UsersDao.class);可以帮助我们为接口生成实现类。而 这个实现类是 SimpleJpaRepository 的对象
//要求:该接口必须要是继承 Repository 接口
UsersDao ud = factory.getRepository(UsersDao.class);
System.out.println(ud);
System.out.println(ud.getClass());
}

四、 Repository 接口

Repository 接口是 Spring Data JPA 中为我我们提供的所有接口中的顶层接口 Repository 提供了两种查询方式的支持
1)基于方法名称命名规则查询
2)基于@Query 注解查询

1 方法名称命名规则查询

规则:
findBy(关键字)+属性名称(属性名称的首字母大写)+查询条件(首字母大写)
关键字 方法命名 sql where 字句
And findByNameAndPwd where name= ? and pwd =?
Or findByNameOrSex where name= ? or sex=?
Is,Equal findById, findByIdEquals
Between findByIdBetween where id between ? and ?
LessThan findByIdLessThan where id < ?
LessThanEqual findByIdLessThanEquals where id <= ?
GreaterThan findByIdGreaterThan where id > ?
GreaterThanEqual findByIdGreaterThanEquals where id > = ?
After findByIdAfter where id > ?
Before findByIdBefore where id < ?
IsNull findByNameIsNull where name is null
isNotNull,Not Null findByNameNotNull where name is not
Like findByNameLike where name like ?
NotLike findByNameNotLike where name not like ?
StartingWith findByNameStartingWith where name like '?%'
EndingWith findByNameEndingWith where name like '%?'
Containing findByNameContaining where name like '%?%'
OrderBy findByIdOrderByXDesc where id=? order by x desc
Not findByNameNot where name <> ?
In findByIdIn(Collection<?> c) where id in (?)
NotIn findByIdNotIn(Collection<?> c) where id not in (?)
True findByAaaTue where aaa = true
False findByAaaFalse where aaa = false
IgnoreCase findByNameIgnoreCase where UPPER(name)=UPPER(?)

创建接口

/**

  • Repository接口讲解
  • @author Administrator

/ public interface UsersDao extends Repository<Users, Integer> { //方法名称命名规则 List<Users> findByUsernameIs(String string); List<Users> findByUsernameLike(String string); List<Users> findByUsernameAndUserageGreaterThanEqual(String name,Integer age); }

测试类

/*

  • Repository接口测试
  • @author Administrator

*/ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class RepositoryTest {

@Autowired
<span class="hljs-keyword">private</span> UsersDao usersDao;

<span class="hljs-comment">/**
 * 需求:使用用户名作为查询条件
 */</span>
@<span class="hljs-function">Test
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">test1</span><span class="hljs-params">()</span></span>{
    <span class="hljs-comment">/**
     * 判断相等的条件,有三种表示方式
     * 1,什么都不写,默认的就是做相等判断
     * 2,Is
     * 3,Equal
     */</span>
    List&lt;Users&gt; <span class="hljs-built_in">list</span> = <span class="hljs-keyword">this</span>.usersDao.findByUsernameIs(<span class="hljs-string">&quot;王五&quot;</span>);
    <span class="hljs-keyword">for</span> (Users users : <span class="hljs-built_in">list</span>) {
        System.out.println(users);
    }
}

<span class="hljs-comment">/**
 * 需求:根据用户姓名做Like处理
 * Like:条件关键字
 */</span>
@<span class="hljs-function">Test
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">test2</span><span class="hljs-params">()</span></span>{
    List&lt;Users&gt; <span class="hljs-built_in">list</span> = <span class="hljs-keyword">this</span>.usersDao.findByUsernameLike(<span class="hljs-string">&quot;王%&quot;</span>);
    <span class="hljs-keyword">for</span> (Users users : <span class="hljs-built_in">list</span>) {
        System.out.println(users);
    }
}

<span class="hljs-comment">/**
 * 需求:查询名称为王五,并且他的年龄大于等于22岁
 */</span>
@<span class="hljs-function">Test
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">test3</span><span class="hljs-params">()</span></span>{
    List&lt;Users&gt; <span class="hljs-built_in">list</span> = <span class="hljs-keyword">this</span>.usersDao.findByUsernameAndUserageGreaterThanEqual(<span class="hljs-string">&quot;王五&quot;</span>, <span class="hljs-number">22</span>);
    <span class="hljs-keyword">for</span> (Users users : <span class="hljs-built_in">list</span>) {
        System.out.println(users);
    }
}

}

2 基于@Query 注解的查询

2.1通过 JPQL 语句查询

JPQL:
通过 Hibernate 的 HQL 演变过来的。他和 HQL 语法及其相似。

创建接口

/**

  • Repository接口讲解
  • @author Administrator

*/ public interface UsersDao extends Repository<Users, Integer> {
//使用@Query注解查询 @Query(value="from Users where username = ?") List<Users> queryUserByNameUseJPQL(String name);

<span class="hljs-meta">@Query</span>(<span class="hljs-string">&quot;from Users where username like ?&quot;</span>)
<span class="hljs-built_in">List</span>&lt;Users&gt; queryUserByLikeNameUseJPQL(<span class="hljs-built_in">String</span> name);

<span class="hljs-meta">@Query</span>(<span class="hljs-string">&quot;from Users where username = ? and userage &gt;= ?&quot;</span>)
<span class="hljs-built_in">List</span>&lt;Users&gt; queryUserByNameAndAge(<span class="hljs-built_in">String</span> name,Integer age); 

}

测试类

/**

  • Repository接口测试
  • @author Administrator

*/ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class RepositoryTest {

<span class="hljs-meta">@Autowired</span>
<span class="hljs-keyword">private</span> UsersDao usersDao;

<span class="hljs-comment">/**
 * 测试<span class="hljs-doctag">@Query</span>查询 JPQL
 */</span>
<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> test4(){
    List&lt;Users&gt; list = <span class="hljs-keyword">this</span>.usersDao.queryUserByNameUseJPQL(<span class="hljs-string">&quot;王五&quot;</span>);
    <span class="hljs-keyword">for</span> (Users <span class="hljs-string">users :</span> list) {
        System.out.println(users);
    }
}

<span class="hljs-comment">/**
 * 测试<span class="hljs-doctag">@Query</span>查询 JPQL
 */</span>
<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> test5(){
    List&lt;Users&gt; list = <span class="hljs-keyword">this</span>.usersDao.queryUserByLikeNameUseJPQL(<span class="hljs-string">&quot;王%&quot;</span>);
    <span class="hljs-keyword">for</span> (Users <span class="hljs-string">users :</span> list) {
        System.out.println(users);
    }
}

<span class="hljs-comment">/**
 * 测试<span class="hljs-doctag">@Query</span>查询 JPQL
 */</span>
<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> test6(){
    List&lt;Users&gt; list = <span class="hljs-keyword">this</span>.usersDao.queryUserByNameAndAge(<span class="hljs-string">&quot;王五&quot;</span>, <span class="hljs-number">22</span>);
    <span class="hljs-keyword">for</span> (Users <span class="hljs-string">users :</span> list) {
        System.out.println(users);
    }
}

}

2.2通过 SQL 语句查询

接口

/**

  • Repository接口讲解
  • @author Administrator

*/ public interface UsersDao extends Repository<Users, Integer> { //使用@Query注解查询SQL //nativeQuery:默认的是false.表示不开启sql查询。是否对value中的语句做转义。 @Query(value="select * from t_users where username = ?",nativeQuery=true) List<Users> queryUserByNameUseSQL(String name);

<span class="hljs-meta">@Query</span>(value=<span class="hljs-string">&quot;select * from t_users where username like ?&quot;</span>,nativeQuery=<span class="hljs-keyword">true</span>)
<span class="hljs-built_in">List</span>&lt;Users&gt; queryUserByLikeNameUseSQL(<span class="hljs-built_in">String</span> name);

<span class="hljs-meta">@Query</span>(value=<span class="hljs-string">&quot;select * from t_users where username = ? and userage &gt;= ?&quot;</span>,nativeQuery=<span class="hljs-keyword">true</span>)
<span class="hljs-built_in">List</span>&lt;Users&gt; queryUserByNameAndAgeUseSQL(<span class="hljs-built_in">String</span> name,Integer age);

}

测试类

/**

  • Repository接口测试
  • @author Administrator

*/ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class RepositoryTest {

<span class="hljs-meta">@Autowired</span>
<span class="hljs-keyword">private</span> UsersDao usersDao;

<span class="hljs-comment">/**
 * 测试<span class="hljs-doctag">@Query</span>查询 SQL
 */</span>
<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> test7(){
    List&lt;Users&gt; list = <span class="hljs-keyword">this</span>.usersDao.queryUserByNameUseSQL(<span class="hljs-string">&quot;王五&quot;</span>);
    <span class="hljs-keyword">for</span> (Users <span class="hljs-string">users :</span> list) {
        System.out.println(users);
    }
}

<span class="hljs-comment">/**
 * 测试<span class="hljs-doctag">@Query</span>查询 SQL
 */</span>
<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> test8(){
    List&lt;Users&gt; list = <span class="hljs-keyword">this</span>.usersDao.queryUserByLikeNameUseSQL(<span class="hljs-string">&quot;王%&quot;</span>);
    <span class="hljs-keyword">for</span> (Users <span class="hljs-string">users :</span> list) {
        System.out.println(users);
    }
}

<span class="hljs-comment">/**
 * 测试<span class="hljs-doctag">@Query</span>查询 SQL
 */</span>
<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> test9(){
    List&lt;Users&gt; list = <span class="hljs-keyword">this</span>.usersDao.queryUserByNameAndAgeUseSQL(<span class="hljs-string">&quot;王五&quot;</span>, <span class="hljs-number">22</span>);
    <span class="hljs-keyword">for</span> (Users <span class="hljs-string">users :</span> list) {
        System.out.println(users);
    }
}

}

3 通过@Query 注解完成数据更新

接口

/**

  • Repository接口讲解
  • @author Administrator

/ public interface UsersDao extends Repository<Users, Integer> { @Query("update Users set userage = ? where userid = ?") @Modifying //@Modifying当前语句是一个更新语句 void updateUserAgeById(Integer age,Integer id); }

测试类

/*

  • Repository接口测试
  • @author Administrator

*/ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class RepositoryTest {

<span class="hljs-variable">@Autowired</span>
private UsersDao usersDao;

<span class="hljs-comment">/**
 * 测试@Query update
 */</span>
<span class="hljs-variable">@Test</span>
<span class="hljs-variable">@Transactional</span>
<span class="hljs-variable">@Rollback</span>(false)
public void test10(){
    <span class="hljs-selector-tag">this</span><span class="hljs-selector-class">.usersDao</span><span class="hljs-selector-class">.updateUserAgeById</span>(<span class="hljs-number">24</span>, <span class="hljs-number">5</span>);
}

}

五、 CrudRepository 接口

1 创建接口

/**

  • CrudRepository接口讲解
  • @author Administrator

*/ public interface UsersDao extends CrudRepository<Users, Integer> {

}

2 测试代码

/**

  • CrudRepository接口测试
  • @author Administrator

*/ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class RepositoryTest {

@Autowired
<span class="hljs-keyword">private</span> UsersDao usersDao;

<span class="hljs-comment">/**
 * 添加单条数据
 */</span>
@<span class="hljs-function">Test
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">test1</span><span class="hljs-params">()</span></span>{
    Users user = <span class="hljs-keyword">new</span> Users();
    user.setUserage(<span class="hljs-number">21</span>);
    user.setUsername(<span class="hljs-string">&quot;赵小丽&quot;</span>);
    <span class="hljs-keyword">this</span>.usersDao.save(user);
}

<span class="hljs-comment">/**
 * 批量添加数据
 */</span>
@<span class="hljs-function">Test
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">test2</span><span class="hljs-params">()</span></span>{
    Users user = <span class="hljs-keyword">new</span> Users();
    user.setUserage(<span class="hljs-number">21</span>);
    user.setUsername(<span class="hljs-string">&quot;赵小丽&quot;</span>);
    
    Users user1 = <span class="hljs-keyword">new</span> Users();
    user1.setUserage(<span class="hljs-number">25</span>);
    user1.setUsername(<span class="hljs-string">&quot;王小虎&quot;</span>);
    
    List&lt;Users&gt; <span class="hljs-built_in">list</span>= <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();
    <span class="hljs-built_in">list</span>.add(user);
    <span class="hljs-built_in">list</span>.add(user1);
    
    <span class="hljs-keyword">this</span>.usersDao.save(<span class="hljs-built_in">list</span>);
    
}

<span class="hljs-comment">/**
 * 根据ID查询单条数据
 */</span>
@<span class="hljs-function">Test
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">test3</span><span class="hljs-params">()</span></span>{
    Users users = <span class="hljs-keyword">this</span>.usersDao.findOne(<span class="hljs-number">13</span>);
    System.out.println(users);
}

<span class="hljs-comment">/**
 * 查询全部数据
 */</span>
@<span class="hljs-function">Test
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">test4</span><span class="hljs-params">()</span></span>{
    List&lt;Users&gt; <span class="hljs-built_in">list</span> = (List&lt;Users&gt;)<span class="hljs-keyword">this</span>.usersDao.findAll();
    <span class="hljs-keyword">for</span> (Users users : <span class="hljs-built_in">list</span>) {
        System.out.println(users);
    }
}

<span class="hljs-comment">/**
 * 删除数据
 */</span>
@<span class="hljs-function">Test
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">test5</span><span class="hljs-params">()</span></span>{
    <span class="hljs-keyword">this</span>.usersDao.<span class="hljs-keyword">delete</span>(<span class="hljs-number">13</span>);
}

<span class="hljs-comment">/**
 * 更新数据 方式一
 */</span>
@<span class="hljs-function">Test
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">test6</span><span class="hljs-params">()</span></span>{
    Users user = <span class="hljs-keyword">this</span>.usersDao.findOne(<span class="hljs-number">12</span>);
    user.setUsername(<span class="hljs-string">&quot;王小红&quot;</span>);
    <span class="hljs-keyword">this</span>.usersDao.save(user);
}

<span class="hljs-comment">/**
 * 更新数据 方式二
 */</span>
@Test
@Transactional
@Rollback(<span class="hljs-literal">false</span>)
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">test7</span><span class="hljs-params">()</span></span>{
    Users user = <span class="hljs-keyword">this</span>.usersDao.findOne(<span class="hljs-number">12</span>);<span class="hljs-comment">//持久化状态的</span>
    user.setUsername(<span class="hljs-string">&quot;王小小&quot;</span>);
}

}

六、 PagingAndSortingRepository 接口

1 分页处理

1.1创建接口

/**

  • PagingAndSortingRepository接口讲解
  • @author Administrator

/ public interface UsersDao extends PagingAndSortingRepository<Users, Integer>{ }

1.2测试代码

/*

  • CrudRepository接口测试
  • @author Administrator

*/ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class RepositoryTest {

<span class="hljs-meta">@Autowired</span>
<span class="hljs-keyword">private</span> UsersDao usersDao;

<span class="hljs-comment">/**
 * 分页
 */</span>
<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> test1(){
    <span class="hljs-keyword">int</span> page = <span class="hljs-number">2</span>; <span class="hljs-comment">//page:当前页的索引。注意索引都是从0开始的。</span>
    <span class="hljs-keyword">int</span> size = <span class="hljs-number">3</span>;<span class="hljs-comment">// size:每页显示3条数据</span>
    Pageable pageable= <span class="hljs-keyword">new</span> PageRequest(page, size);
    Page&lt;Users&gt; p = <span class="hljs-keyword">this</span>.usersDao.findAll(pageable);
    System.out.println(<span class="hljs-string">&quot;数据的总条数:&quot;</span>+p.getTotalElements());
    System.out.println(<span class="hljs-string">&quot;总页数:&quot;</span>+p.getTotalPages());
    List&lt;Users&gt; list = p.getContent();
    <span class="hljs-keyword">for</span> (Users <span class="hljs-string">users :</span> list) {
        System.out.println(users);
    }
}

}

2 排序的处理

2.1测试代码

/**

  • CrudRepository接口测试
  • @author Administrator

*/ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class RepositoryTest {

<span class="hljs-meta">@Autowired</span>
<span class="hljs-keyword">private</span> UsersDao usersDao;
    
<span class="hljs-comment">/**
 * 对单列做排序处理
 */</span>
<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> test2(){
    <span class="hljs-comment">//Sort:该对象封装了排序规则以及指定的排序字段(对象的属性来表示)</span>
    <span class="hljs-comment">//direction:排序规则</span>
    <span class="hljs-comment">//properties:指定做排序的属性</span>
    Sort sort = <span class="hljs-keyword">new</span> Sort(Direction.DESC,<span class="hljs-string">&quot;userid&quot;</span>);
    List&lt;Users&gt; list = (List&lt;Users&gt;)<span class="hljs-keyword">this</span>.usersDao.findAll(sort);
    <span class="hljs-keyword">for</span> (Users <span class="hljs-string">users :</span> list) {
        System.out.println(users);
    }
}

<span class="hljs-comment">/**
 * 多列的排序处理
 */</span>
<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> test3(){
    <span class="hljs-comment">//Sort:该对象封装了排序规则以及指定的排序字段(对象的属性来表示)</span>
    <span class="hljs-comment">//direction:排序规则</span>
    <span class="hljs-comment">//properties:指定做排序的属性</span>
    Order order1 = <span class="hljs-keyword">new</span> Order(Direction.DESC,<span class="hljs-string">&quot;userage&quot;</span>);
    Order order2 = <span class="hljs-keyword">new</span> Order(Direction.ASC,<span class="hljs-string">&quot;username&quot;</span>);
    Sort sort = <span class="hljs-keyword">new</span> Sort(order1,order2);
    List&lt;Users&gt; list = (List&lt;Users&gt;)<span class="hljs-keyword">this</span>.usersDao.findAll(sort);
    <span class="hljs-keyword">for</span> (Users <span class="hljs-string">users :</span> list) {
        System.out.println(users);
    }
}

}

七、 JpaRepository 接口

JpaRepository 接口是我们开发时使用的最多的接口。其特点是可以帮助我们将其他接口的方法的返回值做适配处理。可以使得我们在开发时更方便的使用这些方法。

创建接口

/**

  • JpaRepository接口讲解
  • @author Administrator

*/ public interface UsersDao extends JpaRepository<Users, Integer>{

}

测试类

/**

  • JpaRepository接口测试
  • @author Administrator

*/ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class RepositoryTest {

<span class="hljs-meta">@Autowired</span>
<span class="hljs-keyword">private</span> UsersDao usersDao;

<span class="hljs-comment">/**
 * 查询全部数据
 */</span>
<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> test1(){
    List&lt;Users&gt; list  = <span class="hljs-keyword">this</span>.usersDao.findAll();
    <span class="hljs-keyword">for</span> (Users <span class="hljs-string">users :</span> list) {
        System.out.println(users);
    }
}

}

八、 JpaSpecificationExecutor 接口

完成多条件查询,并且支持分页与排序

1 单条件查询

1.1创建接口

/**

  • JpaSpecificationExecutor接口讲解
  • @author Administrator *注意:JpaSpecificationExecutor<Users>:不能单独使用,需要配合着jpa中的其他接口一起使用 */ public interface UsersDao extends JpaRepository<Users, Integer>,JpaSpecificationExecutor<Users>{

}

测试接口

/**

  • JpaRepository接口测试
  • @author Administrator

*/ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class RepositoryTest {

<span class="hljs-meta">@Autowired</span>
<span class="hljs-keyword">private</span> UsersDao usersDao;

<span class="hljs-comment">/**
 * 需求:根据用户姓名查询数据
 */</span>
<span class="hljs-meta">@Test</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">test1</span><span class="hljs-params">()</span></span>{
    Specification&lt;Users&gt; spec = <span class="hljs-keyword">new</span> Specification&lt;Users&gt;() {

        <span class="hljs-comment">/**
         * <span class="hljs-doctag">@return</span> Predicate:定义了查询条件
         * <span class="hljs-doctag">@param</span> Root&lt;Users&gt; root:根对象。封装了查询条件的对象
         * <span class="hljs-doctag">@param</span> CriteriaQuery&lt;?&gt; query:定义了一个基本的查询。一般不使用
         * <span class="hljs-doctag">@param</span> CriteriaBuilder cb:创建一个查询条件
         */</span>
        <span class="hljs-meta">@Override</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> Predicate <span class="hljs-title">toPredicate</span><span class="hljs-params">(Root&lt;Users&gt; root, CriteriaQuery&lt;?&gt; query, CriteriaBuilder cb)</span> </span>{
            Predicate pre = cb.equal(root.get(<span class="hljs-string">&quot;username&quot;</span>), <span class="hljs-string">&quot;王五&quot;</span>);
            <span class="hljs-keyword">return</span> pre;
        }
    };
    List&lt;Users&gt; list = <span class="hljs-keyword">this</span>.usersDao.findAll(spec);
    <span class="hljs-keyword">for</span> (Users users : list) {
        System.out.println(users);
    }
}

}

2 多条件查询

2.1给定查询条件方式一

    /**
* 多条件查询 方式一
* 需求:使用用户姓名以及年龄查询数据
*/
@Test
public void test2(){
Specification<Users> spec = new Specification<Users>() {

        @Override
        <span class="hljs-keyword">public</span> Predicate toPredicate(Root&lt;Users&gt; root, CriteriaQuery&lt;?&gt; query, CriteriaBuilder cb) {
            List&lt;Predicate&gt; <span class="hljs-built_in">list</span> = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();
            <span class="hljs-built_in">list</span>.add(cb.equal(root.get(<span class="hljs-string">&quot;username&quot;</span>),<span class="hljs-string">&quot;王五&quot;</span>));
            <span class="hljs-built_in">list</span>.add(cb.equal(root.get(<span class="hljs-string">&quot;userage&quot;</span>),<span class="hljs-number">24</span>));
            <span class="hljs-comment">//此时条件之间是没有任何关系的。</span>
            Predicate[] arr = <span class="hljs-keyword">new</span> Predicate[<span class="hljs-built_in">list</span>.size()];
            <span class="hljs-keyword">return</span> cb.<span class="hljs-keyword">and</span>(<span class="hljs-built_in">list</span>.toArray(arr));
        }
        
    };
    List&lt;Users&gt; <span class="hljs-built_in">list</span> = <span class="hljs-keyword">this</span>.usersDao.findAll(spec);
    <span class="hljs-keyword">for</span> (Users users : <span class="hljs-built_in">list</span>) {
        System.out.println(users);
    }
}