springboot 整合 springdataJPA 自定义操作 JPQL和SQL

1.接口StudentJPQLSQLMapper.java

java 复制代码
package com.jmj.springDataApp.mapper;

import com.jmj.springDataApp.pojo.Student;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;

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

public interface StudentJPQLSQLMapper extends PagingAndSortingRepository<Student,Long> {
    //增删改擦

    //查询 JPQL语句
    @Query("FROM Student WHERE name=:name")
    Student findStudentByName(@Param("name") String name);

    //修改 JPQL语句
    @Query("update Student s set s.name=:name  where s.id=:id")
    @Modifying//通知springdatajpa 是增删改的操作
    int updateStudent(@Param("name") String name,@Param("id") Long id);


    @Query("update Student s set  s.name=:#{#stu.name} where s.id=:#{#stu.id}")
    @Modifying//通知springdatajpa 是增删改的操作
    int updateByStudent(@Param("stu")Student student);

    @Query(value = "select * from `tb_student`",nativeQuery = true)
    List<Student> findAllBySQL();

    List<Student> findDistinctByNameIsEndingWithOrderByGradeDesc(String name);
}

测试

java 复制代码
package com.jmj.springDataApp.mapper;

import com.jmj.springDataApp.pojo.Student;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class StudentJPQLSQLMapperTest {

    @Autowired
    private StudentJPQLSQLMapper mapper;

    @Test
    void selectByName() {
        Student student = mapper.findStudentByName("81d17");
        System.out.println(student);
    }

    @Test
    @Transactional(rollbackOn = Exception.class)
    void update() {
        Student student = new Student(5l, "张三", 3);
        int i = mapper.updateStudent(student.getName(),student.getId());
        System.out.println(i);
    }

    @Test
    void selectBySQL() {
        List<Student> allBySQL = mapper.findAllBySQL();

        System.out.println(allBySQL);
    }

    @Test
    void findByVoidName() {
        List<Student> a = mapper.findDistinctByNameIsEndingWithOrderByGradeDesc("a");
        System.out.println(a);
    }
}
相关推荐
风象南14 分钟前
SpringBoot中4种登录验证码实现方案
java·spring boot·后端
hkfkn32 分钟前
Sql刷题日志(day6)
数据库·sql
云之兕1 小时前
Spring Boot 中多线程的基础使用
java·前端·spring boot
他҈姓҈林҈1 小时前
Spring Boot 升级指南(2.x → 3.x)
spring boot
闪电麦坤957 小时前
SQL:子查询(subqueries)
数据库·sql
why1519 小时前
腾讯(QQ浏览器)后端开发
开发语言·后端·golang
浪裡遊9 小时前
跨域问题(Cross-Origin Problem)
linux·前端·vue.js·后端·https·sprint
声声codeGrandMaster9 小时前
django之优化分页功能(利用参数共存及封装来实现)
数据库·后端·python·django
呼Lu噜10 小时前
WPF-遵循MVVM框架创建图表的显示【保姆级】
前端·后端·wpf
bing_15810 小时前
为什么选择 Spring Boot? 它是如何简化单个微服务的创建、配置和部署的?
spring boot·后端·微服务