javajpaentities

Id column comes from other table JPA entities


I have two tables in my DB. Table1 with ID and some other columns. Table2 is a relations table where I have the PK from table1 as id in table2 but i dont use a ID in Table2 and it holds some values to other random data.

In JPA you have to use the @Id annotation. My problem is that I would like to use the entity for table1 to be put in as the @Id for table2 entity. Is this possible and if yes, then how?

Code so far: TABLE 1

@Entity
@Table(name="Log", schema="logs")
@PersistenceUnit(name="domas")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name="type", discriminatorType = DiscriminatorType.STRING)
public abstract class Log implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="id", nullable=false)
    public String id;

    @Column(name="type", nullable=false)
    @Enumerated(EnumType.STRING)
    public LOG_TYPE type;
// and alot more not related code

Table 2

@Entity
@Table(name="Log_Entity", schema="relations")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "relationType", discriminatorType  = DiscriminatorType.STRING)
public abstract class LogRelation implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @OneToOne(mappedBy="id")
    public Log log;

// and alot more not related code

Solution

  • This mappedBy does not make sense if you do not have @OneToOne inverse side with attribute name id and type LogRelation:

    @OneToOne(mappedBy="id")
    

    With following it will work:

    @Id
    @JoinColumn(name="lr_id")//or whatever column name you prefer
    @OneToOne
    Log log;