我正在尝试在MongoDB中创建一个Users数据库,而ive却不了解如何创建数据库并将信息添加到DB的基本知识,但是当我运行该应用程序并检查是否在MongoDB Compass中建立了数据库时,我什么也没看到。我有0个代码错误,所以我不确定问题出在哪里。
任何对此的建议/帮助,将不胜感激。
实体;
@Document(collection = "Users")
public class User {
@Id
private String _firstname;
@Indexed(direction = IndexDirection.ASCENDING)
private String _surname;
private String _email;
private int _nhsid;
private String _password;
private Address _address;
public User(String _firstname, String _surname, String _emaik, int _nhsid, String _password, Address _address) {
this._firstname = _firstname;
this._surname = _surname;
this._email = _emaik;
this._nhsid = _nhsid;
this._password = _password;
this._address = _address;
}
Getters / Setters
public class Address {
private String _addressline;
private String _postcode;
private String _county;
public Address(String _addressline, String _postcode, String _county) {
this._addressline = _addressline;
this._postcode = _postcode;
this._county = _county;
}
Getters / Setters
用户存储库;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface UserRepository extends MongoRepository<User, String> {
}
添加数据的测试类;
@Component
public class TestClass implements CommandLineRunner {
private UserRepository userRepo;
public TestClass(UserRepository userRepo) {
this.userRepo = userRepo;
}
@Override
public void run(String... args) throws Exception {
User test1 = new User("XXXXXXX",
"XXXXX",
"FFFFFFFFFFFFFF",
166673823,
"Test123",
new Address("5 Willet Lane", "XXXXXXXXXXXXX", "London"));
User test2 = new User("Davneet",
"Singh",
"ManlikeDavs50@hotmail.co.uk",
1664433333,
"Test123",
new Address("5 End Wills", "UB5 6JQ", "London"));
this.userRepo.deleteAll();
List<User> allUsers = Arrays.asList(test1,test2);
this.userRepo.saveAll(allUsers);
}
}
控制器;
@RestController
@RequestMapping("/Users")
public class accountServiceController {
private UserRepository userRepo;
public accountServiceController(UserRepository userRepo) {
this.userRepo = userRepo;
}
@GetMapping("/getUsers")
public List<User> getAllUsers(){
List<User> users = this.userRepo.findAll();
return users;
}
}
应用程序属性;
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=Users
答案 0 :(得分:0)
我看不到告诉MongoDB在您提供的代码中创建Schema和表的配置。
请参考以下链接:Unable to get spring boot to automatically create database schema