自定义SQL查询和Spring Data JPA

时间:2018-10-05 11:29:24

标签: java sql spring spring-data-jpa spring-data

如何在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 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

TestRepository中,您可以使用SELECT NEW使用DTO并传递DTO对象:

@Query("SELECT NEW com.app.domain.EntityDTO(table.id, table.col2, table.col3)
FROM Table table")
public List<EntityDTO> findAll();

在该示例中,您的DTO必须具有带有这3个参数的构造函数。

如果要选择属性,可以简单地使用:

@Query("SELECT table.id)
FROM Table table")
public List<Long> findAllIds();