SpringBoot SpringDataJPA 动态查询、多条件查询

Spring-data - JPA用的还是比较多的,之前在公司也一直在用,因为方便。下面我们来整理一下如何配置。

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>springdatajpademo</groupId>
    <artifactId>springdatajpademo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <!-- base setting -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.build.locales>zh_CN</project.build.locales>
        <project.build.jdk>1.7</project.build.jdk>
        <java.version>1.7</java.version>
        <!-- lib versions -->
        <org.springframework.version>4.1.9.RELEASE</org.springframework.version>
        <org.springframework.data.version>1.9.2.RELEASE</org.springframework.data.version>
        <!-- <org.hibernate.version>4.3.7.Final</org.hibernate.version> -->
        <org.hibernate.version>5.1.1.Final</org.hibernate.version>
        <mysql.connector.version>5.1.32</mysql.connector.version>
        <hessian.version>4.0.7</hessian.version>
        <fastjson.version>1.2.7</fastjson.version>
        <org.eclipse.jetty.version>9.1.0.v20131115</org.eclipse.jetty.version>
        <org.apache.cxf.version>2.7.7</org.apache.cxf.version>
        <project.name>data-manager-server</project.name>
        <main.class>com.goldmsg.res.Bootstrap</main.class>
    </properties>

    <dependencies>
        <!-- spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <!-- spring data jpa -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>${org.springframework.data.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${org.hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${org.hibernate.version}</version>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.connector.version}</version>
        </dependency>
        <!-- druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.15</version>
        </dependency>
    </dependencies>
    
</project>

userInfo.java

import javax.persistence.*;

/**
 * Created with IntelliJ IDEA.
 * User: lu
 * Date: 17-3-30
 * Time: 下午5:57
 * To change this template use File | Settings | File Templates.
 */
@Entity
@Table(name="obj_user")
@NamedQuery(name="UserInfo.findAll", query="SELECT o FROM UserInfo o")
public class UserInfo {
    private int userId;
    private String name;
    private int age;
    private long high;

    @javax.persistence.Id
    @Column(name="user_id")
    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public long getHigh() {
        return high;
    }

    public void setHigh(long high) {
        this.high = high;
    }
}

UserInfoDao.java

public interface UserInfoDao extends PagingAndSortingRepository<UserInfo, String>, JpaSpecificationExecutor<UserInfo> {

}

UserInfoSpecDao.java

import com.springdatajpademo.pojo.UserInfo;
import com.springdatajpademo.pojo.UserInfo_;
import org.springframework.data.jpa.domain.Specification;

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

/**
 * Created with IntelliJ IDEA.
 * User: lu
 * Date: 17-3-30
 * Time: 下午8:05
 * To change this template use File | Settings | File Templates.
 */
public class UserInfoDaoSpec {
    public static Specification<UserInfo> getSpec(final String name,final int age,final int high) {
        return new Specification<UserInfo>() {

            @Override
            public Predicate toPredicate(Root<UserInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate p1 = null;
                if(name!=null) {
                    Predicate p2 = cb.equal(root.get(UserInfo_.name),name);
                    if(p1 != null) {
                        p1 = cb.and(p1,p2);
                    } else {
                        p1 = p2;
                    }
                }

                if(age!=0) {
                    Predicate p2 = cb.equal(root.get(UserInfo_.age), age);
                    if(p1 != null) {
                        p1 = cb.and(p1,p2);
                    } else {
                        p1 = p2;
                    }
                }

                if(high!=0) {
                    Predicate p2 = cb.equal(root.get(UserInfo_.high), high);
                    if(p1 != null) {
                        p1 = cb.and(p1,p2);
                    } else {
                        p1 = p2;
                    }
                }

                return p1;
            }
        };
    }
}

UserInfoExtendDao.java

import com.springdatajpademo.pojo.UserInfo;
import com.springdatajpademo.pojo.UserInfo_;
import com.springdatajpademo.pojo.UserStat;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Tuple;
import javax.persistence.criteria.*;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: lu
 * Date: 17-3-31
 * Time: 上午10:32
 * To change this template use File | Settings | File Templates.
 */
@Repository
public class UserInfoExtendDao {

    @PersistenceContext(unitName = "springJpa")
    EntityManager em;

    public List<UserInfo> getUserInfo(String name,int age,int high) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<UserInfo> query = cb.createQuery(UserInfo.class);

        //from
        Root<UserInfo> root = query.from(UserInfo.class);

        //where
        Predicate p1 = null;
        if(name!=null) {
            Predicate p2 = cb.equal(root.get(UserInfo_.name),name);
            if(p1 != null) {
                p1 = cb.and(p1,p2);
            } else {
                p1 = p2;
            }
        }

        if(age!=0) {
            Predicate p2 = cb.equal(root.get(UserInfo_.age), age);
            if(p1 != null) {
                p1 = cb.and(p1,p2);
            } else {
                p1 = p2;
            }
        }

        if(high!=0) {
            Predicate p2 = cb.equal(root.get(UserInfo_.high), high);
            if(p1 != null) {
                p1 = cb.and(p1,p2);
            } else {
                p1 = p2;
            }
        }
        query.where(p1);

        List<UserInfo> userInfos = em.createQuery(query).getResultList();
        return userInfos;
    }



    public UserStat getUserStat(String name) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Tuple> query = cb.createTupleQuery();

        //from
        Root<UserInfo> root = query.from(UserInfo.class);

        //select
        Selection<Long> countUser;
        Selection<Long> sumHigh;

        countUser = cb.count(root.get(UserInfo_.userId));
        sumHigh = cb.sum(root.get(UserInfo_.high));

        CompoundSelection<Tuple> selection = cb.tuple(countUser, sumHigh);

        //where
        Predicate predicate = cb.equal(root.get(UserInfo_.name), name);

        //query
        CriteriaQuery<Tuple> criteriaQuery = query.select(selection).where(predicate);

        Tuple tuple = em.createQuery(criteriaQuery).getSingleResult();
        UserStat userStat = new UserStat();
        userStat.setCountUser(tuple.get(countUser));
        userStat.setSumHigh(tuple.get(sumHigh));

        return userStat;
    }
}

