Setix
Setix

Reputation: 141

JPA2 One-To-Many Empty Join Table

I'm trying to create a one-to-many relationship between Publications and Authors, however for some reason when I persist the Publication, the Authors get persisted, but the Join table is empty.

Publication.java

@Id
@Column(name="PUBLICATIONID")
private String id;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "authorspublication", fetch = FetchType.EAGER)
private Collection<Author> authors;

Author.java

@Id
@Column(name = "AUTHORID")
private String authorid;

@ManyToOne(optional = false, targetEntity = Publication.class)
@JoinColumn(name = "authorspublication", referencedColumnName = "publicationid")
private Publication authorspublication;

DataParser.java

//pub is created - non managed
//author is created - non managed

author.setPublication(pub);
pub.getAuthors().add(author);

em.merge(pub);

I dont know if owning sides are backwards, or if its something else.

Any insight would be appreciated.

Upvotes: 0

Views: 1146

Answers (2)

Neil Stockton
Neil Stockton

Reputation: 11531

You haven't defined it to use a @JoinTable; it is currently using a foreign key hence why no insert into the join table. You need to add

@JoinTable

to the one to many field (authors). Don't forget to remove the @JoinColumn since that is for FK relations

Upvotes: 0

Alan Hay
Alan Hay

Reputation: 23246

You are using @JoinColumn which indicates you are using a FK column in the authors table to link publications to their authors.

If you want to use a join table you need to remove this and use the @JoinTable annotation. However it seems to me that you have your mappings the wrong way round. Surely the relationship is OneToMany from Authors to Publications? For that matter surely an author can have many publications and a publication can have more than one author?

For the scenario posted however it should like:

public class Publication{

    @Id
    @Column(name="PUBLICATIONID")
    private String id;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "publications", fetch = FetchType.EAGER)
    private Collection<Author> authors;
}


public class Author{

    @Id
    @Column(name = "AUTHORID")
    private String id;

    @ManyToOne
    @JoinTable(name = "author_publications", joinColumn = @JoinColumn(name = "AUTHORID"), inverseJoinColumn = @JoinColumn(name = "PUBLICATIONID"))
    private Publication publications;
}

However you probably want to change the Publication field in Author to a be a Collection of Publications and replace the @OnetoMany with a @ManyToMany

Upvotes: 2

Related Questions