簡體   English   中英

自定義SQL查詢和Spring Data JPA

[英]Custom SQL queries and 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嗎? 您如何實現自定義方法?

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM