Весенний ботинок много ко многим публикации в обоих направленияхJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Весенний ботинок много ко многим публикации в обоих направлениях

Сообщение Anonymous »

ЗДЕСЬ НОВОЙ КОНТУРЫ. Я хочу такую ​​же функциональность. Автор может иметь несколько книг, а также книга может быть написана в соавторстве более чем одним автором. Я пришел к результату, когда публикация автора работает так, как предполагалось, но публикация книги не обновляет таблицу соединения, хотя обновляются как пользователи, так и таблицы книг. Моя база данных - Postgres.
Детали реализации: < /p>
Класс пользователей: < /p>

Код: Выделить всё

@Entity
@Table
@Getter
@Setter
@NoArgsConstructor
public class Users {

@Id
@SequenceGenerator(
name = "user_sequence",
sequenceName = "user_sequence",
allocationSize = 1
)
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "user_sequence"
)

private Long userId;
private String password;
private LocalDate dateOfBirth;
private String fullName;
private String email;

@Enumerated(EnumType.STRING)
private Roles role;

@ManyToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "USERS_BOOKS", joinColumns = {
@JoinColumn (name = "User_id", referencedColumnName = "userId")
},
inverseJoinColumns = {
@JoinColumn(name = "BookId", referencedColumnName = "bookId")
})
private Set books;

public Users(String password, LocalDate dateOfBirth, String fullName, String email, Roles role){
this.password = password;
this.dateOfBirth = dateOfBirth;
this.fullName = fullName;
this.email = email;
this.role = role;
}

public Users(String password, LocalDate dateOfBirth, String fullName, String email, Set books){
this.password = password;
this.dateOfBirth = dateOfBirth;
this.fullName = fullName;
this.email = email;
this.books = books;
}

public void addBooks(Set books){
if(this.role == Roles.AUTHOR){
for(Book book : books)
try{
this.books.add(book);
book.addAuthors(Set.of(this));
} catch(Exception e){
System.out.println("Wrong type of object for a List of Book");
continue;
}
} else {
throw new IllegalArgumentException("Non author users cannot hold books");
}
}

public void removeBooks(Set books){
for(Book book : books)
for(Book user : this.books){
if (user.equals(book)) {
this.books.remove(user);
}
else{
System.out.println("Book: "+book.getTitle()+ " is already not in set.");
}
}
}

}
< /code>
Класс книг: < /p>
@Table(name = "Books")
@Entity
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor

public class Book {
@Id
@SequenceGenerator(
name = "book_sequence",
sequenceName = "book_sequence",
allocationSize = 1
)
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "book_sequence"
)
private Long bookId;
private String title;
private LocalDate releaseDate;
private String genresStr;
@Column(columnDefinition = "text")
private String content;

@ManyToMany(mappedBy="books", fetch=FetchType.LAZY, cascade = CascadeType.ALL)

private Set authors;

public Book(String title, LocalDate releaseDate, String content, String genresStr){
this.genresStr = genresStr;
this.title= title;
this.releaseDate = releaseDate;
this.content = content;
}

public Book(String title, LocalDate releaseDate, String content, String genresStr, Set authors){
this.genresStr = genresStr;
this.title= title;
this.releaseDate = releaseDate;
this.content = content;
this.authors = authors;
}

public void addAuthors(Set authors){
System.out.println("addAuthorsCalled");
for(Users author : authors)
try{
this.authors.add(author);
author.addBooks(Set.of(this));
author.setRole(Roles.AUTHOR);
} catch(Exception e){
System.out.println("Wrong type of object for a List of Users");
}
}

