stakowerflol
stakowerflol

Reputation: 1079

Maping table misses non unique id in @manyToMany

This is the jpa fragment code:

@Entity
public class Author {

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

    @ManyToMany
    @JoinTable(name = "author_book", joinColumns = @JoinColumn(name = "author_id"),
    inverseJoinColumns = @JoinColumn(name = "book_id"))
    private Set<Book> books = new HashSet<>();

.

 @Entity
    public class Book {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private long id;
        private String title;
        private String isbn;

        @OneToOne
        private Publisher publisher;

        @ManyToMany(mappedBy = "books")
        private Set<Author> authors = new HashSet<>();

.

private void initData() {

        Publisher publisher1 = new Publisher("Tabor");
        publisherRepository.save(publisher1);

        // Magdo, Madziu, Magdaleno
        Author author1 = new Author("Magda", "Magdaleńska");
        Book book1 = new Book("Tytuł książki 1", "123456abc", publisher1);

        author1.getBooks().add(book1);
        book1.getAuthors().add(author1);

        bookRepository.save(book1);
        authorRepository.save(author1);


        // Cygan
        Author author2 = new Author("Cygan", "Śniady");
        Book book2 = new Book("Jak sprzedać dywan", "222", publisher1);
        Book book3 = new Book("Jak sprzedać dywan2", "2223", publisher1);

        author2.getBooks().add(book2);
        author2.getBooks().add(book3);
        book2.getAuthors().add(author2);
        book3.getAuthors().add(author2);

        bookRepository.save(book2);
        bookRepository.save(book3);
        authorRepository.save(author2);
    }

which generates these tables in database:
author book

ab

In the third table the third row is missing with values(6, 5).
I don't understand why. There is a primary key set on author_id and book_id and a foreign key on author_id not unique and a foreign key on book_id not unique:

sp

Any prompts how to fix it?

Upvotes: 0

Views: 72

Answers (1)

CRISTIAN ROMERO MATESANZ
CRISTIAN ROMERO MATESANZ

Reputation: 1828

I have just created a GitHub repo with your code to be able to test it. (Feel free to clone it):

https://github.com/cristianprofile/stack_overflow_response/tree/master

It works fine: 3 tuples are added to author_book.

enter image description here

enter image description here

Upvotes: 1

Related Questions