文章19 | 阅读 10061 | 点赞0
# 启动服务,需要指定db路径
> ./bin/mongod --dbpath ./data/db/
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
注意:如果密码单独配需要加单引号
spring:
data:
mongodb:
#uri: mongodb://mongo:123456@localhost:27017/test
host: localhost
port: 27017
database: test
username: mongo
password: '123456'
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Address implements Serializable {
private String province;
private String city;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserInfo {
private Integer gender;
}
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "user")
@CompoundIndex( def = "{'id': 1, 'nickname': -1}")
public class User implements Serializable {
@Id
private String id;
@Indexed
@Field("username")
private String username;
private String nickname;
private Integer age;
private Date createTime;
private UserInfo userInfo;
private List<String> tags;
private List<Address> addresses;
}
public interface UserRepository extends MongoRepository<User, String> {
}
@SpringBootTest
@RunWith(SpringRunner.class)
class SpringbootMongodbApplicationTests {
@Autowired
private UserRepository userRepository;
@Test
void testMongoDB() {
User user = new User();
user.setId("1");
user.setUsername("monday");
user.setNickname("mengday");
user.setAge(30);
user.setCreateTime(new Date());
user.setUserInfo(new UserInfo(1));
user.setTags(Arrays.asList("xiaojiejie", "dog"));
user.setAddresses(Arrays.asList(
new Address("shanghai", "pudong"),
new Address("beijing", "chaoyang")
));
userRepository.save(user);
List<User> userList = userRepository.findAll();
System.out.println("userList=" + userList);
User result = userRepository.findById("1").get();
System.out.println(result);
userRepository.deleteById("1");
}
}
Spring Data : Spring 的一个子项目。用于简化数据库访问,支持NoSQL 和 关系数据存储。其主要目标是使数据库的访问变得方便快捷。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://monday.blog.csdn.net/article/details/115673902
内容来源于网络,如有侵权,请联系作者删除!