1.生成一个springboot mongodb项目
2.解压生成的zip,在src/main/resources/application.properties配置mongodb的基本信息
spring.data.mongodb.host=127.0.0.1 spring.data.mongodb.port=27017 spring.data.mongodb.database=demo-mongo
3.创建一个POJO持久化对象
package cn.dxbtech.domain; import org.springframework.data.annotation.Id; public class User { @Id private Integer id; private String name; public User() { } public User(Integer id, String name) { this.id = id; this.name = name; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
3.创建Repository
package cn.dxbtech.domain; import org.springframework.data.mongodb.repository.MongoRepository; public interface UserRepository extends MongoRepository<User,Integer> { }
4.调用(repository的高级应用见spring data jpa)
package cn.dxbtech.test; import cn.dxbtech.domain.User; import cn.dxbtech.domain.UserRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.List; @Component public class Runner { @Autowired public Runner(UserRepository userRepository) { final Logger logger = LoggerFactory.getLogger(getClass()); //insert User user = userRepository.save(new User(1, "dxbtech.cn")); User user2 = userRepository.save(new User(2, "小明")); logger.info("创建用户成功 : [{}],[{}]", user, user2); //query List<User> all = userRepository.findAll(); logger.info("查询用户 : [{}]", Arrays.toString(all.toArray())); } }