JPA / Hibernate: Mapping a many-to-many relationship when the join table has its own primary key

I have three tables with a simple structure:

pub [id, name]
days [id, name]
pub_days [id, pub_id, days_id]

      

For some wicked reason, someone thought that a tricky identity for the pub_days table (which would be pub_id + days_id) was not enough and would add its own primary key. I cannot change it now, a different and higher system depends on it. #sigh

I'm trying to map this to Hibernate with the standard @ManyToMany

JPA annotation , so (I didn't use getters, setters, @Entitiy annotations and other hindrances):

class Pub {

    @ManyToMany(cascade = {CascadeType.ALL})
    @JoinTable(name = "pub_days",
            joinColumns = {@JoinColumn(name = "pub_id")},
            inverseJoinColumns = {@JoinColumn(name = "days_id")})
    @OrderBy("id")
    private List<Day> pubOpeningDays;
}

class Day {
    @Id Long id;
    String name.
}

      

when i execute the following code:

Day day = repository.find(Day.class, id);
pub.getPubOpeningDays().add(day);
repository.persist(pub);

      

I am getting this error:

ERROR: ORA-01400: cannot insert NULL into ("PUB"."pub_days"."id")

      

Unfortunately this makes sense because I have not matched this ID anywhere. The thing is, I don't even want to do this. I want it to be generated but not sure how to solve this with @ManyToMany

mapping. Any ideas?

+3


source to share


2 answers


What you can do is that I mentioned in my comments that you can create a separate CD with objects, which in turn will connect with two classes A and B, Now the relationship will be numerous for many between A and B and therefore A (many for many) CD (many for many) B. Now, according to your requirement, when you need to get an instance of A or B, you can simply run a query in the DB with the proper parameters, i.e. id or id b this will help you get the desired result.



0


source


I only see two options, either you change your collation to a PubDay list like samwise-gamgee told you in the comments, or you add a trigger to insert into table pub_days that set a value for the column id if it is null (it can use the sequence ). But this approach depends on the features your DB supports.



0


source







All Articles