本文主要是介绍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 {@Autowiredprivate StudentJPQLSQLMapper mapper;@Testvoid 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);}@Testvoid selectBySQL() {List<Student> allBySQL = mapper.findAllBySQL();System.out.println(allBySQL);}@Testvoid findByVoidName() {List<Student> a = mapper.findDistinctByNameIsEndingWithOrderByGradeDesc("a");System.out.println(a);}
}
这篇关于springboot 整合 springdataJPA 自定义操作 JPQL和SQL的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!