一.查詢所有
1.dao層
(1)代碼塊
import cn.pojo.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
/**
* 使用sql語句進行查詢
*/
public interface CustomerDao2 extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {
/**
* 查詢所有
* 註解@Query
* 屬性:
* value:添加sql語句
* nativeQuery:設置是否本地查詢,
* true爲本地查詢,sql語法
* false爲hql查詢,hql語法
*
* @return
*/
@Query(value = "select * from cst_customer",nativeQuery = true)
public List<Object[]> findByAll();//注意:返回值類型是object數組
}
(2)範例
2.測試類
(1)代碼塊
import cn.dao.CustomerDao;
import cn.dao.CustomerDao2;
import cn.pojo.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.List;
/**
* 測試dao層的方法
* sql語句註解方式
*/
@RunWith(SpringJUnit4ClassRunner.class) //聲明spring提供的單元測試
@ContextConfiguration(locations = "classpath:applicationContext.xml")//配置spring容器環境
public class CustomerTest5 {
@Autowired
private CustomerDao2 customerDao;
/**
* 使用sql語句查詢
* 查詢所有用戶
*/
@Test
public void test1(){
List<Object[]> list = customerDao.findByAll();
for (Object[] obj:list){
System.out.println(Arrays.toString(obj));
}
}
(2)範例
二.條件查詢
1.dao層
(1)代碼塊
/**
* 模糊查詢所有
* @param custName
* @return
*/
@Query(value = "select * from cst_customer where cust_name like ?",nativeQuery = true)
public List<Object[]> findLikeAll(String custName);//注意:返回值類型是object數組
(2)範例
2.測試類
(1)代碼塊
/**
* 使用sql語句查詢
* 模糊查詢
*/
@Test
public void test2(){
List<Object[]> list = customerDao.findLikeAll("%李%");
for (Object[] obj:list){
System.out.println(Arrays.toString(obj));
}
}
(2)範例
三.源碼
day02.rar