Spring Boot viele bis viele posten in beide RichtungenJava

Java-Forum
Guest
 Spring Boot viele bis viele posten in beide Richtungen

Post by Guest »

Neuling zum Spring -Start hier. Ich möchte die gleiche Funktionalität. Ein Autor kann mehrere Bücher haben und auch ein Buch kann von mehr als einem Autoren gemeinsam geschrieben werden. Ich bin zu einem Ergebnis gekommen, in dem das Posten eines Autors wie beabsichtigt funktioniert, aber das Posten eines Buches aktualisiert die Join -Tabelle nicht, obwohl sowohl Benutzer als auch Büchertabellen aktualisiert werden. Meine Datenbank ist postgres.

Code: Select all

@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>
Bücher Klasse: < /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>
Buchcontroller: < /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>
Benutzercontroller: < /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>
Benutzerdienst < /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>
Buchdienst: < /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>
Rollen ist ein einfacher Auflauf: < /p>
public enum Roles {
AUTHOR, ADMIN, GUEST
}
Beispiel für Postman -Anfragen:
Post: localhost: 8080/api/user

// Benutzer mit Buch einfügen
// funktioniert gut

Code: Select all

body:
{
"password":"itsDanBrown",
"dateOfBirth":"1964-07-22",
"fullName":"Dan Brown",
"email":"[email protected]",
"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/user

// Buch mit Benutzer
// Einfügen in die Tabelle und Bücher in Benutzern einfügen, aber nicht in user_books table < /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": "[email protected]"
}
]
}
< /code>
Danke im Voraus!
(Java Version 18, Spring Boot 3.4.2) < /P.>

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post