1、客户端工具 2、MongoDB常用操作 3、springboot集成MongoDB(mongoTemplate) 4、springboot集成MongoDB(MongoRepository) 5、医院需求介绍 6、部署医院模拟系统 7、开发平台接口-上传医院接口 |
1、MongoDB适用场景 2、客户端工具 (1)安装 (2)使用 |
1、INSERT > db.User.save({name:'zhangsan',age:21,sex:true}) > db.User.find() 2、QUERY (1)where # select * from User where name = 'zhangsan' > db.User.find({name:"zhangsan"}) (2)FIELDS # select name, age from User where age = 20 > db.User.find({age:21}, {'name':1, 'age':1}) (3)sort # select * from User order by age > db.User.find().sort({age:1}) (4)SUCE # select * from User skip 2 limit 3 > db.User.find().skip(0).limit(2) (5)IN # select * from User where age in (21, 26, 32) > db.User.find({age:{$in:[21,44,55]}}) (6)COUNT # select count(*) from User where age >20 > db.User.find({age:{$gt:20}}).count() (7)OR # select * from User where age = 20 or age = 30 > db.User.find({$or:[{age:21}, {age:55}]}) 3、UPDATE # update User set age = 100, sex = 0 where name = 'lucy' > db.User.update({name:"zhangsan"}, {$set:{age:100, sex:0}}) 4、Remove //移除对应id的行 > db.User.remove(id) //移除所有 > db.User.remove({}) 5、aggregate聚合 (1)插入测试数据 见课件 (2)实现聚合查询 # select by_user, count(*) from article group by by_user > db.article.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}]) |
1、集成方案 spring-data-mongodb提供了MongoTemplate与MongoRepository两种方式访问mongodb,MongoRepository操作简单,MongoTemplate操作灵活,我们在项目中可以灵活适用这两种方式操作mongodb,MongoRepository的缺点是不够灵活,MongoTemplate正好可以弥补不足。 2、准备工作 (1)在service_hosp引入依赖 <dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-mongodbartifactId>
dependency>
dependencies> (2)添加mongo配置 spring.data.mongodb.uri=mongodb://192.168.140.138:27017/test 3、使用MongoTemplate实现curd (1)创建目录创建实体 添加com.atguigu.yygh.hosp.testmongo.User类 @Data
@Document("User")
public class User {
@Id
private String id;
private String name;
private Integer age;
private String email;
private String createDate;
} (2)创建测试类 @RestController
@RequestMapping("/mongo1")
public class TestMongo1 {
@Autowired
private MongoTemplate mongoTemplate;
//添加
@GetMapping("create")
public void createUser() {
User user = new User();
user.setName("zhang3");
user.setAge(33);
user.setEmail("[email protected]");
User user1 = mongoTemplate.insert(user);
System.out.println("user1 = " + user1);
}
//查询所有
@GetMapping("findAll")
public void findUser() {
List<User> users = mongoTemplate.findAll(User.class);
users.forEach(System.out::println);
}
//根据id查询
@GetMapping("findId")
public void getById() {
User user = mongoTemplate.findById("64b4a856a2225f220ec3fa0f", User.class);
System.out.println("user = " + user);
}
//条件查询
@GetMapping("findUser")
public void findUserList() {
Query query = new Query(
Criteria.where("name").is("zhang3")
.and("age").is(33)
);
List<User> users = mongoTemplate.find(query, User.class);
users.forEach(System.out::println);
}
//条件模糊查询
@GetMapping("findUserLike")
public void findUserLike() {
String name = "ang";
String regex = String.format("%s%s%s", "^.*", name, ".*$");
Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
Query query = new Query(
Criteria.where("name").regex(pattern)
);
List<User> users = mongoTemplate.find(query, User.class);
users.forEach(System.out::println);
}
//条件模糊分页查询
@GetMapping("findUserPage")
public void findUserPage() {
//0定义分页参数
int pageNo = 1;
int pageSize = 10;
//1设置筛选条件
String name = "ang";
String regex = String.format("%s%s%s", "^.*", name, ".*$");
Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
Query query = new Query(
Criteria.where("name").regex(pattern)
);
//2查询总记录数total
long total = mongoTemplate.count(query, User.class);
//3设置分页条件
query.skip((pageNo-1)*pageSize).limit(pageSize);
List<User> users = mongoTemplate.find(query, User.class);
System.out.println("total = " + total);
users.forEach(System.out::println);
}
//修改
@GetMapping("update")
public void updateUser() {
User user = mongoTemplate.findById("5ffbfa2ac290f356edf9b5aa", User.class);
user.setName("test_1");
user.setAge(25);
user.setEmail("[email protected]");
Query query = new Query(Criteria.where("_id").is(user.getId()));
Update update = new Update();
update.set("name", user.getName());
update.set("age", user.getAge());
update.set("email", user.getEmail());
UpdateResult result = mongoTemplate.upsert(query, update, User.class);
long count = result.getModifiedCount();
System.out.println(count);
}
//删除操作
@GetMapping("delete")
public void delete() {
Query query =
new Query(Criteria.where("_id").is("5ffbfa2ac290f356edf9b5aa"));
DeleteResult result = mongoTemplate.remove(query, User.class);
long count = result.getDeletedCount();
System.out.println(count);
}
} |
1、准备工作 @Repository
public interface UserRepository extends MongoRepository<User,String> {
} 2、实现测试案例 @RestController
@RequestMapping("/mongo2")
public class TestMongo2 {
@Autowired
private UserRepository userRepository;
//添加
@GetMapping("create")
public void createUser() {
User user = new User();
user.setAge(20);
user.setName("张三");
user.setEmail("[email protected]");
User user1 = userRepository.save(user);
System.out.println("user1 = " + user1);
}
//查询所有
@GetMapping("findAll")
public void findUser() {
List<User> users = userRepository.findAll();
users.forEach(System.out::println);
}
//根据id查询
@GetMapping("findId")
public void getById() {
User user = userRepository.findById("64b4a856a2225f220ec3fa0f").get();
System.out.println("user = " + user);
}
//条件查询
@GetMapping("findUser")
public void findUserList() {
User user = new User();
user.setName("张三");
user.setAge(20);
Example<User> example = Example.of(user);
List<User> users = userRepository.findAll(example);
users.forEach(System.out::println);
}
//条件模糊查询
@GetMapping("findUserLike")
public void findUserLike() {
//查询条件
User user = new User();
user.setName("三");
//模板构造器
ExampleMatcher matcher = ExampleMatcher.matching()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
.withIgnoreCase(true);
//查询条件模板
Example<User> example = Example.of(user,matcher);
List<User> users = userRepository.findAll(example);
users.forEach(System.out::println);
}
//条件模糊分页查询
@GetMapping("findUserPage")
public void findUserPage() {
//创建排序对象
Sort sort = Sort.by(Sort.Direction.DESC,"age");
//创建分页对象 第一页从0开始
Pageable pageable = PageRequest.of(0,2,sort);
//查询条件
User user = new User();
user.setName("三");
//模板构造器
ExampleMatcher matcher = ExampleMatcher.matching()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
.withIgnoreCase(true);
//查询条件模板
Example<User> example = Example.of(user,matcher);
Page<User> userPage = userRepository.findAll(example, pageable);
userPage.getContent().forEach(System.out::println);
System.out.println("userPage.getTotalElements() = " + userPage.getTotalElements());
}
//修改
@GetMapping("update")
public void updateUser() {
User user = userRepository.findById("60b8d57ed539ed5b124942de").get();
user.setName("张三_1");
user.setAge(25);
user.setEmail("[email protected]");
User save = userRepository.save(user);
System.out.println(save);
}
//删除操作
@GetMapping("delete")
public void delete() {
userRepository.deleteById("60b8d57ed539ed5b124942de");
}
@GetMapping("testMethod1")
public void testMethod1() {
List<User> users = userRepository.getByNameAndAge("张三",20);
users.forEach(System.out::println);
}
@GetMapping("testMethod2")
public void testMethod2() {
List<User> users = userRepository.getByNameLike("三");
users.forEach(System.out::println);
}
} *创建接口 @Repository
public interface UserRepository extends MongoRepository<User,String> {
List<User> getByName(String name);
List<User> getByNameLike(String name);
List<User> getByNameAndAge(String name, int age);
} |
1、分析需求 (1)实现与医院对接接口(医院、科室、排班) (2)调用接口需要进行验签 |
1、确认资料 2、创建医院模拟系统 (1)创建工程hospital-manage (2)替换pom (3)复制源码 (4)删除测试目录代码 (5)添加静态资源 (6)创建数据库 (7)修改配置信息 3、启动工程 |
1、解读api文档 2、准备工作 (1)添加封装返回结果 (2)添加工具类 3、搭建mongo访问框架 (1)确认依赖 (2)确认配置 (3)确认实体 (4)创建接口
@Repository
public interface HospitalRepository extends MongoRepository<Hospital,String> {
} (5)搭建service public interface HospitalService {
} @Service
public class HospitalServiceImpl implements HospitalService {
@Autowired
private HospitalRepository hospitalRepository;
} (6)创建controller @Api(tags = "医院管理API接口")
@RestController
@RequestMapping("/api/hosp")
public class ApiController {
@Autowired
private HospitalService hospitalService;
} 4、实现上传医院接口 (1)分析接口 *参数:请求对象 *返回值:Result.ok() (2)实现controller @ApiOperation(value = "上传医院")
@PostMapping("saveHospital")
public Result saveHospital(HttpServletRequest request) {
//1从request获取参数,类型转化
Map<String, String[]> parameterMap = request.getParameterMap();
Map<String, Object> paramMap = HttpRequestHelper.switchMap(parameterMap);
//2 TODO 进行验签
//3 保存医院信息
hospitalService.save(paramMap);
//4 返回结果
return Result.ok();
} (3)实现service //保存医院信息
@Override
public void save(Map<String, Object> paramMap) {
//1使用工具实现paramMap=》Hospital
String paramJsonStr = JSONObject.toJSONString(paramMap);
Hospital hospital = JSONObject.parseObject(paramJsonStr, Hospital.class);
//2根据hoscode查询mongo,获取医院信息
Hospital targetHospital = hospitalRepository.getByHoscode(hospital.getHoscode());
if(targetHospital!=null){
//3医院信息不为空,更新数据
hospital.setId(targetHospital.getId());
hospital.setCreateTime(targetHospital.getCreateTime());
hospital.setUpdateTime(new Date());
hospital.setStatus(0);
hospitalRepository.save(hospital);
}else{
//4医院信息为空,新增数据
hospital.setCreateTime(new Date());
hospital.setUpdateTime(new Date());
hospital.setStatus(0);
hospitalRepository.save(hospital);
}
} *创建接口方法 @Repository
public interface HospitalRepository extends MongoRepository<Hospital,String> {
//根据hoscode查询mongo,获取医院信息
Hospital getByHoscode(String hoscode);
} 5、启动服务进行测试 (1)测试数据 (2)联调测试 6、签名校验 (1)验证数据 (2)改造医院系统加密方式 (3)hosp实现获取签名秘钥接口 /**
* 获取签名key
* @param hoscode
* @return
*/
String getSignKey(String hoscode); //获取签名key
@Override
public String getSignKey(String hoscode) {
LambdaQueryWrapper<HospitalSet> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(HospitalSet::getHoscode,hoscode); HospitalSet hospitalSet = baseMapper.selectOne(wrapper);
if(hospitalSet!=null){
return hospitalSet.getSignKey();
}else{
throw new YyghException(20001,"获取签名失败");
}
} (4)改造上传接口 @ApiOperation(value = "上传医院")
@PostMapping("saveHospital")
public Result saveHospital(HttpServletRequest request) {
//1从request获取参数,类型转化
Map<String, String[]> parameterMap = request.getParameterMap();
Map<String, Object> paramMap = HttpRequestHelper.switchMap(parameterMap);
//2 进行验签
//2.1获取相关参数
String hoscode = (String) paramMap.get("hoscode");
String sign = (String) paramMap.get("sign");
//2.2获取签名秘钥
String signKey = hospitalSetService.getSignKey(hoscode);
//2.3 MD5加密签名秘钥
String signKeyMD5 = MD5.encrypt(signKey);
System.out.println("sign = " + sign);
System.out.println("signKeyMD5 = " + signKeyMD5);
//2.4 进行验签
if(!sign.equals(signKeyMD5)){
throw new YyghException(20001,"签名校验不通过");
}
//传输过程中“+”转换为了“ ”,因此我们要转换回来
String logoData = (String)paramMap.get("logoData");
logoData = logoData.replaceAll(" ","+");
paramMap.put("logoData",logoData);
//3 保存医院信息
hospitalService.save(paramMap);
//4 返回结果
return Result.ok();
} (5)测试 |