以Spring Boot为例,连接MongoDB有两种主要方式:使用MongoTemplate或使用MongoRepository。
使用MongoTemplate
- 添加MongoDB和Spring Data MongoDB依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
- 在application.properties中添加数据库配置
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=yourusername
spring.data.mongodb.password=yourpassword
spring.data.mongodb.database=yourdbname
- 创建实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "users")
public class User {
@Id
private String id;
private String name;
private Integer age;
}
- 创建MongoTemplate
@Configuration
public class MongoConfig {
@Autowired
private MongoClient mongoClient;
@Bean
public MongoTemplate mongoTemplate() {
return new MongoTemplate(mongoClient, "yourdbname");
}
}
- 在service/dao层使用MongoTemplate
@Service
public class UserService {
@Autowired
private MongoTemplate mongoTemplate;
public void saveUser(User user) {
mongoTemplate.save(user);
}
public User getUser(String id) {
Query query = Query.query(Criteria.where("_id").is(id));
return mongoTemplate.findOne(query, User.class);
}
public void updateUser(User user) {
Query query = Query.query(Criteria.where("_id").is(user.getId()));
Update update = new Update();
update.set("name", user.getName());
update.set("age", user.getAge());
mongoTemplate.updateFirst(query, update, User.class);
}
public void deleteUser(String id) {
Query query = Query.query(Criteria.where("_id").is(id));
mongoTemplate.remove(query, User.class);
}
}
使用MongoRepository
- 添加MongoDB和Spring Data MongoDB依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
- 在application.properties中添加数据库配置
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=yourusername
spring.data.mongodb.password=yourpassword
spring.data.mongodb.database=yourdbname
- 创建实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "users")
public class User {
@Id
private String id;
private String name;
private Integer age;
}
- 创建MongoRepository
public interface UserRepository extends MongoRepository<User, String> {
User findByName(String name);
}
- 在service/dao层使用MongoRepository
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void saveUser(User user) {
userRepository.save(user);
}
public User getUser(String id) {
return userRepository.findById(id).orElse(null);
}
public void updateUser(User user) {
userRepository.save(user);
}
public void deleteUser(String id) {
userRepository.deleteById(id);
}
}
以上就是使用MongoTemplate和MongoRepository两种方式连接MongoDB的完整攻略。
示例:实现一个简单的用户登录和注册功能
- 创建UserController,添加REST接口
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/register")
public String register(@RequestBody User user) {
if (userService.getUserByName(user.getName()) != null) {
return "用户名已存在";
} else {
userService.saveUser(user);
return "注册成功";
}
}
@PostMapping("/login")
public String login(@RequestBody User user) {
User foundUser = userService.getUserByName(user.getName());
if (foundUser == null) {
return "用户不存在";
} else if (foundUser.getPassword().equals(user.getPassword())) {
return "登录成功";
} else {
return "密码错误";
}
}
}
- 修改UserService,添加getUserByName方法
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void saveUser(User user) {
userRepository.save(user);
}
public User getUserById(String id) {
return userRepository.findById(id).orElse(null);
}
public User getUserByName(String name) {
return userRepository.findByName(name);
}
public void updateUser(User user) {
userRepository.save(user);
}
public void deleteUser(String id) {
userRepository.deleteById(id);
}
}
- 修改User实体类,添加password属性
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "users")
public class User {
@Id
private String id;
private String name;
private Integer age;
private String password;
}
- 注册新用户
POST /user/register HTTP/1.1
Content-Type: application/json
{
"name": "test",
"age": 18,
"password": "123456"
}
- 登录已存在的用户
POST /user/login HTTP/1.1
Content-Type: application/json
{
"name": "test",
"password": "123456"
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:spring data 连接mongodb的两种方式 - Python技术站