springdata-jpa 八种查询方法

使用:maven+Spring+jpa+Junit4

查询方式:SQL,JPQL查询,Specification多条件复杂查询

返回类型:list<POJO>,list<Stinrg>,list<Object>,Page<Object>

1. Pom.xml

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.litblack</groupId>
  <artifactId>SpringData_jpa</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringData_jpa Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
        <spring.version>4.3.4.RELEASE</spring.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- jpa -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.8.Final</version>
             <exclusions>
                <exclusion>
                    <groupId>org.javassist</groupId>
                    <artifactId>javassist</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
        </dependency> -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.11.Final</version>
            <exclusions>
                <exclusion>
                    <groupId>org.javassist</groupId>
                    <artifactId>javassist</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- oracle -->
        <dependency>
            <groupId>ojdbc</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.4</version>
        </dependency>
        <!-- mysql  -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!-- ali 数据源连接 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.31</version>
        </dependency>

        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.12.1.GA</version>
        </dependency>

        <!-- Test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- springdata -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.11.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons-core</artifactId>
            <version>1.4.1.RELEASE</version>
        </dependency>
  </dependencies>
  <build>
    <finalName>SpringData_jpa</finalName>
  </build>
</project>

pom.xml

2. Spring-config.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:cache="http://www.springframework.org/schema/cache"
    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-3.1.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.1.xsd
          http://www.springframework.org/schema/aop
          http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
          http://www.springframework.org/schema/cache
          http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
          http://www.springframework.org/schema/data/jpa
          http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
          http://www.springframework.org/schema/data/repository
          http://www.springframework.org/schema/data/repository/spring-repository-1.5.xsd">
    <context:component-scan base-package="com.litblack.jpa"></context:component-scan>

    <!-- 配置Spring Data JPA扫描目录, repository 包 -->
    <jpa:repositories base-package="com.litblack.jpa" /> 

    <!-- 定义实体管理器工厂 -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 扫描pojo -->
        <property name="packagesToScan" value="com.litblack.jpa" />
        <property name="persistenceProvider">
            <bean class="org.hibernate.ejb.HibernatePersistence" />
        </property>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="generateDdl" value="true" />
                   <property name="database" value="MYSQL" />
                <!-- <property name="database" value="ORACLE" />  -->
                <!-- <property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" /> -->
                <property name="showSql" value="true" />
            </bean>
        </property>
        <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
        </property>
        <property name="jpaPropertyMap">
            <map>
                <entry key="hibernate.generate_statistics" value="false" /><!-- 关闭打印的日志 -->
                <entry key="hibernate.query.substitutions" value="true 1, false 0" />
                <entry key="hibernate.default_batch_fetch_size" value="16" />
                <entry key="hibernate.max_fetch_depth" value="2" />
                <entry key="hibernate.bytecode.use_reflection_optimizer" value="true" />
                <entry key="hibernate.cache.use_second_level_cache" value="false" />
                <entry key="hibernate.cache.use_query_cache" value="false" />
            </map>
        </property>
    </bean>

    <!-- 数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/cyd?useUnicode=true&amp;characterEncoding=UTF-8" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>
    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <!-- 启用 annotation事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

Spring-config.xml

3. UserBean.java

 

package com.litblack.jpa;

import java.util.Date;

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

import org.hibernate.annotations.GenericGenerator;
import org.springframework.stereotype.Component;

@Table(name = "cyd_sys_user")
@Entity
public class UserBean {

    @Id
    @GeneratedValue(generator = "system_uuid")
    @GenericGenerator(name = "system_uuid", strategy = "uuid")
    private String id;
    @Column(name="user_name")
    private String userName;
    @Column(name="create_time")
    private Date createTime;

    public String getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @Override
    public String toString() {
        return "UserBean [id=" + id + ", userName=" + userName + ", createTime=" + createTime + "]";
    }

}

POJO

4. UserBeanRepository.java

package com.litblack.jpa;

