SpringBoot 整合MongoDB

做了一个短网址服务demo,使用到了MongoDB和SpringBoot。速度快高并发选择MongoDB代替MySQL。随手写的,别在意细节错误,仅提供搭建和基本使用方法思路

环境:SpringBoot、MongoDB、Gradle、lombok

工程图

Gradle:

repositories {
 maven { url 'http://maven.aliyun.com/repository/public/' }
 mavenCentral()
}

dependencies {
 implementation 'org.springframework.boot:spring-boot-starter-web'
 implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
 compileOnly 'org.projectlombok:lombok'
 annotationProcessor 'org.projectlombok:lombok'
 testImplementation('org.springframework.boot:spring-boot-starter-test') {
  exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
 }
}

application.yml

spring:
    data:
        mongodb:
          uri: mongodb://192.168.28.173:27017/kafeurl (Mongdb服务器IP)

Entity:

@Setter
@Getter
public class KfEntity<E> {
	private String id;
	private LocalDate createAt;
	private LocalDate modifyAt;
}

KafeMonGoDao:

@Service
public class KafeMongGoDao<E extends KfEntity<E>> {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 新增数据
     *
     * @param e 数据
     * @return 插入的数据
     */
    public KfEntity<E> save(E e) {
        mongoTemplate.save(e);

        return findById(e.getId());
    }

    public List<UrlEntity> getList() {
        return mongoTemplate.findAll(UrlEntity.class);
    }

    /**
     * 根据对象属性查询信息
     *
     * @return
     */
    @SuppressWarnings({"unchecked"
    })
    public KfEntity<E> findById(String id) {
        Query query = new Query(Criteria.where("id").is(id));

        return mongoTemplate.findOne(query, KfEntity.class);
    }

    /**
     * 更新对象
     */
    @SuppressWarnings("unused")
    public String update(E e) {
        StringBuffer sb = new StringBuffer();
        Query query = new Query(Criteria.where("id").is(e.getId()));

        if (query == null) {
            return "error:null";
        }

        Update update = new Update();

        if (e != null) {
            Field[] declaredFields = e.getClass().getDeclaredFields();

            for (int i = 0; i < declaredFields.length; i++) {
                Field field = declaredFields[i];
                field.setAccessible(true);

                String name = field.getName();
                Object value = null;

                try {
                    value = field.get(e);
                } catch (Exception x) {
                    sb.append("[ERROR]:" + name + ":" + x.toString());
                }

                if (value != null) {
                    update.set(name, value.toString());
                    sb.append("[Success]:" + name + ":" + value.toString());
                }
            }
        }
        mongoTemplate.updateFirst(query,update,e.getClass());
        return sb.toString();
    }

    /**
     * 删除对象
     *
     * @param id
     */
    public void delete(E e) {
        Query query = new Query(Criteria.where("id").is(e.getId()));
        mongoTemplate.remove(query, e.getClass());
    }
}
原文链接:SpringBoot 整合MongoDB