@Query("select user from User u where u.userName=?1 and u.age=?2 ") User getUserByUserNameAndAge2(String userName,Integer age);
当需要更新和删除操作,加一个@Modifying注解:
@Modifying @Query("UPDATE User u set u.userName =: userName where u.age =:age") voidupdate(@Param(value = "userName") String userName, @Param(value = "age")Integer age);
4.Spring Data MongoDB
Spring Data MongoDB与Spring Data JPA同级,都是Spring Data的子项目,其核心是MongoRepository+MongoTemplate。它的核心接口MongoRepository<T, ID>也是继承自PagingAndSortingRepository<T, ID>接口:
@Override public Instance queryByIp(String ip){ Query query = new Query(); query.addCriteria(Criteria.where("ip").is(ip)); Instance instance = mongoTemplate.findOne(query, Instance.class); if (instance == null) { thrownew ObjectNotFoundException("服务实例"); } return instance; }
@Override public List<Instance> findAllByMetadataId(String metadataId){ Query query = new Query(); query.addCriteria(Criteria.where("metadataId").is(metadataId)); return mongoTemplate.find(query, Instance.class); }
@Override public List<Instance> findAllByImageId(String imageId){ Query query = new Query(); query.addCriteria(Criteria.where("imageId").is(imageId)); return mongoTemplate.find(query, Instance.class); }
}
5.MyBatis
Mybatis是一款优秀的持久层框架,他支持自定义SQL、存储过程以及高级映射。Mybatis免除了几乎所有的JDBC代码以及设置参数和获取结果集的工作。Mybatis可以通过简单的XML或注解来配置和映射原始类型、接口和Java POJO(Plain Old Java Objects,普通老式Java对象)为数据库中的记录。