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);
    }
}
相关推荐
Livingbody38 分钟前
ubuntu25.04完美安装typora免费版教程
后端
阿华的代码王国1 小时前
【Android】RecyclerView实现新闻列表布局(1)适配器使用相关问题
android·xml·java·前端·后端
码农BookSea1 小时前
自研 DSL 神器:万字拆解 ANTLR 4 核心原理与高级应用
java·后端
lovebugs1 小时前
Java并发编程:深入理解volatile与指令重排
java·后端·面试
海奥华21 小时前
操作系统到 Go 运行时的内存管理演进与实现
开发语言·后端·golang
codervibe1 小时前
Spring Boot 服务层泛型抽象与代码复用实战
后端
_風箏1 小时前
Shell【脚本 04】传递参数的4种方式(位置参数、特殊变量、环境变量和命名参数)实例说明
后端
斜月1 小时前
Python Asyncio以及Futures并发编程实践
后端·python
CRUD被占用了1 小时前
coze-studio学习笔记(一)
后端