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

猜你喜欢

转载自www.cnblogs.com/roadlandscape/p/12374879.html
今日推荐