SpringData JPA使用JPQL的方式查詢和使用SQL語句查詢


使用Spring Data JPA提供的查詢方法已經可以解決大部分的應用場景,但是對於某些業務來說,我們還需要靈活的構造查詢條件,

這時就可以使用@Query注解,結合JPQL的語句方式完成查詢

持久層接口:

/**
 * 客戶持久層接口
 * JpaRepository<實體類類型,主鍵類型>:用來完成基本CRUD操作
 * JpaSpecificationExecutor<實體類類型>:用於復雜查詢(分頁等查詢操作)
 */
public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {

    /**
     * 根據客戶名稱查詢客戶
     * 使用jpql的形式查詢
     *  jpql:from Customer where custName = ?
     *  配置jpql語句,使用的@Query注解
     */
    @Query("from Customer where custName = ?")
    Customer findJpql(String custName);

    /**
     * 根據客戶名稱和客戶id查詢客戶
     * jpql: from Customer where custName = ? and custId = ?
     *  對於多個占位符參數
     *      賦值的時候,默認的情況下,占位符的位置需要和方法參數中的位置保持一致
     *      也可以指定占位符參數的位置
     *          ?索引的方式,指定此占位的取值來源
     */
    @Query("from Customer where custName = ?2 and custId = ?1")
    Customer findCustNameAndId(Long id, String name);

    /**
     * 使用jpql完成更新操作
     * 根據id更新,客戶的名稱
     * sql  :update cst_customer set cust_name = ? where cust_id = ?
     * pql : update Customer set custName = ? where custId = ?
     *  @Query : 代表的是進行查詢
     *  @Modifying : 聲明此方法是用來進行更新操作
     */
    @Query(value = "update Customer set custName = ? where custId = ?")
    @Modifying
    @Transactional // springdata jpa使用jpql執行插入,更新,刪除需要手動提交事務
    @Rollback(false) // 默認在執行之后,回滾事務,這里設置不回滾
    void updateCustomer(String custName, long custId);


    /**
     * 使用sql的形式查詢:查詢全部的客戶
     *      sql:select * from cst_customer
     *      nativeQuery : true 使用本地sql的方式查詢 false(默認) jpql查詢
     */
    @Query(value = "select * from cst_customer", nativeQuery = true)
    List<Customer> findSql();
}

測試:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class JpqlTest {
    @Autowired
    private CustomerDao customerDao;

    @Test
    public void testFindJpql() {
        Customer c = customerDao.findJpql("小明");
        System.out.println(c);
    }

    @Test
    public void testFindCustNameAndId() {
        Customer c = customerDao.findCustNameAndId(6L, "小倩");
        System.out.println(c);
    }

    @Test
    public void testUpdateCustomer() {
        customerDao.updateCustomer("lily", 4L);
    }

    @Test
    public void testFindSql() {
        List<Customer> customers = customerDao.findSql();
        for (Customer customer : customers) {
            System.out.println(customer);
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM