前几天调研了一下spring-data的使用。此处做一下使用的简单介绍:
在使用关系型数据库的传统Java web开发中,我们通常使用如下层级结构:![在这里输入图片标题 输入图片说明](https://static.oschina.net/uploads/img/201611/24192724_hhqF.png)
![在这里输入图片标题 输入图片说明](https://static.oschina.net/uploads/img/201611/24193406_TSdQ.png)
- 业务逻辑代码和数据库操作代码耦合在一起,较为难以分离
- 加大了单元测试的难度
- 结构层次不清晰
以下是理由:
- 上面1和3造成的原因都是因为函数体变长,业务代码和数据库代码杂糅在一起造成的,出错时,需要对整个函数进行复验,确保函数的编写的正确性。编写UT时也会造成需要覆盖的路径(语句)增多,难度因此增加。
- 结构层次不清晰,在分为Service和Dao层的情况下,逻辑层级更为清晰,业务层主做业务,Dao层主做数据库的CURD。
所以我们可以使用spring-data-mongo来完成dao层的编写。
以下代码都是测试通过的,主要注意几个点:- 代码只需要定义成这样既可,一般的查询都可以使用这些自动生成的代码来进行完成
- 如果需要添加自定义的方法,在这边我使用的是JDK8的default关键字,直接将实现添加在了接口里面,实测可用
- 启动时spring会操作字节码自动生成实现类,所以启动可能较慢,并且一旦有bug调试起来很麻烦(基本无法调试)。
接口定义示例:
public interface UserRepository extends MongoRepository{ //Query/ // Do not recommend using @Query annotation like this @Query("{ 'firstname' : ?0, 'password': ?1 }") public User findByUsernameAndPassword(String username, String password); // find age larger than // there are others: public List findByAgeGreaterThan(Integer age); public List findByAgeLessThan(Integer age); public List findByAgeBetween(Integer from, Integer to); public List findBySexNot(String sex); public List findBySexLike(String sex); public List findBySexNotLike(String sex); public List findByUsernameNull(); public List findByUsernameNotNull(); // find by username public User findByUsername(String username); // find distinct users by username public List findDistinctUserByUsername(String username); public List findUserDistinctByUsername(String username); // find users by username and age public List findByUsernameAndAge(String username, Integer age); // find users by username or age public List findByUsernameOrAge(String username, Integer age); // find users by sex with ignoring cases public List findBySexIgnoreCase(String sex, Pageable pageable); // find users by sex with order firstname ascending public List findBySexOrderByUsernameAsc(String sex); // find users by sex with the order sort specfied public List findBySex(String sex, Sort sort); // find users bys sex with pageable public List findBySex(String sex, Pageable pageable); // find the first ten results by user sex public Slice findTop10BySex(String sex, Sort sort); public Slice findFirst10BySex(String sex, Sort sort); // other query like Stream Query and Async Query could be // found here http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#repositories.query-methods // define the method by ourself default User findByUsernameAndPasswordByOwn(String username, String password) { MongoOperations ops = DbUtil.getDbUtil().getMongoTemplate(); User user = ops.findOne(query(where("username").is(username)) .addCriteria(where("password").is(password)), User.class); return user; } default GroupByResults findUserGroupBySex() { GroupByResults results = DbUtil.getDbUtil().getMongoTemplate() .group("user", GroupBy.key("sex").initialDocument("{ count: 0 }") .reduceFunction("function(doc, prev) { prev.count += 1 }"), User.class); return results; } //Delete/ public void deleteByUsername(String username); public void removeByUsernameAndAge(String username, Integer age); /update // normally, we use sper.update(), if the method can't meet your demand, // you can write the method yourself default void updateMultiByUsername(String username, Integer age) { MongoOperations ops = DbUtil.getDbUtil().getMongoTemplate(); // update all the documents whose username atteribute is username // and the class need to be User ops.updateMulti(query(where("username").is(username)), Update.update("age", age), User.class); } //save/// // just use default save(). forget about the others.}
使用例子:
@RestControllerpublic class UserController { @Autowired UserRepository userRepository; @RequestMapping("/") public String sayHello(String name) { return "Hello, " + name; } @RequestMapping(value="/user", method = RequestMethod.POST) public String add(@RequestParam String companyId, @RequestBody User user) { user = userRepository.save(user); return user.getId(); } @RequestMapping(value = "/user/username", method = RequestMethod.GET) public User getUserByUserName(@RequestParam String companyId, @RequestParam String username, @RequestParam String password) { User user; user = userRepository.findByUsernameAndPassword(username, password); return user; } @RequestMapping(value="/user/group/sex", method = RequestMethod.GET) public GroupByResultsgroupUserBySex() { return userRepository.findUserGroupBySex(); }}