2

Is there a way in JPA 2 to use a @JoinTable to generate a UUID key for the id of the row? I do not want to create new entity for this table (even if that would solve the problem) and I do not want to create it from the DB.

    @ManyToMany
    @JoinTable(name="Exams_Questions", schema="relation",
            joinColumns = @JoinColumn(name="examId", referencedColumnName="id"),
            inverseJoinColumns = @JoinColumn(name="questionId", referencedColumnName = "id"))   
    private List<Question> questions = new ArrayList<Question>();

db table

CREATE TABLE [relation].[Exams_Questions](
    [id] [uniqueidentifier] PRIMARY KEY NOT NULL,
    [examId] [uniqueidentifier] NOT NULL,
    [questionId] [uniqueidentifier] NOT NULL,
Marthin
  • 6,413
  • 15
  • 58
  • 95
  • The question being asked is hard to understand due to grammatical problems. – Richard Sitze Mar 24 '13 at 16:40
  • Not sure if you are still around, but what solution did you finally go with? I am trying to do the same thing, no reason to make the Join Table as an @Entity when there is only 3 actual fields being the table's ID, and the two ids from the 2 tables that are being joined together by the join table. – bytor99999 Mar 30 '22 at 15:45
  • Cant remember to be honest, But the answer given seems like the best way forward – Marthin Apr 04 '22 at 07:02

1 Answers1

0

Not sure exactly what the question is, but let me try a response.

For your first sentence alone, I would say "Yes" and "Possibly":

  1. You'll need a separate @Entity class for the Question, and in that class you'd specify the mapping for id.

  2. There is no way using spec JPA to specify auto-generation of a UUID value for a column. There are ways using OpenJPA and Hibernate. EclipseLink will allow you to create a custom generator for this purpose, and their example is, in fact, for a UUID.

If you'd like to expose properties of the join-table OR otherwise have JPA manage them (i.e. the id on the Exams_Questions table), then see this external link (found on this answer). You'll end up with @OneToMany relations from Exam/Question entities to the join table, and @ManyToOne relations from the join table to Exam/Question entities.

Exposing the join table as an entity will let you manage a separate key (uuid). If you don't need the uuid primary key, then don't do this - it's not necessary to solve the problem, as the examId/questionId combination is unique.

Community
  • 1
  • 1
Richard Sitze
  • 8,262
  • 3
  • 36
  • 48