import java.util.List;
import java.util.Map;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
/**
 * SQL,JPQL查询
 * 返回:list<POJO>,list<Stinrg>,list<Object>,Page<Object>
 * 不能返回MAP
 * @author chenyd
 * 2018年1月10日
 */
public interface UserBeanRepository  extends JpaRepository<UserBean, Long>, JpaSpecificationExecutor<UserBean>{

    UserBean findByUserName(String username);

    @Query("from UserBean where userName =?1")
    List<UserBean> find_Jpql_list_obj(String username);

    @Query("select userName from UserBean where userName =?1")
    List<String> find_Jpql_list_one(String username);

    @Query("select userName,createTime from UserBean where userName =?1")
    List<Object> find_Jpql_list_morefield(String username);

    @Query("select userName,createTime from UserBean ")
    List<Object> find_Jpql_list_pojo_morefield();

    /**
     * 若返回类型为POJO,必须是所有POJO的所有字段,不能只查询某个字段
     */
    @Query(value="select * from cyd_sys_user",nativeQuery=true)
    List<UserBean> find_SQL_pojo();

    @Query(value="select user_name,name from cyd_sys_user,t_user",nativeQuery=true)
    List<Object> find_SQL_obj();

    /**
     * 分页需要 #pageable 标识
     * NativeJpaQuery
     * @param pageable
     * @return
     */
    @Query(value="select user_name,name from cyd_sys_user,t_user  /*#pageable*/  ",countQuery="select count(*) from cyd_sys_user,t_user",nativeQuery=true)
    Page<Object> find_SQL_obj(Pageable pageable);
}

5. BaseJunit4Test.java

package com.litblack.jpa;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:/spring-config.xml" })
public class BaseJunit4Test {

    @Autowired
    private UserBeanRepository userRepository;

