mongodb
docker 安装mongodb-创建用户
docker run -itd --name mongo -p 27017:27017 mongo --auth
docker exec -it mongo mongo admin
# 创建一个名为 admin,密码为 123456 的用户。
db.createuser({ user:'admin',pwd:'123456',roles:[ { role:'userAdminAnyDatabase', db: 'admin'},"readWriteAnyDatabase"]});
# 尝试使用上面创建的用户信息进行连接。
db.auth('admin', '123456')
使用这个账号连接navicat是可以正常使用的,但是连接java代码会报错
org.springframework.data.mongodb.UncategorizedMongoDbException:
Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='admin', source='cloud_iexe', password=<hidden>, mechanismProperties=<hidden>}; nested exception is com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='admin', source='cloud_iexe', password=<hidden>, mechanismProperties=<hidden>}
db.createuser(
{
user: "wenqiang",
pwd: "1438438",
roles: ["readWrite"]
}
)
@Document(collection = "user")
public class MongoUser implements Serializable {
@Id
private String id;
@Field("user_name")
private String userName=null;
private String note=null;
@Field("roles")
private List<MongoRole> roleList=null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public List<MongoRole> getRoleList() {
return roleList;
}
public void setRoleList(List<MongoRole> roleList) {
this.roleList = roleList;
}
}
db: 可以用通过template也可以用:
public interface MongoDbUserRepository extends MongoRepository<MongoUser,String> {
}
public MongoUser saveUser(MongoUser mongoUser){
MongoUser mongoUser1=mongoDbUserRepository.save(mongoUser);
return mongoUser1;
}
@Autowired
private MongoUserServiceImpl mongoUserService;
@Test
public void saveMongoUser(){
MongoUser mongoUser=new MongoUser();
mongoUser.setId("1");
mongoUser.setUserName("亚索");
mongoUser.setNote("托儿索");
MongoRole mongoRole=new MongoRole();
mongoRole.setId("3");
mongoRole.setRoleName("中单");
mongoRole.setNote("快乐风男");
List<MongoRole> mongoRoleList=new ArrayList<MongoRole>();
mongoRoleList.add(mongoRole);
mongoUser.setRoleList(mongoRoleList);
logger.info("新增用户{}",new Gson().toJson(mongoUserService.saveUser(mongoUser)));
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。