Spring Data JPA自定义方式实现数据查询

前言

上一篇博文Spring Data JPA的简单使用 讲到,如果按照JPA的命名规范,Spring Data Jpa会自动为我们实现数据库相关操作。但如果我们想自己实现数据库相关操作该怎么做?

自定义数据库操作

1、使用HQL语句:定义Dao方法,并使用@Query注解写自定义sql,如果是修改类型的SQL,还必须加上@Modifying和@Transactional注解

import com.prince.entity.VipCourse;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

public interface CourseRepository extends JpaRepository<VipCourse, String> {
    /**
     * 自定义实现数据库操作
     * @param cname
     */
    @Modifying
    @Transactional
    @Query("delete from VipCourse where course_name=:courseName")
    void deleteByCname(@Param("courseName") String cname);
}

2、 使用SQL语句

public interface CourseRepository extends JpaRepository<VipCourse, String> {
    /**
     * 使用sql语句实现自定义查询
     * 注意:这里查询出来的字段名后面不能取别名,Jpa会自动映射到实体类的属性名
     *    也就是这样会报错:select course_id courseId from vip_course
     * @return
     */
    @Query(value = "select course_id, course_name, price, description from vip_course", nativeQuery = true)
    List<VipCourse> findAll();
}

3、使用SPEL表达式

public interface CourseRepository extends JpaRepository<VipCourse, String> {
    /**
     * 使用SPEL表达式实现数据库操作
     * @param course
     */
    @Modifying
    @Transactional
    @Query(value = "update vip_course set course_name=:#{#course.courseName}, price=:#{#course.price}, description=:#{#course.description}  " +
            "where course_id=:#{#course.courseId}", nativeQuery = true)
    void updateCourse(@Param("course") VipCourse course);
}

附:JPA命名规范

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/chenshufeng115/article/details/108478238
今日推荐