public void removeAuthors(Set  authors){
if(authors.size() == 1){
System.out.println("Can't delete all authors for certain book");
return;
}
for(Users author : authors)
for(Users user : this.authors){
if (user.equals(author)) {
this.authors.remove(user);
}
else{
System.out.println("User: "+author.getFullName()+ " is already not in set.");
}
}
}
}
< /code>
Контроллер книги: < /p>
@RestController
@RequestMapping(path = "api/books")
public class BookController {

private final BookService bookService;
private UserService userService;

public BookController(@Autowired BookService bookService, UserService userService){
this.bookService = bookService;
this.userService = userService;
}

@GetMapping
public List getBooks(){
return bookService.getBooks();
}

@PostMapping
public void addBook(@RequestBody Book book){
if(!book.getAuthors().isEmpty()){
for(Users author :  book.getAuthors()){
author.setRole(Roles.AUTHOR);
userService.saveUser(author);
}
}
bookService.saveBook(book);
}

@DeleteMapping(path="{bookId}")
public void deleteBook(@PathVariable ("bookId") Long bookId){
bookService.deleteBook(bookId);
}

@PutMapping(path="{bookId}")
public void updateBook(
@PathVariable("bookId") Long bookId,
@RequestParam(required = false) String title,
@RequestParam(required = false) LocalDate releaseDate,
@RequestParam(required = false) String content,
@RequestParam(required = false) Set userIds

){
Set usersToAdd = null;
if(userIds!=null){
usersToAdd = userService.getUsersById(userIds);
}
bookService.updateBook(bookId, title, releaseDate, content, usersToAdd);
}

@PutMapping(path = "/{bookId}/delAuthor")
public void putMethodName(
@PathVariable Long bookId,
@RequestParam(required = true) Set userIds
){
Set usersToRemove = userService.getUsersById(userIds);
bookService.removeAuthors(bookId, usersToRemove);

}
}
< /code>
Пользовательский контроллер: < /p>
@RestController
@RequestMapping(path = "api/users")
public class UserController {

private final UserService userService;

public UserController(@Autowired UserService userService){
this.userService = userService;
}

@GetMapping
public List getAllUsers() {
return userService.getUsers();
}

@PostMapping
public void addNewUser(@RequestBody Users user) {
userService.saveUser(user);

}

@DeleteMapping(path="{userId}")
void deleteUser(@PathVariable ("userId") Long userId){
userService.deleteUser(userId);
}

@PutMapping(path="{userId}")
void updateUser(@PathVariable ("userId") Long userId,
@RequestParam(required = false) String fullName,
@RequestParam(required = false) String password,
@RequestParam(required = false) LocalDate dateOfBirth,
@RequestParam(required = false) String email,
@RequestParam(required = false) Set bookIds
){
userService.updateUser(userId, password, dateOfBirth, fullName, email, bookIds);
}
}
< /code>
Пользовательская служба < /p>
@Service
public class UserService {

private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

private final UserRepository userRepository;
private BookRepository bookRepository;

public UserService(@Autowired UserRepository userRepository, BookRepository bookRepository){
this.userRepository = userRepository;
this.bookRepository = bookRepository;
}

public Users getUser(Long id){
return this.userRepository.getReferenceById(id);
}

public List  getUsers(){
return this.userRepository.findAll();
}

public Set getUsersById(Set userIds){
Set users = new HashSet();
for(Long userId : userIds)
if(userId != null){
users.add(this.getUser(userId));
}
return users;
}

public void saveUser(Users user){
Optional userEmailOptional = userRepository.findUserByEmail(user.getEmail());
if(userEmailOptional.isPresent()){
throw new IllegalStateException("This email already exists in database");
}

if(user.getRole() == Roles.AUTHOR){
Optional authorByFullName = userRepository.findUserByFullName(user.getFullName());
if(authorByFullName.isPresent()){
throw new IllegalStateException("Authors cannot have the same name");
}
}
if(user.getBooks() != null && !user.getBooks().isEmpty())
user.setRole(Roles.AUTHOR);

user.setPassword(encoder.encode(user.getPassword()));
if(user.getBooks() != null && !user.getBooks().isEmpty())
for(Book book : user.getBooks())
bookRepository.save(book);
userRepository.save(user);
}

public void deleteUser(Long userId){
boolean exists = userRepository.existsById(userId);
if(!exists){
throw new IllegalStateException("No user with Id: " + userId+ " in database");
}
userRepository.deleteById(userId);
}

@Transactional
public void updateUser(Long userId,
String password,
LocalDate dateOfBirth,
String fullName,
String email,
Set bookIds){
Users user = userRepository.findById(userId).orElseThrow(() ->
new IllegalStateException("No user with id: "+userId+" in database"));
if(password != null && password.length() > 0){
user.setPassword(password);
}
if(dateOfBirth!=null){
user.setDateOfBirth(dateOfBirth);
}
if(fullName!=null && fullName.length() > 0){
user.setFullName(fullName);
}
if(email!=null && email.length() > 0){
Optional userOptional = userRepository.findUserByEmail(email);
if(userOptional.isPresent()){
throw new IllegalStateException("Email "+email+" already exists in database");
}
user.setEmail(email);
}
if(bookIds != null){
Set booksToAdd = new HashSet();
for(Long bookId : bookIds){
booksToAdd.add(bookRepository.getReferenceById(bookId));
}
user.addBooks(booksToAdd);
}
}
}
< /code>
Книжная служба: < /p>
@Service
public class BookService {

private final BookRepository bookRepository;

public BookService(@Autowired BookRepository bookRepository){
this.bookRepository = bookRepository;
}

public List getBooks(){
return bookRepository.findAll();
//List.of(new Book("kostas", LocalDate.of(2000, Month.APRIL, 12)));
}

public void saveBook(Book book){

bookRepository.save(book);
}

public void deleteBook(Long bookId){
boolean exists = bookRepository.existsById(bookId);
if(!exists){
throw new IllegalStateException("Book with id: " + bookId + " does not exist");
}
bookRepository.deleteById(bookId);
}

@Transactional
public void removeAuthors(Long bookId, Set authors){
Book book = bookRepository.findById(bookId).
orElseThrow(() -> new IllegalStateException("No books with the id requested"));
if(!authors.isEmpty())
book.removeAuthors(authors);
}

@Transactional
public void updateBook(Long bookId, String title, LocalDate releasDate, String content, Set  authors){
Book book = bookRepository.findById(bookId).
orElseThrow(() -> new IllegalStateException("No books with the id requested"));

if(title != null && title.length() > 0){
book.setTitle(title);
}
if(releasDate != null){
book.setReleaseDate(releasDate);
}
if(content != null && content.length() > 0){
book.setContent(content);
}
if(authors != null)
book.addAuthors(authors);
}
}
< /code>
Роли - это простой переход: < /p>
public enum Roles {
AUTHOR, ADMIN, GUEST
}
Пример запросов почтальона:
post: localhost: 8080/api/users