    /**
     * 保存
     */
    public void save_obj() {
        System.out.println(userRepository);
        for (int i = 0; i < 100; i++) {
            UserBean entity = new UserBean();
            entity.setUserName("user_" + i);
            entity.setCreateTime(new Date());
            userRepository.save(entity);
        }

    }
    /**
     * 查询-所有
     */
    public void get_ALL_obj(){
        List<UserBean> list=userRepository.findAll();
        for (int i = 0; i < list.size(); i++) {
            UserBean obj = list.get(i);
            System.out.println(obj.getCreateTime());
        }
    }
    /**
     * 查询-one-obj,自定义接口
     */
    public void get_one_obj(){
        UserBean obj = userRepository.findByUserName("user_1");
        System.out.println(obj.toString());
    }
    /**
     * 根据JQPL查询,获取一个包含所有字段的OBJ
     * 返回: 一个pojo 集合
     */
    public void get_jqpl_obj(){
        List<UserBean> list=userRepository.find_Jpql_list_obj("user_2");
        for (int i = 0; i < list.size(); i++) {
            UserBean obj = list.get(i);
            System.out.println(obj.toString());
        }
    }
    /**
     * 根据JQPL查询,获取一个字段,
     * 返回:一个字段
     */
    public void get_jqpl_onestr(){
        List<String> list=userRepository.find_Jpql_list_one("user_2");
        for (int i = 0; i < list.size(); i++) {
            String obj = list.get(i);
            System.out.println(obj.toString());
        }
    }
    /**
     * 根据JQPL查询,一行数据,获取多个字段
     * 返回:object 不是POJO,不是string[]。是Object[]
     * 注意:每个数据类型与POJO类型一致
     */
    public void get_jqpl_morestr(){
        List<Object> list=userRepository.find_Jpql_list_morefield("user_2");
        for (int i = 0; i < list.size(); i++) {
            Object[] obj = (Object[]) list.get(i);
            String username=(String) obj[0];
            Date date=(Date) obj[1];
            System.out.println(username+"\t"+date);
        }
    }
    /**
     * JQPL  获取指定字段的多个POJO
     */
    public void get_jqpl_pojo_morestr(){
        List<Object> list=userRepository.find_Jpql_list_pojo_morefield();
        for (int i = 0; i < list.size(); i++) {
            Object[] obj = (Object[]) list.get(i);
            String username=(String) obj[0];
            Date date=(Date) obj[1];
            System.out.println(username+"\t"+date);
        }
    }
    /**
     * SQL  获取POJO的所有字段,必须是所有POJO的所有字段
     */
    public void get_sql_pojo_allstr(){
        List<UserBean> list=userRepository.find_SQL_pojo();
        for (int i = 0; i < list.size(); i++) {
            UserBean obj = list.get(i);
            System.out.println(obj.toString());
        }
    }
    /**
     * SQL  获取多表查询的字段,可用于多表查询,组成临时表
     * 注意:每个数据类型与POJO类型一致
     */
    public void get_sql_obj_morestr(){
        List<Object> list=userRepository.find_SQL_obj();
        for (int i = 0; i < list.size(); i++) {
            Object[] obj = (Object[]) list.get(i);
            String username=(String) obj[0];
            String name=(String) obj[1];
            System.out.println(username+"\t"+name);
        }
    }
    /**
     * 分页查询,先排序后分页
     * select user_name,name from cyd_sys_user,t_user order by user_name desc limit ?, ?
     */
    public void get_sql_obj_morestr_page(){
        Sort sort=new Sort(Direction.DESC,"user_name");
        Pageable page=new PageRequest(2,10,sort);//第二页,每页10条
        Page<Object> p=userRepository.find_SQL_obj(page);
        List<Object> list=p.getContent();
        for (int i = 0; i < list.size(); i++) {
            Object[] obj = (Object[]) list.get(i);
            String username=(String) obj[0];
            String name=(String) obj[1];
            System.out.println(username+"\t"+name);
        }
    }
    /**
     * 多条件查询,分页,排序
     */
    public void get_sql_obj_morestr_(){
        Page<UserBean> p=userRepository.findAll(new Specification<UserBean>() {

            public Predicate toPredicate(Root<UserBean> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate stuNameLike = cb.like(root.<String> get("userName"), "%user_%");
                Order oderby =cb.desc(root.<String> get("userName"));
                if(null != stuNameLike) query.where(stuNameLike);
                query.orderBy(oderby);
                return stuNameLike;
            }
        },new PageRequest(0, 20));
        List<UserBean> list=p.getContent();
        for (int i = 0; i < list.size(); i++) {
            UserBean obj = list.get(i);
            System.out.println(obj.toString());
        }
    }

    /**
     * 通用单个实体查询
     * @param T
     * @return
     */
    public <T> Specification base_Specification(Class T){
        return new Specification<T>(){
            public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate predicate=cb.conjunction();
                List<Expression<Boolean>> expression=predicate.getExpressions();
                expression.add(cb.like(root.<String> get(""), ""));
                return predicate;
            }};
    }

}

参考链接

Spring Data JPA 简单查询--接口方法https://www.cnblogs.com/rulian/p/6557471.html

Spring data jpa中Query和@Query分别返回map结果集https://www.cnblogs.com/wucongyun/p/6730582.html

纯干货,Spring-data-jpa详解,全方位介绍。 http://www.cnblogs.com/dreamroute/p/5173896.html

转载 spring-data-jpa 介绍 复杂查询,包括多表关联,分页,排序等 http://blog.csdn.net/mendeliangyang/article/details/52366799

原文地址:https://www.cnblogs.com/litblank/p/8267333.html

时间: 2024-10-13 23:52:33

springdata-jpa 八种查询方法的相关文章

WordPress慢的八种解决方法(用排查法解决)

