MongoDBとRestコントローラを使用してspringbootアプリケーションを作成し、OneToManyなどの古典的なJpaアノテーションの代わりにDBRefを使用してオブジェクトを一緒に接続しようとしています。目的は特定のアカウントのすべてのブックマークを印刷することです。ブックマークのリストはユーザー名で見つかりますが、動作しないようです。spongbootでmongoDBを使ってエンティティ間のリレーショナルマッピングを作成する方法は?
これらは私のクラスである:
@Document
public class Account {
@DBRef
private Set<Bookmark> bookmarkSet = new HashSet<>();
@Id
private String id;
@JsonIgnore
private String username;
private String password;
public Account(String username, String password) {
this.username = username;
this.password = password;
}
public void setBookmarkSet(Set<Bookmark> bookmarkSet) {
this.bookmarkSet = bookmarkSet;
}
public String getId() {
return id;
}
}
@Document
public class Bookmark {
@DBRef
@JsonIgnore
private Account account;
@Id
private String id;
private String uri;
private String description;
public Bookmark(Account account, String uri, String description) {
this.account = account;
this.uri = uri;
this.description = description;
}
public Account getAccount() {
return account;
}
public String getId() {
return id;
}
public String getUri() {
return uri;
}
public String getDescription() {
return description;
}
}
リポジトリ:
public interface AccountRepository extends MongoRepository<Account, Long> {
Optional<Account> findOneByUsername(String username);
}
public interface BookmarkRepository extends MongoRepository<Bookmark, Long> {
Collection<Bookmark> findByAccountUsername(String username);
}
そしてRestController:
@RestController
@RequestMapping("/{userId}/bookmarks")
public class BookmarkRestController {
private final AccountRepository accountRepository;
private final BookmarkRepository bookmarkRepository;
@Autowired
public BookmarkRestController(AccountRepository accountRepository, BookmarkRepository bookmarkRepository) {
this.accountRepository = accountRepository;
this.bookmarkRepository = bookmarkRepository;
}
@RequestMapping(value = "/{bookmarkId}", method = RequestMethod.GET)
Bookmark readBookmark(@PathVariable String userId, @PathVariable Long bookmarkId) {
this.validateUser(userId);
return bookmarkRepository.findOne(bookmarkId);
}
@RequestMapping(method = RequestMethod.GET)
Collection<Bookmark> readBookmarks(@PathVariable String userId) {
this.validateUser(userId);
return this.bookmarkRepository.findByAccountUsername(userId);
}
private void validateUser(String userId) {
this.accountRepository.findOneByUsername(userId).orElseThrow(() -> new UserNotFoundException(userId));
}
}
私は、アプリケーションを実行した後、私はこのエラーを取得する:
Invalid path reference account.username! Associations can only be pointed to directly or via their id property!
しかし、私は1000のブックマークがある場合、それらを保存する方法は、手動で格納することは狂っています。私はAutowireを使うべきですか?どのくらい正確に? – Gustavo
私は自分の答えを更新しました。乾杯 – robjwilkins