猿问

自定义 SQL 查询和 Spring Data JPA

如何在 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 吗?你如何实现你的自定义方法?


富国沪深
浏览 155回答 2
2回答

暮色呼如

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);OR2)@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:&nbsp;@Entity@Table(name = "table_name1", schema="db_name")@NamedQuery(name = "ENTITY.fetchParam",&nbsp; &nbsp; &nbsp; &nbsp; 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:@Repositorypublic interface TestRepository extends JpaRepository<Employee,Long>, TestRepositoryCustom {&nbsp; &nbsp; List<String> fetchParam(@Param("param") String param);}
随时随地看视频慕课网APP

相关分类

Java
我要回答