关于java:springboot-使用MongoDB

36次阅读

共计 1344 个字符,预计需要花费 4 分钟才能阅读完成。

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);
    }
}

正文完
 0