QueryDSL给Spring JPA添上了翅膀,那我再给它加个鸡腿,拿掉VO

目录

第一步,配置pom.xml文件

第二步:在主启动文件中加入以下代码 ,让Spring来管理JPAQueryFactory

第三步:参考上一篇文章写的案例进行

第四步:在控制器层调用

第五步:运行结果输出   http://127.0.0.1:9011/search


 QueryDSL给Spring JPA添上了翅膀,那我再给它加个鸡腿,拿掉VO

 吐槽:JAVA SQL查询和PHP SQL查询比,简直一个是木头人。两者灵活性不能比较,当然PHP是脚本语言自然灵活。现在我们要解决的是怎么把一个木头人,变的灵活。 编程也要学会偷懒,有一种“懒” 也是开发效率的提升!

下面我们结合“QueryDSL给Spring JPA添上了翅膀” ,再加个鸡腿,拿掉VO

第一步,配置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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.1.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.weijuhe</groupId>
	<artifactId>wjh</artifactId>
	<version>0.0.1</version>
	<packaging>jar</packaging>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.28</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.16.20</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<!--QueryDSL支持-->
		<dependency>
			<groupId>com.querydsl</groupId>
			<artifactId>querydsl-apt</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>com.querydsl</groupId>
			<artifactId>querydsl-jpa</artifactId>
		</dependency>
		<!--QueryDSL支持-->

		<!-- 单元测试-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
		</dependency>
		<!-- 单元测试-->
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<!--Query DSL-->
			<plugin>
				<groupId>com.mysema.maven</groupId>
				<artifactId>apt-maven-plugin</artifactId>
				<version>1.1.3</version>
				<executions>
					<execution>
						<goals>
							<goal>process</goal>
						</goals>
						<configuration>
							<outputDirectory>target/generated-sources/java</outputDirectory>
							<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<!--Query DSL-->
		</plugins>
	</build>

</project>

 第二步:在启动文件中加入以下代码 ,让Spring来管理JPAQueryFactory

//让Spring管理JPAQueryFactory
	@Bean
	public JPAQueryFactory jpaQueryFactory(EntityManager entityManager) {
		return new JPAQueryFactory(entityManager);
	}

第三步:参考上一篇文章写的案例进行

修改 UserService 文件 ,主要看:dynamicQuery

https://blog.csdn.net/qq_15371293/article/details/107025611   

package com.example.demo.service;

import com.example.demo.entity.QUser;
import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import com.example.demo.util.DynamicBeanUtil;
import com.example.demo.util.JpaUtil;
import com.google.common.collect.Lists;
import com.querydsl.core.QueryResults;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class UserService extends BaseService<UserRepository, User,Integer> {


    @Autowired
    JPAQueryFactory queryFactory;


    //分页查询
    public Page<Object> dynamicQuery(Predicate predicate, Pageable pageable) {
        QUser u = QUser.user;    //需要 maven compile 自动生成 前缀 Q + 实体类
        QueryResults<Tuple> queryResults = queryFactory.select(u.id, u.username,u.status).from(u)
                .where(predicate).offset(pageable.getOffset()).limit(pageable.getPageSize())
                .orderBy(u.id.desc()).fetchResults();

        if (queryResults == null || queryResults.isEmpty() ){
            System.out.println("查询空!!");
            return  null;
        }
        List<Tuple> tuples = queryResults.getResults();
        List<Object> data = Lists.newArrayList();

        //根据字段生成动态vo类
        Map<String, Expression> field = new HashMap<String, Expression>() {{
            put(u.id.getMetadata().getName(), u.id);
            put(u.username.getMetadata().getName(), u.username);
            put(u.status.getMetadata().getName(), u.status);
        }};
        for (Tuple tu : tuples) {
            DynamicBeanUtil vo = new DynamicBeanUtil(DynamicBeanUtil.referObjectType(field));
            for (String fieldName : field.keySet()) {
                vo.setValue(fieldName, tu.get(field.get(fieldName)));
            }
            data.add(vo.getObject());
        }
        long total = queryResults.getTotal();
        return new PageImpl<>(data, pageable, total);
    }



    @Autowired
    UserRepository userRepository;

    public User saveUser(User data) {
        User save = null;
        Optional<User> selectData = userRepository.findById(data.getId());
        if (selectData.isPresent()) {
            String[] Field = {"nick", "theme"};  //更新 Field指定允许字段
            JpaUtil.copyNotNullPropertiesAllow(data, selectData.get(), Field);
            save = userRepository.save(selectData.get());
        } else {
            userRepository.save(data); //新增
        }
        return save;
    }

}

第四步:在控制器层调用

package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.entity.QUser;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
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.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

@RestController
@Controller
@RequestMapping("/")
public class IndexController {

    @Autowired
    UserService userService;

    @GetMapping("index")
    public void index() {
        User data = new User();
        data.setId(1);
        data.setNick("只更新,允许的字段");
        userService.saveUser(data);
    }


    @GetMapping(value = "search", name = "查询 分页,总数")
    public void search(@RequestParam(value = "id", required = false) Long id,
                       @RequestParam(value = "page", required = false, defaultValue = "2") int page,
                       @RequestParam(value = "limit", required = false, defaultValue = "5") int limit
    ) {
        QUser user = QUser.user;    //需要 maven compile 自动生成 前缀 Q + 实体类
        //初始化组装条件(类似where 1=1)
        Predicate predicate = user.isNotNull().or(user.isNull());
        predicate =  ExpressionUtils.and(predicate,user.mobile.ne("1111"));
        predicate =  ExpressionUtils.and(predicate,user.id.ne(1));
        
        Pageable pageable = PageRequest.of(page, limit);
        Page<Object> data = userService.dynamicQuery(predicate, pageable);

        Map<String, Object> ret = new HashMap();
        ret.put("数据", data.getContent());
        ret.put("总共", data.getTotalElements()+"条");
        ret.put("第", data.getNumber()+"页");
        ret.put("每页显示", data.getNumberOfElements()+"条");
        ret.put("总共", data.getTotalPages()+"页");

        System.out.println("输出查询数据,拿掉VO ※ \n" + JSON.toJSON(ret));
        
    }
}

第五步:运行结果输出   http://127.0.0.1:9011/search

©️2020 CSDN 皮肤主题: 深蓝海洋 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值