What is the best way to map entity with JPA composite key?

Asked

Viewed 177 times

3

I have two tables to map in two entities.
I need to list on the screen like this:

Id | Produto | Cliente | Razão Social  | País   | Estado
-----------------------------------------------------------------
1  | TV      | 000001  | Jao da Silva  | Brasil | São Paulo
2  | PC      | 000001  | Jao da Silva  | Brasil | Rio de Janeiro
3  | TV      | 000002  | Maria Pereira | EUA    | Florida

Since the country and state is a region control of products reservation, it is not the customer’s location.

The second table is generic with composite key... so far so good. Just map using InheritanceType and create the IdClass. The problem is I don’t have the field TYPE (DiscriminatorColumn) in the reserve table

The ERP system is old, I have no way to modify the tables. I have tried to query without mapping with DTO doing Join left, I have tried subquery. But I couldn’t.

What is the best way to solve?

Reservations:

|ID| PRODUTO|CLIENTE|PAIS|ESTADO|
---------------------------------
|1 | 1      |000001 |001 |SP    |
|2 | 2      |000001 |001 |RJ    |
|3 | 1      |000002 |002 |FL    |

Elements:

|TIPO|ID |DESCRICAO     |
--------------------
|NAZ |001|Brasil        |
|NAZ |002|EUA           |
|EST |SP |São Paulo     |
|EST |RJ |Rio de Janeiro|
|EST |FL |Florida       |

Entity 1:

@Entity 
public class Reserva implements Serializable {

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

    @Column(name = "PRODUTO")
    private String produto;

    @ManyToOne
    private Cliente cliente;

    @Column(name = "PAIS")
    private String pais;

    @Column(name = "ESTADO")
    private String estado;

    //Getters & Setters
}

Entity 2:

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "TIPO")
@IdClass(ElementoPK.class)
public abstract class Elemento implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "TIPO")
    private String tipo;

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

    @Column(name = "DESCRICAO")
    private String descricao;

    //Getters & Setters
}

public class ElementoPK implements Serializable {

    private String tipo;
    private String id;

    //Getters & Setters
}

@Entity
@DiscriminatorValue("NAZ")
public class Pais extends Elemento implements Serializable {
}

@Entity
@DiscriminatorValue("EST")
public class Estado extends Elemento implements Serializable {
}
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.