首页 > 数据库 >JPA exists子查询 SQLServer 源码粘贴复制

JPA exists子查询 SQLServer 源码粘贴复制

时间:2022-10-26 11:24:31浏览次数:44  
标签:return String exists JPA id 源码 org import public

引导类代码:

package com.aniu.niu;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class NiuApplication {

    public static void main(String[] args) {
        SpringApplication.run(NiuApplication.class, args);
    }

}

 

Entity相关代码:

package com.aniu.niu.entity;

import javax.annotation.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Student {
    @Id
    private String id;

    public String getId() {
        return id;
    }

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

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

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

    public String getCourseId() {
        return courseId;
    }

    public void setCourseId(String courseId) {
        this.courseId = courseId;
    }

    @Column(name = "name")
    private String studentName;
    private String sex;
    private int age;
    //演示 数据库字段和类属性不一致的情况, courseId关联 Course表
    @Column(name = "course")
    private String courseId;
}
package com.aniu.niu.entity;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Course {
    @Id
    public String id;

    public String getId() {
        return id;
    }

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

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

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

    public String code;
    private String name;
}

repository代码:

package com.aniu.niu.repository;

import com.aniu.niu.entity.Student;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface StudentRepository extends JpaRepository<Student, String> {
    List<Student> findAll(Specification<Student> specification);
}

Controller代码:

package com.aniu.niu.controller;

import com.aniu.niu.entity.Course;
import com.aniu.niu.entity.Student;
import com.aniu.niu.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping(value = "stu")
public class StudentController {
    @Autowired
    private StudentRepository repository;

    /**
     * 注意参数添加 @RequestBody
     * @param student
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/create")
    public String createStudent(@RequestBody Student student){
        if(StringUtils.isEmpty(student.getId())){
            student.setId(UUID.randomUUID().toString());
        }
        repository.save(student);
        return "创建成功";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/upd")
    public String modifyStudent(@RequestBody Student student){
        repository.save(student);
        return "修改成功";
    }


    @RequestMapping(method = RequestMethod.GET, value = "/findbyid")
    public Student findStudent(String id){
        Student student = repository.findById(id).get();
        return student;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/findall")
    public List<Student> findAllStudent(){
        List<Student> students = repository.findAll();
        return students;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/gthan")
    public List<Student> findStudentByExists(int age){
        Specification<Student> studentSpecification =  (root, criteriaQuery, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            Subquery<String> subQuery = criteriaQuery.subquery(String.class);
            Root subRoot = subQuery.from(Course.class);
            //注意courseId条件和数据库字段不一致,要以实体上的名称为准
            subQuery
                    .select(cb.literal("1"))
                    .where(
                            cb.equal(subRoot.get("id"), root.get("courseId"))
                    );

            predicates.add(cb.exists(subQuery));
            predicates.add(cb.greaterThan(root.get("age").as(Integer.class), age));
            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        List<Student> students = repository.findAll(studentSpecification);
        return students;
    }
}

application.properties配置文件内容:

# 应用名称
spring.application.name=niu
# 应用服务 WEB 访问端口
server.port=8080

spring.datasource.url=jdbc:sqlserver://localhost;databaseName=jpatest
spring.datasource.username=sa
spring.datasource.password=123123a?
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.ddl-auto=none

 

最后Postman调用:

http://localhost:8080/stu/gthan?age=20

sql效果:

Hibernate: select student0_.id as id1_1_, student0_.age as age2_1_, student0_.course as course3_1_, student0_.sex as sex4_1_, student0_.name as name5_1_ from student student0_ where (exists (select '1' from course course1_ where course1_.id=student0_.course)) and cast(student0_.age as int)>20

标签:return,String,exists,JPA,id,源码,org,import,public
From: https://www.cnblogs.com/niuge/p/16827605.html

相关文章

  • 基于springboot+vue商品推荐管理系统的设计与实现(源码调试+讲解+文档)
    ......
  • JAVA---Set集合底层源码分析
    1.Set集合介绍      常用方法,添加,删除和遍历 Set接口对象不能使用索引获取,他是无序的,没有索引。set集合无序,所以没有修改和查看某个元素,因为某个位置上是......
  • 从源码中解析fabric区块数据结构(一)
    从源码中解析fabric区块数据结构(一)前言最近打算基于fabric-sdk-go实现hyperledgerfabric浏览器,其中最重要的一步就是解析fabric的上链区块。虽说fabric是Golang实现的,但......
  • rest_framework权限源码分析
    位置APIView---->dispatch方法---->initial方法--->self.check_permissions(request)(APIView的对象方法)分析defcheck_permissions(self,request):"""Chec......
  • rest_framework认证源码分析
    认证源码分析位置:APIVIew----》dispatch方法---》self.initial(request,*args,**kwargs)---->有认证,权限,频率三个版块分析:只读认证源码:self.perform_authenticatio......
  • 源码分析之ViewSetMixin类
    在rest_framework中继承了ModelViewSet类的视图函数,其内部ModelViewSet类继承了一个ViewSetMixin类ViewSetMixin类重新写了as_view()方法,使得我们可以更加方便快速的写出......
  • 模糊测试工具AFL源码浅析
    前言AFL是一款著名的模糊测试的工具,最近在阅读AFL源码,记录一下,方便以后查阅。环境项目:AFL编译项目:将编译的优化选项关闭,即改写成-O0afl-gcc.c使用gdb加载afl-......
  • 45.限流Throttling及源码解析
    什么是限流?限流类似于权限机制,它也决定是否接受当前请求,用于控制客户端在某段时间内允许向API发出请求的次数,也就是频率假设有客户端(比如爬虫程序)短时间发起大量请......
  • 爱上源码,重学Spring AOP深入
    AOP(AspectOrientProgramming):直译过来就是面向切面编程。AOP是一种编程思想用途:Transactions(事务调用方法前开启事务,调用方法后提交关闭事务)、日志、性能(监控方法......
  • 直播带货源码,如何用Android Studio实现登录跳转
    直播带货源码,如何用AndroidStudio实现登录跳转一、基本要求实现一个简单的用户登录界面,功能如下: 1、默认不存储用户信息,默认隐藏密码。 2、能通过勾选框记住密码......