WordPress的打开速度慢会影响到用户体验和关键词的稳定排名,WordPress为什么加载慢呢?其实很简单的,就是WordPress水土不服,用WordPress的大家都知道,WordPress是外国人开发的,在国内用肯定会卡的,今天笔者给大家整理了几个解决各种WordPress慢的慢的问题,希望能够帮助到大家! 方法一:删除不必要的插件 什么叫不必要的插件呢?就是能用代码解决的就用代码不用插件,不是非常需要的功能类的插件,美化网站的各种插件,常见的久这两种. 方法二:关闭主题的谷歌字体 这

几种查询方法(lambda Linq Enumerable静态类方式)

1.需要一个数据源类: using System; using System.Collections.Generic; namespace Linq { public class Student { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } public class Data { public static List<Student> studentLi

数据结构八种排序方法作业示例(无讲解)

#include <cstdio> #include <cstring> #include <ctime> #include <algorithm> #include <cstdlib> #include <cmath> #include <fstream> using namespace std; class insertSort{ public: insertSort(int * a,int size){ this-&

推广新网站的八种有效方法

据AdWeek调查显示,81%的顾客在决定购买一件商品或服务之前会先访问该公司的网站. 一部分的顾客会直接通过社交媒体平台.电子邮件营销活动或他们读到的博文中的链接来访问一个特定的网站--但大约60%的顾客会通过搜索引擎输入关键词进入一个网站. 如果您的潜在客户通过在线搜索或其它的营销渠道找不到您的网站,那么您的网站就不能产生很多流量,而您的企业就无法得到发展了. 那创建新网站最主要的是什么呢?如果您尚未制定好一个网站推广计划,那么花时间创建一个新网站根本就没有多大意义,bluehost建议使用

只查看ett.txt文件(共100行)内第25到35行的内容的八种解决方法

试题:只查看ett.txt文件(共100行)内第25到35行的内容 解答: 方法一:head -35 /data/ett.txt |tail -11 方法二:sed -n '25,35p' /data/ett.txt 方法三:grep -C5 30 /data/ett.txt 方法四:grep -A10 25 /data/ett.txt 方法五:grep -B10 35 /data/ett.txt 方法六:awk 'NR=25,NR==35' /data/ett.txt 方法七:awk 'NR>

selenium—八种定位方法

find_element_by_id() find_element_by_name() find_element_by_class_name() find_element_by_tag_name() find_element_by_link_text() find_element_by_partial_link_text() find_element_by_xpath() find_element_by_css_selector()

(六)八种定位方法

1.安装火狐插件 ①旧版本firefox 火狐浏览器右上角-->附件-->获取更多附件-->搜索-->Firebug 安装 Firebug 扩展:https://addons.mozilla.org/zh-CN/firefox/addon/firebug/ ,添加到firebug之后,重启火狐,之后会在右上角看大一个七星瓢虫类似的说明安装成功. 但是由于FIrebug已经不再更新了,新版本的Firefox浏览器好像不支持firebug的js调试 下个旧版本Firefox39.0.2

Dynamic CRM 2015学习笔记(3)oData 查询方法及GUID值比较

本文将比较二种查询字符串在同一个oData查询方法中的不同,另外,还将介绍如何比较不同方法返回的GUID的值. 用同一个oData查询方法,如果传入查询的字符串不一样,返回结果的格式竟然完全不一样. 1. oData查询方法: //OData查询 ODataRetrieve: function (oDataString) { var retrieveReq = new XMLHttpRequest(); retrieveReq.open("GET", encodeURI(Xrm.Pag

SpringData JPA之方法名查询的关键字表

在springdata jpa 中我们经常会对数据库进行各种各样的CURD操作.比如,查询操作.当然对于一些简单业务的CURD操作由jpa自带的JpaRepository接口就行已经可以满足了,但是往往在开发中需求的复杂程度是不能够预测的,所以构建一些能自适应相对复杂业务的CURD操作是很有必要的.这时候我们也可以选择采用@Query注解进行原生SQL语句的编写.获取采用@Query注解编写SpEL语句进行着对数据库的CURD操作.而现在我要说的是采用jpa 提供的方法名派生查询的方式.比如在P