一、依赖
<!-- mongodb -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.0</version>
</dependency>
二、application配置
spring:
application:
name: mongodb
data:
mongodb:
host: 192.168.1.1 # ip
port: 27017 # 端口 默认27017
database: book # 数据库名
三、实体类
@Data
@Document(collection="表名")
public class MongodbData {
@Id
private String id;
private List<MongodbChildData> data;
}
@Data
@Document
public class MongodbChildData {
private String id;
private String name;
private int length;
}
四、使用实例
public interface MongodbDao {
List<MongodbData> queryList();
MongodbData query(int id);
void insert(MongodbData model);
void update(MongodbData model);
void delete(MongodbData model);
MongodbData findById(MongodbData model);
}
public class MongodbService implements MongodbDao{
@Resource
private MongoTemplate mongoTemplate;
@Override
public List<MongodbData>getBookList() {
List<MongodbData> all = mongoTemplate.findAll(MongodbData.class);
all.forEach(System.out::print);
return all;
}
@Override
public MongodbData query(int id) {
Query query = new Query();
query.addCriteria(Criteria.where("id").is(id));
MongodbData one = mongoTemplate.findOne(query, MongodbData.class);
System.out.println(one);
return one;
}
public void insert(MongodbData model){
mongoTemplate.save(model);
}
public void update(MongodbData model){
mongoTemplate.save(model);
}
public void deleteById(MongodbData model){
MongodbData data = mongoTemplate.findById(model, MongodbData.class);
if(data != null){
mongoTemplate.remove(data);
}
}
public MongodbData findById(MongodbData model){
return mongoTemplate.findById(model, MongodbData.class);
}
}