Home > AI > Backend > SpringBoot > mysql-connector-java >

ManyToMany-JpaRepository-CRUD

In this example, one entity gets deleted, the associated entity and relationship will be deleted as well.

Author.java

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "authors")
public class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String firstName;
    private String lastName;

    @ManyToMany(mappedBy = "authors", fetch = FetchType.LAZY)
    private Set<Book> books = new HashSet<>();

}

Book.java

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name="books")
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String title;
    @Column(name="isbn", unique = true)
    private String isbn;
    private String publisher;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "author_book", joinColumns = @JoinColumn(name = "book_id"),
            inverseJoinColumns = @JoinColumn(name = "author_id"))
    private Set<Author> authors;


    public void addAuthor(Author author) {
        if (author == null){
            return;
        }

        if (authors == null) {
            authors = new HashSet<>();
            authors.add(author);

            author.getBooks().add(this);
        }
    }

}

BookRepository.java

@Repository
public interface BookRepository extends JpaRepository<Book, Long> {
    List<Book> findByIsbn(String isbn);
}

Bo0kController.java (not used)

@RestController
@RequestMapping("books")
public class BookController {
    @Autowired
    BookRepository bookRepository;

    @GetMapping
    public List<Book> findAll() {

        return bookRepository.findAll();

    }

    @PostMapping
    public Boolean save(@RequestBody Book book) {
        try {
            bookRepository.save(book);
            return true;
        } catch (Exception e) {
            System.out.println(e);
            return false;
        }

    }

}

TestRepository.java

@Slf4j
@SpringBootTest
@Transactional
@Rollback(false)
public class TestRepository {


    @Autowired
    BookRepository bookRepository;


    @BeforeEach
    public void init() {
        bookRepository.deleteAll();

        log.info("[Shark] + init" + bookRepository.findAll().size());
    }

    @Test
    public void test_save() {
        log.info("[Shark] + save" );


        Book book = new Book();
        book.setIsbn("23423dfd");
        book.setPublisher("knf");
        book.setTitle("Java");

        Author author1 = new Author();
        author1.setFirstName("Sibin");
        author1.setLastName("knf");

        book.addAuthor(author1);

        bookRepository.save(book);
    }

    @Test
    public void test_delete() {
        log.info("[Shark] + delete" );



        // 1 - save
        Book book = new Book();
        book.setIsbn("23423dfd");
        book.setPublisher("knf");
        book.setTitle("Java");

        Author author1 = new Author();
        author1.setFirstName("Sibin");
        author1.setLastName("knf");

        book.addAuthor(author1);

        bookRepository.save(book);



        // 2 - delete
        bookRepository.deleteById(book.getId());
        System.out.println(bookRepository.findAll().size());

    }



    @Test
    public void test_delete_all() {
        log.info("[Shark] + delete all" );


        bookRepository.deleteAll();
        assertEquals(0, bookRepository.findAll().size());
    }
}

resources/application.properties

server.port = 8888


##################
# Mysql
##################
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
spring.jpa.show-sql= false

Leave a Reply