Composite primary key of two foreign keys

Viewed 1119

I have a problem in the structure of an Entity, I am using Hibernate + JPA. The class consists of a user classification, where a primary key will be the user (coming from the Usuario class), and the other is the season (coming from the Temporada class). Below the class structure:

@Entity(name = "CLASSIFICACAO")
@Data
public class Classificacao implements Serializable
{
  @Id
  @GeneratedValue(generator="SharedPrimaryKeyGenerator")
  @GenericGenerator(name="SharedPrimaryKeyGenerator",strategy="foreign",parameters =  @Parameter(name="property", value="usuario"))
  @Column(unique = true, nullable = false)
  private String classificacao;
  @Id
  @GeneratedValue(generator="SharedPrimaryKeyGenerator")
  @GenericGenerator(name="SharedPrimaryKeyGenerator",strategy="foreign",parameters =  @Parameter(name="property", value="temporada"))
  @Column(unique = true, nullable = false)
  private Long codTemporada;
  //another fields  
  @OneToOne
  @PrimaryKeyJoinColumn
  private Usuario usuario;
  @ManyToOne
  @PrimaryKeyJoinColumn
  private Temporada temporada;
}

The 'classificacao' field receives the user's name from the Usuario foreign key; Before I didn't have the 'codTemporada' field as a primary, and it worked like a charm. 'classificacao' received user and was primary, and the 'temporada' only foreign. But now I need the 'codTemporada' field to be primary as well, making a composite primary key class. But I just received the error: broken column mapping for: usuario.id of: br.com.xxxxx.model.Classificacao.

Any suggestions of what I can do?

1 Answers

If you have multiple ids in a entity , you should use EmbeddedId. Here both of your Ids are foreign key constraints , so you need to use @JoinColumn to join them. Sample code for classificacao class and classificacaoId class.

Classificacao.java

@Entity
public class Classificacao implements Serializable {

    @Id
    ClassificacaoId id;

    String name;
    // getter and setter

}

ClassificacaoId.java

@Embeddable
public class ClassificacaoId implements Serializable {

    @OneToOne
    @JoinColumn(name = "userId", referencedColumnName = "userId")
    private Usuario usuarioIo;

    @ManyToOne
    @JoinColumn(name = "tempId", referencedColumnName = "id")
    private Temporada temporada;

    // getter and setter

}

Generated SQL in h2 db

create table classificacao (
    name varchar(255), 
    user_id varchar(255) not null, 
    temp_id bigint not null, 
    primary key (temp_id, user_id)
);
create table temporada (
    id bigint not null, 
    name varchar(255), 
    primary key (id)
);
create table usuario (
    user_id varchar(255) not null, 
    name varchar(255), 
    primary key (user_id)
);
alter table classificacao add constraint FK1najxwr5x189iul4rguqc4wyx 
foreign key (user_id) references usuario;
alter table classificacao add constraint FKlvk517howhduqt5ghb4mgx0ko 
foreign key (temp_id) references temporada;
Related