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

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 {
    //增删改擦

    //查询 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 findAllBySQL();

    List 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 allBySQL = mapper.findAllBySQL();

        System.out.println(allBySQL);
    }

    @Test
    void findByVoidName() {
        List a = mapper.findDistinctByNameIsEndingWithOrderByGradeDesc("a");
        System.out.println(a);
    }
}

你可能感兴趣的:(SpringBoot,spring,boot,sql,后端)