Spring+Mongo混合自定義CRUD功能
配置請參考上一篇移至Spring註解配置Mongo,Mongo的DAO介面方法定義分為3種:自定義(查詢)操作、指定(查詢)操作、混合自定義功能操作
1、自定義方法的方法名及是根據CRUD操作及查詢引數、查詢資料庫欄位名設定的
例:(1)根據顧客名引數(對應欄位customer)查詢order集合方法名-----findByCustomer(String name)/getByCustomer(String name)/readByCustomer(String name)
(2)根據顧客名模糊查詢:findByCustomerLike(String n)
(3)、根據型別欄位type和顧客名模糊查詢:findByCustomerLikeAndTypeLike(String name,String type)
查詢方法名以find、read、get為字首均可,條件查詢時需加上By,引數順序與方法名欄位名順序一一對應,如3的引數name對應欄位customer,type對應Type,這是Spring-Data的一個特性,Repository方法由一個動詞、一個可選的主題、關鍵詞By及一個斷言所組成
其它CRUD操作同理,如根據客戶名刪除:deleteByCustomer(String name);
2、指定操作
指定操作方法名不受限制,但需在@Query補充完整操作
例:(1)根據型別查詢:
@Query(value="{ 'type',?0}")
List<Order> customSelect(String type); //?0對應第一個引數位
那要是模糊查詢呢?Mongo的資料都為json格式,所以模糊查詢時的引數肯定不是%param%的格式,而是正則表示式形式,即/???/形式,JDK1.8中有一個Pattern類可以為我們建立正則表示式,建立時呼叫該類的compile靜態方法進行建立,所以此時我們傳參就不再是字串,而是正則表示式,如:
(2)根據型別模糊查詢:
@Query(value="{ 'type',?0}")
List<Order> customSelect(Pattern pattern);
(3)根據型別刪除
@Query(value = "{'type':?0}",delete = true)
@Query中還含有exists根據條件判斷資料是否存在,count進行資料統計
3、混合自定義功能
自定義的方法混合到自動生成的Repository中時,還需要涉及到建立一箇中間介面來宣告自定義的方法。
在上一篇中,OrderRepository只繼承了MongoRepository介面,若想新增自定義方法,則需再繼承一個自定義的介面,同時也要再編寫一個實現類實現該自定義介面。如我想定義額外的Order操作方法,於是新建了一個OrderDAO介面,並使OrderRepository介面繼承OrderDAO介面,再新建一個實現類OrderRepositoryImpl實現OrderDAO介面,實現類的命名須已pojo類名+Repository+Impl命名,字尾impl可修改,只需在配置類中的@EnableMongoRespositories中新增repositoryImplementationPostfix='xxx'即可設定字尾。
程式碼附錄(POJO類與上篇相同):
OrderDAO.java:
package per.nosql.dao; import per.nosql.pojo.Order; import java.util.List; /** * Created by Wilson on 2017/5/5. */ public interface OrderDAO { List<Order> findByParam(); }OrderRespositoryImpl.java:
package per.nosql.dao.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import per.nosql.dao.OrderDAO; import per.nosql.pojo.Order; import java.util.List; /** * Created by Wilson on 2017/5/5. */ public class OrderRepositoryImpl implements OrderDAO { @Autowired private MongoOperations operations; //MongoTemplate的父介面 @Override public List<Order> findByParam() { Criteria criteria = Criteria.where("type").is("1").and("customer").regex("tom"); return operations.find(Query.query(criteria), Order.class); } }OrderRepository.java:
package per.nosql.dao; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import per.nosql.pojo.Order; import java.util.List; import java.util.regex.Pattern; /** * Created by Wilson on 2017/5/5. */ public interface OrderRepository extends MongoRepository<Order, String>, OrderDAO { /*自定義查詢方法*/ @Query("{'type' : '1'},{'customer': ?1}") List<Order> findByTypeAndName(String type, String name); List<Order> readByType(String type); List<Order> getByCustomerLikeAndType(String name,String type); int countByCustomerLike(String name); List<Order> findByTypeAndCustomer(String type, String customer); int deleteByCustomer(String customer); @Query(value = "{'type':?0}") List<Order> customSelect(Pattern pattern); @Query(value = "{'type':?0}",delete = true) int customDelete(String type); }測試類MongoTest.java:
package per.nosql.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import per.nosql.config.MongoConfig; import per.nosql.dao.OrderRepository; import per.nosql.pojo.Order; import java.util.List; import java.util.regex.Pattern; /** * Created by Wilson on 2017/5/5. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = MongoConfig.class) public class MongoTest { @Autowired OrderRepository orderRepository; @Test public void addOrder() { orderRepository.save(new Order(null, "Wilson", "22", null /*Arrays.asList( new Item(null, null, "麵條", 13, 5))*/)); findAllOrders(); } @Test public void findByType() { System.out.println("----------------------------------------findByType-------------------------------------------"); listToString(orderRepository.readByType("2")); } @Test public void findByTypeAndName() { findAllOrders(); System.out.println("------------------------------------findByTypeAndName----------------------------------------------"); listToString(orderRepository.findByTypeAndName("2", "Wilson")); } @Test public void getByCustomerLikeAndType() { findAllOrders(); System.out.println("------------------------------------getByCustomerLikeAndType----------------------------------------------"); listToString(orderRepository.getByCustomerLikeAndType("ls", "2")); } @Test public void countAll() { System.out.println("------------------------------------count----------------------------------------------"); System.out.println("db記錄數:" + orderRepository.count()); } @Test public void countByNameLike() { findAllOrders(); System.out.println("------------------------------------countByNameLike----------------------------------------------"); System.out.println("name like num:" + orderRepository.countByCustomerLike("il")); } @Test public void findAllOrders() { System.out.println("------------------------------------findAll----------------------------------------------"); listToString(orderRepository.findAll()); } @Test public void findByParam() { findAllOrders(); System.out.println("------------------------------------findByParam----------------------------------------------"); listToString(orderRepository.findByParam()); } @Test public void findByTypeAndCustomer() { findAllOrders(); System.out.println("------------------------------------findByTypeAndCustomer----------------------------------------------"); listToString(orderRepository.findByTypeAndCustomer("2", "il")); } @Test public void deleteById() { orderRepository.delete("590c4f39b81fcf661ee40e13"); findAllOrders(); } @Test public void deleteByCustomer() { findAllOrders(); System.out.println("刪除數目:" + orderRepository.deleteByCustomer("Wilson")); findAllOrders(); } @Test public void customSelect() { findAllOrders(); System.out.println("------------------------------------customSelect----------------------------------------------"); listToString(orderRepository.customSelect(Pattern.compile("2"))); } @Test public void customDelete() { findAllOrders(); System.out.println("------------------------------------customDelete----------------------------------------------"); System.out.println("自定義刪除數:" + orderRepository.customDelete("22")); findAllOrders(); } private void listToString(List<Order> orderList) { StringBuffer buffer = new StringBuffer(); orderList.forEach(each -> buffer.append(each).append("\n")); System.out.println(buffer.toString()); } }自定義查詢方法getByCustomerLikeAndType(String name,String type)測試結果:
混合自定義功能方法findByParam()測試結果:
指定操作刪除方法customDelete(String type)測試結果: