目录
一、新建项目springboot-mongodb,项目结构如下
二、确认pom文件依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
三、配置application.properties
spring.data.mongodb.uri=mongodb://账号:密码@mongodb_host:27017/user?authSource=admin&authMechanism=SCRAM-SHA-1
#spring.data.mongodb.authentication-database=admin
#spring.data.mongodb.password=root
#spring.data.mongodb.username=Root123700
四、创建实体User
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.time.LocalDateTime;
/***
* @date: 2022/7/7
* @author: 微信公众号:深入技术架构
*/
@Data
//指定要对应的文档名(表名)
@Document(collection = "user")
public class User {
/*** 自定义mongo主键 加此注解可自定义主键类型以及自定义自增规则
* 若不加 插入数据数会默认生成 ObjectId 类型的_id 字段
* org.springframework.data.annotation.Id 包下
* mongo库主键字段还是为_id 。不必细究(本文实体类中为id)
*/
@Id
private Long userId;
private String userName;
private LocalDateTime timer;
}
五、创建UserService
import com.duoduo.springbootmongodb.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
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 java.time.LocalDateTime;
import java.util.List;
import java.util.regex.Pattern;
/***
* @date: 2022/7/7
* @author: 微信公众号:深入技术架构
*/
@Service
public class UserService {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 新增用户
*/
public int insertUser(User user){
try {
user.setTimer(LocalDateTime.now());
mongoTemplate.insert(user);
return 1;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
/**
* 根据Id修改 ,如需其他条件 修改Query 查询条件即可
*/
public int updateUser(User user) {
//通过query根据id查询出对应对象,通过update对象进行修改
Query query = new Query(Criteria.where("userId").is(user.getUserId()));
Update update = new Update().set("userName", user.getUserName());
try {
mongoTemplate.updateFirst(query, update, User.class);
return 1;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
/**
* 根据id删除,如需其他删除条件,修改对应Query对象即可
*/
public int removeUser(Long id) {
Query query=new Query(Criteria.where("userId").is(id));
try {
mongoTemplate.remove(query,User.class);
return 1;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
/**
* 查询一个
*/
public User findOne(User user) {
Query query = new Query(Criteria.where("userId").is(user.getUserId()));
User one = mongoTemplate.findOne(query, User.class);
return one;
}
/**
* 查询集合-模糊匹配
*/
public List<User> findlike(User user) {
Pattern pattern = Pattern.compile("^.*" + user.getUserName().trim() + ".*$", Pattern.CASE_INSENSITIVE);
Query query = new Query(Criteria.where("userName").regex(pattern));
List<User> userList = mongoTemplate.find(query, User.class);
return userList;
}
/**
* 查询集合-精确匹配
*/
public List<User> findmore(User user) {
Query query = new Query(Criteria.where("userName").is(user.getUserName()));
List<User> users = mongoTemplate.find(query, User.class);
return users;
}
/**
* 倒叙排列查询
*/
public List<User> findtime(User user) {
Query query = new Query();
Query with = query.with(Sort.by(Sort.Direction.DESC, "timer"));
List<User> users = mongoTemplate.find(query, User.class);
return users;
}
/**
* MongoDB分页查询
*/
public List<User> findtimeByPage(User user) {
Query query = new Query();
query.with(Sort.by(Sort.Direction.DESC, "timer"));
query.skip(0).limit(3);
List<User> users = mongoTemplate.find(query, User.class);
return users;
}
}
六、创建UserController
import com.duoduo.springbootmongodb.entity.User;
import com.duoduo.springbootmongodb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/***
* @date: 2022/7/7
* @author: 微信公众号:深入技术架构
*/
@RestController
public class UserController {
@Autowired
UserService userService;
@RequestMapping("insertUser/{id}")
public String insertUser(@PathVariable("id") long id){
User user = new User();
user.setUserId(id);
user.setUserName("张三" + id);
userService.insertUser(user);
return "insert succ";
}
@RequestMapping("updateUser")
public String updateUser() {
User user = new User();
user.setUserId(1234L);
user.setUserName("张三");
userService.updateUser(user);
return "update succ";
}
@RequestMapping("removeUser")
public String removeUser(){
userService.removeUser(1234L);
return "remove succ";
}
@RequestMapping("getUser")
public String getUser(){
User user = new User();
user.setUserId(1234L);
return userService.findOne(user).toString();
}
}
七、创建配置类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoConverter;
/***
* @date: 2022/7/7
* @author: 微信公众号:深入技术架构
* @description: MongoDB监听配置, 此类若不加,那么插入的一行会默认添加一个_class字段来存储实体类类型 如(com.duoduo.mongodb.entity.User)
*/
@Configuration
public class ApplicationReadyListener implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
MongoTemplate oneMongoTemplate;
private static final String TYPEKEY = "_class";
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
MongoConverter converter = oneMongoTemplate.getConverter();
if (converter.getTypeMapper().isTypeKey(TYPEKEY)) {
((MappingMongoConverter) converter).setTypeMapper(new DefaultMongoTypeMapper(null));
}
}
}
八、测试结果
http://localhost:8080/insertUser/1234
看完帮忙用拼多多扫个码吧,非常感谢。
标签:
大数据
本文转载自: https://blog.csdn.net/f88069684/article/details/125659233
版权归原作者 架构师小冯 所有, 如有侵权,请联系我们删除。
版权归原作者 架构师小冯 所有, 如有侵权,请联系我们删除。