1、引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
2、增加配置
spring.data.mongodb.uri=mongodb://localhost:27017/pra
3、创建数据实体
public class User implements Serializable {
private static final long serialVersionUID = -3258839839160856613L;
private Long id;
private String userName;
private String passWord;
//getter、setter 省略
}
4、将 MongoTemplate 注入到实体类
@Component
public class UserRepositoryImpl implements UserRepository {
@Autowired
private MongoTemplate mongoTemplate;
}
5、写增删改查
@Component
public class UserRepositoryImpl implements UserRepository{
@Autowired
private MongoTemplate mongoTemplate;
@Override
public void saveUser(User user) {
mongoTemplate.save(user);
}
@Override
public User findUserByUserName(String username) {
Query query = new Query(Criteria.where("username").is(username));
User user = mongoTemplate.findOne(query, User.class);
return user;
}
@Override
public long updateUser(User user) {
Query query = new Query(Criteria.where("id").is(user.getId()));
Update update = new Update().set("userName", user.getUserName()).set("password", user.getPassWord());
UpdateResult result = mongoTemplate.updateFirst(query, update, User.class);
if(result!=null)
return result.getMatchedCount();
else
return 0;
}
@Override
public void deleteUserById(Long id) {
Query query = new Query(Criteria.where("id").is(id));
mongoTemplate.remove(query, User.class);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。