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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值