Jpa實現數據庫的CRUD 需求 使用SpringDataJpa實現數據庫的CRUD 開發步驟 1 創建MAVEN 工程 2 添加依賴 mysql c3p0 hibernate springDataJpA spring相關jar包 3 創建配置文件 4 創建實體類 5 創建Dao 創建接口 即可 要求接口繼承 JpaRspository接口 6 編寫測試程序 1 初始花啊spring 容器 2 從容器中獲得Dao代理對象 3 使用Dao 實現增刪改查 添加/修改 數據 save 刪除數據 delete 查詢 :findOne. 查詢全部 findAll() findAll(Pageable pageaable) 返回Page對象 這里面包含:totalElements 總記錄數 totalPages 總頁數 content 結果列表
## 1 springDataJpa 其它的相關查詢方式 1 查詢全部帶排序‘ 2 count 統計 3 exixtx 判斷記錄是否存在 ## 2 在springDataJpa框架使用Jpql 查詢 使用方法 a: 在dao 接口中定義一個方法 使用方法的參數設置jpql的參數 並且使用方法的返回值接受查詢的結果 b: 在方法上添加一個注解Qquery c 在注解中編寫jpql d 測試 ## 3 使用原生的Sql語句 使用方法 1 dao中 定義一個方法 2 在方法中添加@Query注解 3 在注解中 添加 原生的sql 語句 添加一個屬性 nativeQuery=true 4 測試 ## 4 方法命名規則查詢 通過一定的規則 定義一個方法 框架本省就可以根據方法名生成一個SQL語句進行查詢 規則 1 應該使用findBy開頭 2 查詢某個字段 findBy后跟實體類的屬性的名稱 3 如果有多個條件 就在方法后加And+實體類的屬性名 4 方法的參數 對應查詢的定義 5 返回值根據返回的數據類型定義 如果需要分頁查詢 在方法中添加一個參數Pageable 即可 ## 5 使用Specification方式進行查詢 最強大的查詢方式 除了原生的SQL 語句以外 最復雜的查詢方式 使用方式 1 要在dao 繼承JpaSeciFicationExection 接口 2 使用JpaSeciFicationExection 接口 中提供的方法進行查詢 每個方法都需要使用Specification對象作為參數
CRUD 框架整合 (數據源)(工程類對象)(事物)(dao 掃描器) Entity Dao 定義接口就行 繼承JpaRepository<Customer,Long> 1 crud 使用dao 實現CRUD(重點) 添加 save 修改 save 刪除 delete 查詢 findOne getOne findAll 可以分頁 排序 2 使用jpql 查詢 查詢 @Query 更新 刪除 3 原生 sql 使用@Query注解 添加屬性nativeQuery=true 4 方法名命名規則 查詢(重點) findBy 5 使用SpeciFication 方式查詢
dao層
public interface CustomerDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> { @Query("from Customer") List<Customer> getAllCustomer(); @Query("from Customer") List<Customer> getAllCustomerByPape(Pageable pageable); // 條件查詢‘ @Query("from Customer where cust_id=?") Customer getCustomerById(long id); // 模糊查詢 @Query("from Customer where custName like?2 and custAddress like ?1") List<Customer> getCustList(String address,String name); // 更新 @Query("update Customer set custSource=? where custId=?") @Modifying // @Transactional void updateSource(String source,long id); // 原生語句調價查詢操作 @Query(value = "SELECT * FROM cst_customer where cust_name LIKE ?",nativeQuery = true) List<Customer> getCustomerListByNative(String name); //方法命名規則查詢 Customer findByCustId(long id); List<Customer> findByCustNameLikeAndCustAddressLike(String name,String address); // 分頁 Page<Customer> findByCustAddressLike(String address,Pageable pageable); }
測試層
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class JpaCRUD1 { @Autowired private CustomerDao customerDao; @Test public void addCustomer(){ // ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); // CustomerDao customerDao = ac.getBean(CustomerDao.class); Customer cc = new Customer(); cc.setCustName("謝大腳"); cc.setCustAddress("北京朝陽區"); cc.setCustLevel("黑金VIP"); customerDao.save(cc); } // 刪除 @Test public void deleteCustomer(){ customerDao.delete(2l); } // 更新數據 @Test public void updateCustomer(){ Customer customer = customerDao.findOne(1l); customer.setCustName("張一山"); customer.setCustLevel("鉑金vip"); customerDao.save(customer); } @Test public void findById(){ Customer one = customerDao.findOne(1l); System.out.println(one); } @Test @Transactional// 加上事物注解 在方法執行結束之前 連接不會斷 public void testGetOne(){ Customer one = customerDao.getOne(1l); System.out.println("-----------------------"); System.out.println(one); } @Test public void testFindAll(){ List<Customer> customerDaoAll = customerDao.findAll(); for(Customer customer:customerDaoAll){ System.out.println(customer); } } @Test public void testFindAllWithPage() { PageRequest pageRequest = new PageRequest(0, 2); Page<Customer> page = customerDao.findAll(pageRequest); long totalElements = page.getTotalElements(); System.out.println("總記錄數"+totalElements); int totalPages = page.getTotalPages(); System.out.println("總頁碼"+totalPages); List<Customer> content = page.getContent(); for(Customer customer:content){ System.out.println(customer); } } // 查詢所有帶排序 8月19日 @Test public void testFindAllWithSort(){ // 創建一個sort 對象 // 參數1 排序方式 // 參數2 排序的字段 應該是實體類的屬性名 Sort sort = new Sort(Sort.Direction.DESC,"custId"); List<Customer> list = customerDao.findAll(sort); for(Customer customer:list){ System.out.println(customer); } } @Test public void testCount(){ long count = customerDao.count(); System.out.println(count); } @Test public void testExists(){ boolean exists = customerDao.exists(2l); System.out.println(exists); }
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class JPQLCrud { @Autowired private CustomerDao customerDao; @Test public void testgetAllCustomer(){ List<Customer> list = customerDao.getAllCustomer(); for(Customer customer:list){ System.out.println(customer); } } @Test public void testGetAllCustomerByPage(){ List<Customer> allCustomerByPape = customerDao.getAllCustomerByPape(new PageRequest(0, 3)); for(Customer customer:allCustomerByPape){ System.out.println(customer); } } @Test public void testGetCustomerById(){ Customer customerById = customerDao.getCustomerById(1l); System.out.println(customerById); } @Test public void testGetCustList(){ List<Customer> custList = customerDao.getCustList("%北京%", "%大%"); for(Customer customer:custList){ System.out.println(customer); } } @Test @Transactional @Commit public void testUpdatSource(){ customerDao.updateSource("互聯網111",1l); } @Test public void testCustomerListByNative(){ List<Customer> list = customerDao.getCustomerListByNative("%腳%"); for(Customer customer :list){ System.out.println(customer); } }
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class SpringDataJpaVoid { @Autowired private CustomerDao customerDao; @Test public void testFindByCustId(){ Customer customer = customerDao.findByCustId(1l); System.out.println(customer); } @Test public void testFindByCustNameLikeAndCustAddressLike(){ List<Customer> list = customerDao.findByCustNameLikeAndCustAddressLike("%腳%", "%北京%"); for(Customer customer:list){ System.out.println(customer); } } @Test public void testFindByCustomerAddressByPage(){ Page<Customer> pa = customerDao.findByCustAddressLike("%北京%", new PageRequest(0, 3)); System.out.println(pa.getTotalElements()); System.out.println(pa.getTotalPages()); List<Customer> list = pa.getContent(); for(Customer customer:list){ System.out.println(customer); } // 測試 使用Specification方式進行查詢 } @Test public void testFindByIdSpeciFication(){ Customer customer =customerDao.findOne(new Specification<Customer>() { @Override public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { // 參數1 字段名稱 // 參數2 字段的值 Predicate predicate = criteriaBuilder.equal(root.get("custId"), 1l); return predicate; } }); System.out.println(customer); } // 根據地址模糊查詢 @Test public void testFindByNmaeAdress(){ customerDao.findAll(new Specification<Customer>() { @Override public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { // 創建 根據模糊查詢的條件 Predicate predicate1 = criteriaBuilder.like(root.get("custName"), "%腳%"); Predicate like1 = criteriaBuilder.like(root.get("custAddress"), "%北京%"); // 組合兩個條件 Predicate predicate = criteriaBuilder.and(predicate1, like1); return predicate; } }).forEach(c->System.out.println(c));//forEach(System.out::println); } @Test public void testFindByNmaeAdressWithPage(){ Page<Customer> page = customerDao.findAll(new Specification<Customer>() { @Override public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { // 創建 根據模糊查詢的條件 Predicate predicate1 = criteriaBuilder.like(root.get("custName"), "%腳%"); Predicate like1 = criteriaBuilder.like(root.get("custAddress"), "%北京%"); // 組合兩個條件 Predicate predicate = criteriaBuilder.and(predicate1, like1); return predicate; } },new PageRequest(0,3)); System.out.println(page.getTotalElements()); System.out.println(page.getTotalPages()); List<Customer> content = page.getContent(); for (Customer customer:content){ System.out.println(customer); } } }