1 在pom文件中添加mongodb依赖
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
...
2 创建mongodb实体类
package com.sileaf.pojo;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Data
@Document("User")
public class User {
@Id
private String id;
private String name;
private int age;
private String favorite;
private String tel;
}
3 创建mongodb资源库
3.1 mongo资源库接口
package com.sileaf.repository;
import com.sileaf.pojo.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import java.util.List;
/**
* 继承MongoRepository,可以按一定规则自定义方法而无需实现
* 对于复杂的查询可使用@Query注解,fields属性可以配置字段是否显示
* 也可自定义接口,进行多继承
*/
public interface UserRepository extends MongoRepository<User, String>, UserRepositoryCustom {
public List<User> findByName(String name);
public List<User> findByNameAndAge(String name, int age);
public List<User> findByAgeGreaterThan(int age);
public List<User> findByAgeLessThan(int age);
public List<User> findByNameOrderByName(String name);
@Query(value = "{id : ?0}", fields = "{favorite : 0}")
public User findOneById(String id);
}
3.2 mongo资源自定义库接口
package com.sileaf.repository;
import com.sileaf.pojo.User;
public interface UserRepositoryCustom {
public User findUserById(String id);
}
3.3 mongo资源自定义库接口实现
package com.sileaf.repository;
import com.sileaf.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
public class UserRepositoryImpl implements UserRepositoryCustom {
@Autowired
private MongoTemplate mongoTemplate;
@Override
public User findUserById(String id) {
return mongoTemplate.findById(id, User.class);
}
}
4 mongo配置
4.1 配置类形式配置mongo
4.1.1 创建Mongo库配置类
package com.sileaf.config;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
@EnableMongoRepositories(basePackages = {"com.sileaf.repository"}, mongoTemplateRef = "mongoTemplate")
public class MongoConfig {}
4.1.2 创建mongo上下文配置类
package com.sileaf.config;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
@Configuration
public class MongoContext {
@Value("${spring.data.mongodb.uri}")
private String uri;
@Bean("mongoClient")
public MongoClient mongoClient() {
return MongoClients.create(uri);
}
@Bean("mongoDatabaseFactory")
public MongoDatabaseFactory mongoDatabaseFactory() {
return new SimpleMongoClientDatabaseFactory(uri);
}
@Bean("mongoTemplate")
public MongoTemplate mongoTemplate(@Autowired MongoDatabaseFactory mongoDatabaseFactory) {
return new MongoTemplate(mongoDatabaseFactory);
}
}
4.2 xml文件形式配置mongo
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/mongo https://www.springframework.org/schema/data/mongo/spring-mongo.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:application.yml"/>
<mongo:mongo-client id="mongoClient" host="${mongodb.host}" port="${mongodb.port}" credential="${mongodb.username}:${mongodb.password}@${mongodb.database}"/>
<mongo:db-factory id="mongoDatabaseFactory" dbname="${mongodb.database}" mongo-client-ref="mongoClient"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDatabaseFactory"/>
</bean>
<mongo:repositories base-package="com.sileaf.repository" mongo-template-ref="mongoTemplate"/>
</beans>
5 创建测试用controller
package com.sileaf.controller;
import com.sileaf.pojo.User;
import com.sileaf.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping(value = "/find/{id}")
public User findUserById(@PathVariable("id") String id) {
return userRepository.findById(id).orElse(null);
}
@PostMapping("/save")
public User saveUser(User user) {
return userRepository.save(user);
}
}