// Вставка пользователя в книгу
// работает нормально

Код: Выделить всё

body:
{
"password":"itsDanBrown",
"dateOfBirth":"1964-07-22",
"fullName":"Dan Brown",
"email":"d.brown@mail.com",
"books":[
{
"title":"The Da Vinci Code",
"releaseDate":"2003-03-18",
"content":"",
"genres":["Mystery", "detective fiction", "conspiracy fiction", "thriller"]
},
{
"title":"Angels & Demons",
"releaseDate":"2000-05-30",
"content":"",
"genres":["Mystery", "thriller"]
}
]
}
post: localhost: 8080/api/users

// Вставка книги с пользователем
// Включает значение в таблицу пользователей и таблицу книг, но не В таблице users_books < /p>
{
"title":"The Da Vinci Code",
"releaseDate":"2003-03-18",
"content":"",
"genres":["Mystery", "detective fiction", "conspiracy fiction", "thriller"],
"authors":[
{
"password":"password",
"dateOfBirth":"2000-02-02",
"fullName":"Dan Brown",
"email": "d.brown@email.com"
}
]
}
< /code>
Заранее спасибо!
(Java версия 18, Spring Boot 3.4.2) < /p>

Подробнее здесь: https://stackoverflow.com/questions/794 ... -both-ways
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Весенний ботинок много ко многим публикации в обоих направлениях
    Anonymous » » в форуме JAVA
    0 Ответы
    11 Просмотры
    Последнее сообщение Anonymous
  • Весенний ботинок много ко многим публикации в обоих направлениях
    Anonymous » » в форуме JAVA
    0 Ответы
    10 Просмотры
    Последнее сообщение Anonymous
  • Обновление контекста приложения WCSession в обоих направлениях
    Anonymous » » в форуме IOS
    0 Ответы
    18 Просмотры
    Последнее сообщение Anonymous
  • Графический каркас, идущий в обоих направлениях
    Anonymous » » в форуме Python
    0 Ответы
    29 Просмотры
    Последнее сообщение Anonymous
  • Графический каркас, идущий в обоих направлениях
    Anonymous » » в форуме Python
    0 Ответы
    26 Просмотры
    Последнее сообщение Anonymous

Вернуться в «JAVA»