SpringBoot整合MongoDB
程序员文章站
2022-03-20 10:41:38
...
一:目录结构
二:配置文件
2.1 pom.xml配置文件
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2.2 appliction.properties配置文件内容
当然我这种连接MongoDB数据库是没有用户密码的情况下,如果你的DB库有账号密码可修改为:
spring.data.mongodb.uri=mongodb://userName:aaa@qq.com:27017/weck
三:实体类
package com.zz.entity;
import java.io.Serializable;
import org.springframework.data.mongodb.core.mapping.Document;
@Document (collection = "weckLog")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String _id;
/** 名称 */
private String name;
/** 年龄 */
private Integer age;
/** 职业 */
private String occupation;
public User () {
// TODO Auto-generated constructor stub
}
public User (String name, Integer age, String occupation) {
super ();
this.name = name;
this.age = age;
this.occupation = occupation;
}
public String get_id () {
return _id;
}
public void set_id (String _id) {
this._id = _id;
}
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
public Integer getAge () {
return age;
}
public void setAge (Integer age) {
this.age = age;
}
public String getOccupation () {
return occupation;
}
public void setOccupation (String occupation) {
this.occupation = occupation;
}
@Override
public String toString () {
return String.format ("Customer[name='%s', age='%s']", name, age);
}
}
@Document 可理解为关联对应的表
四:启动类
package com.zz;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication (scanBasePackages = "com.zz")
public class App {
public static void main (String[] args) {
SpringApplication.run (App.class, args);
}
}
五:封装泛型接口(基本上常用的接口都封装好了。直接拿去用就可以了)
5.1 Service
package com.zz.service;
import java.util.List;
import com.zz.exception.NullIdException;
/**
* MongoDB 非关系型数据库泛型接口定义
*
* @Title MongodbService
* @Description
* @Company
* @author Zheng.Zeng
* @date 2018年5月31日 下午2:21:41
*/
public interface MongodbService <T> {
void update (T entity) throws NullIdException;
/**
* 添加或者修改(ALL)</br>
* 如果有_ID值则为修改,如果没有_ID值则为添加</br>
*
* @return null
*/
void saveOrUpdate (T entity);
/**
* 添加</br>
*
* @return null
*/
void save (T entity);
/**
* 查询全部</br>
*
* @param entity 查询实体 </br>
* 因为MongoDB具体要查询的Document是设置在实体类的,所以需要传具体的实体类</br>
* @return java.util.List </br>
*/
List <T> findAll (T entity);
/**
* 根据_ID查询</br>
*
* @param id 编码</br>
* @param entity 查询实体 </br>
* 因为MongoDB具体要查询的document是设置在实体类的,所以需要传具体的实体类
* @return entity </br>
*/
T findById (String id, T entity);
/**
* 根据_ID删除
*
* @param id 编码</br>
* @param entity 查询实体</br>
* 因为MongoDB具体要查询的document是设置在实体类的,所以需要传具体的实体类 </br>
* @return null </br>
*/
void deleteById (String id, T entity);
/**
* 根据_ID修改某一个键值队</br>
*
* @param id 编码</br>
* @param key 键</br>
* @param value 值</br>
* @param entity 操作实体</br>
* 因为MongoDB具体要查询的document是设置在实体类的,所以需要传具体的实体类 </br>
* @return null
*/
void updateById (String id, String key, Object value, T entity);
}
5.2 ServiceImpl
package com.zz.service.impl;
import java.util.List;
import org.bson.types.ObjectId;
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 org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import com.zz.exception.NullIdException;
import com.zz.service.MongodbService;
import com.zz.util.ReflectUtil;
/**
* MongoDB 业务逻辑层
*
* @Title MongodbServiceImpl
* @Description
* @Company
* @author Zheng.Zeng
* @param <T>
* @date 2018年5月31日 下午2:24:40
*/
@Service
public class MongodbServiceImpl <T> implements MongodbService <T> {
@Autowired
MongoOperations mongoTemplate;
/**
* 修改</br>
*
* @return null
*/
public void update (T entity) throws NullIdException {
boolean falg = ReflectUtil.reflectObject (entity);
if (!falg) {
throw new NullIdException ("_ID is null");
}
mongoTemplate.save (entity);
}
/**
* 添加或者修改(ALL)</br>
* 如果有_ID值则为修改,如果没有_ID值则为添加</br>
*
* @return null
*/
public void saveOrUpdate (T entity) {
mongoTemplate.save (entity);
}
/** 添加 */
public void save (final T entity) {
mongoTemplate.insert (entity);
}
/**
* 查询全部
*
* @param entity 查询实体 </br>
* 因为MongoDB具体要查询的document是设置在实体类的,所以需要传具体的实体类
* @return
*/
@SuppressWarnings ("unchecked")
public List <T> findAll (T entity) {
return (List <T>) mongoTemplate.findAll (entity.getClass ());
}
/**
* 根据_ID查询
*
* @param entity 查询实体 </br>
* 因为MongoDB具体要查询的document是设置在实体类的,所以需要传具体的实体类
* @return
*/
@SuppressWarnings ("unchecked")
public T findById (String id, T entity) {
return (T) mongoTemplate.findOne (new Query (Criteria.where ("_id").is (new ObjectId (id))),
entity.getClass ());
}
/**
* 根据_ID删除
*
* @param id 编码</br>
* @param entity 查询实体</br>
* 因为MongoDB具体要查询的document是设置在实体类的,所以需要传具体的实体类 </br>
* @return null </br>
*/
public void deleteById (String id, T entity) {
mongoTemplate.remove (new Query (Criteria.where ("_id").is (new ObjectId (id))), entity.getClass ());
}
/**
* 根据_ID修改某一个键值队</br>
*
* @param id 编码</br>
* @param key 键</br>
* @param value 值</br>
* @param entity 操作实体</br>
* 因为MongoDB具体要查询的document是设置在实体类的,所以需要传具体的实体类 </br>
* @return null
*/
public void updateById (String id, String key, Object value, T entity) {
mongoTemplate.updateFirst (new Query (Criteria.where ("_id").is (new ObjectId (id))),
Update.update (key, value), entity.getClass ());
}
}
六:控制器
package com.zz.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zz.entity.User;
import com.zz.exception.NullIdException;
import com.zz.service.MongodbService;
@RestController
public class UserController {
@Autowired
MongodbService <User> MongodbService;
@RequestMapping (value = "save")
public String save () {
User user = new User ("cs", 1, "牛皮");
MongodbService.save (user);
return "保存成功!";
}
@RequestMapping (value = "findAll")
public List <User> findAll () {
return MongodbService.findAll (new User ());
}
@RequestMapping (value = "findById")
public User findById () {
String id = "5b0f60d3c9b20d735cbfe087";
return MongodbService.findById (id, new User ());
}
@RequestMapping (value = "deleteById")
public List <User> delete () {
String id = "5b0f99d2d3372328a097c5d6";
MongodbService.deleteById (id, new User ());
return findAll ();
}
@RequestMapping (value = "update")
public List <User> update () {
String id = "5b0f60d3c9b20d735cbfe087";
MongodbService.updateById (id, "name", "小曾正", new User ());
return findAll ();
}
@RequestMapping (value = "saveOrUpdate")
public List <User> saveOrUpdate () {
User user = new User ();
user.setOccupation ("WEB全栈工程师");
user.set_id ("5b0fba07d3372324f0c61baf");
MongodbService.saveOrUpdate (user);
return findAll ();
}
@RequestMapping (value = "updates")
public List <User> up () {
User user = new User ("刘德华", 55, "演员");
user.set_id ("5b0fba07d3372324f0c61baf");
try {
MongodbService.update (user);
} catch (NullIdException e) {
e.printStackTrace ();
}
return findAll ();
}
}
七:工具类
package com.zz.util;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectUtil {
/**
* 反射对象
*
* @return 是否有数据为null
* @throws Exception
*/
public static boolean reflectObject (Object obj) {
boolean len = false;
Field[] field = obj.getClass ().getDeclaredFields ();
try {
for (int j = 0; j < field.length; j++) {
String name = field[j].getName ();
name = name.substring (0, 1).toUpperCase () + name.substring (1);
if (name.equals ("_id")) {
Method m = obj.getClass ().getMethod ("get" + name);
String value = (String) m.invoke (obj);
if (value != null && !"".equals (value)) {
System.out.println ("属性值为:" + value);
len = true;
}
}
}
} catch (Exception e) {
e.printStackTrace ();
}
return len;
}
}
八:异常类
package com.zz.exception;
/**
* 空_ID异常
*
* @Title NullIdException
* @Description
* @Company
* @author Zheng.Zeng
* @date 2018年5月31日 下午5:34:21
*/
public class NullIdException extends Exception {
private static final long serialVersionUID = 1L;
public NullIdException (String message) {
super (message);
}
public NullIdException (String message, Throwable cause) {
super (message, cause);
}
}
九:演示结果
整合MongoDB就这么简单。