Application.java

import com.springdatajpademo.pojo.UserInfo;
import com.springdatajpademo.pojo.UserStat;
import com.springdatajpademo.repository.UserInfoDao;
import com.springdatajpademo.repository.UserInfoDaoSpec;
import com.springdatajpademo.repository.UserInfoExtendDao;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;


public class Application {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        Application  application = new Application ();
        application .testJpa1(applicationContext);
        application .testJpa2(applicationContext);

    }

    public void testJpa1(ClassPathXmlApplicationContext applicationContext) {
        UserInfoExtendDao userInfoExtendDao = (UserInfoExtendDao)applicationContext.getBean("userInfoExtendDao");

        List<UserInfo> userInfos = userInfoExtendDao.getUserInfo("张三",16,165);
        printUserInfo(userInfos);

        UserStat userStat = userInfoExtendDao.getUserStat("张三");
        System.out.println(userStat.getCountUser());
        System.out.println(userStat.getSumHigh());
    }

    public void testJpa2(ClassPathXmlApplicationContext applicationContext) {
        UserInfoDao userInfoDao = (UserInfoDao)applicationContext.getBean("userInfoDao");
        {
            //三个条件:"张三",16,165
            System.out.println("\n三个条件:张三,16,165");
            List<UserInfo> userInfos = userInfoDao.findAll(UserInfoDaoSpec.getSpec("张三",16,165));
            printUserInfo(userInfos);
        }

        {
            //两个条件:"张三",16,这里假设赋值0为未赋值
            System.out.println("\n两个条件:张三,16");
            List<UserInfo> userInfos = userInfoDao.findAll(UserInfoDaoSpec.getSpec("张三",16,0));
            printUserInfo(userInfos);
        }

        {
            //两个条件:"张三",16,这里假设赋值0为未赋值
            System.out.println("\n一个条件:张三");
            List<UserInfo> userInfos = userInfoDao.findAll(UserInfoDaoSpec.getSpec("张三",0,0));
            printUserInfo(userInfos);
        }

    }

    private void printUserInfo(List<UserInfo> userInfos) {
        if(userInfos!=null) {
            for(UserInfo userInfo : userInfos) {
                System.out.println("userId:"+userInfo.getUserId()+" name:"+userInfo.getName());
            }
        }
    }


}

以上配置来自网络,有问题可以在下面评论,技术问题可以私聊我。

QQ技术交流群:213365178

posted @ 2019-05-07 14:25  坐看云起时_雨宣  阅读(1993)  评论(0编辑  收藏  举报