为了账号安全,请及时绑定邮箱和手机立即绑定

自定义 SQL 查询和 Spring Data JPA

自定义 SQL 查询和 Spring Data JPA

富国沪深 2021-10-28 14:24:02
如何在 Spring Data JPA 中编写自定义查询? 还有比下面更方便的方法吗?我以前是这样做的:public class TestCustomRepositoryImpl implements TestCustomRepository {    @PersistenceContext    private EntityManager entityManager;    @Override    public Double getValue(Long param) {        // Simple SQL query for example.        String queryString = "SELECT column_name1 FROM table_name1 "              + "WHERE column_name2 = " + param;        Query query = entityManager.createNativeQuery(queryString);        List resultList = query.getResultList();        if (!resultList.isEmpty()) {            Number value = (Number) resultList.get(0);            if (value != null) {                return value.doubleValue();            }        }        return 0.0;    }}然后我将自定义界面添加到我的 JPA 存储库中:public interface TestRepository extends JpaRepository<TestEntity, Long>, TestCustomRepository {}有没有更方便的方法?例如,我可以将 Spring Data 用于 CRUD 并使用 MyBatis 实现 TestCustomRepository 吗?你如何实现你的自定义方法?
查看完整描述

2 回答

?
暮色呼如

TA贡献1853条经验 获得超9个赞

You can write the native query in the repository like this:


1)

@Query("SELECT t.column_name1 FROM table_name1 t WHERE t.column_name2 =:param")

List<String> getValue(@Param("param") String param);


OR


2)@Query("SELECT t.column_name1 FROM table_name1 t WHERE t.column_name2 = 'param'", nativeQuery=true)

List<String> getValue();


Or you can use NamedQuery and add the query in the model only.

for eg: 

@Entity

@Table(name = "table_name1", schema="db_name")

@NamedQuery(name = "ENTITY.fetchParam",

        query = "SELECT t.column_name1 FROM table_name1 t WHERE t.column_name2 =:param "

)

public class Employee {

}


And have same method in the repository like:

@Repository

public interface TestRepository extends JpaRepository<Employee,Long>, TestRepositoryCustom {


    List<String> fetchParam(@Param("param") String param);

}


查看完整回答
反对 回复 2021-10-28
  • 2 回答
  • 0 关注
  • 154 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信