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

发布时间:2023年12月20日

1.接口StudentJPQLSQLMapper.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);
}

测试

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);
    }
}

文章来源:https://blog.csdn.net/qq_53374893/article/details/135118325
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。