How to map an entity with a composite key using JPA?

Asked

Viewed 572 times

2

@Entity

@Table(name = "USUARIO")

public class Usuario implements Serializable {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    @Column(name = "ID")
    private Long id;

    @Column(name = "USER_NAME", nullable = false)
    private String userName;
}

@Entity

@Table(name = "CARGO")

public class Cargo implements Serializable {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    @Column(name = "ID")
    private Long id;

    @Column(name = "NAME", nullable = false)
    private String name;
}

@Entity

@Table(name = "USUARIO_CARGO")

public class Cargo implements Serializable {

    @JoinColumn(name = "USARIO_ID")
    private User user;

    @JoinColumn(name = "CARGO_ID")
    private Cargo cargo;
}

3 answers

0

I use it exactly like this and it works.

@Entity
@Table(name = "USUARIO_CARGO")
public class usuario_Cargo implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @ManyToOne
    @JoinColumn(name = "USARIO_ID", referencedColumnName = "ID")
    @NotFound(action = NotFoundAction.IGNORE)
    private User user;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @ManyToOne
    @JoinColumn(name = "CARGO_ID", referencedColumnName = "ID")
    @NotFound(action = NotFoundAction.IGNORE)
    private Cargo cargo;

}

See if it solves...

0

For me, usuario_cargo is a JOIN TABLE, should not become an entity, you can map directly in user or position, in the example, as if it were user:

@ManyToMany
@JoinTable(
  name = "USUARIO_CARGO", 
  joinColumns = @JoinColumn(name = "USARIO_ID"), 
  inverseJoinColumns = @JoinColumn(name = "CARGO_ID"))
List<Cargo> cargos;

0

face I don’t know if that’s what you want but this one

@Entity
@Table(name = "USUARIO_CARGO")
public class usuario_Cargo implements Serializable {

    @Id
    @JoinColumn(name = "USARIO_ID", referencedColumnName= "id")
    private User user;

    @Id
    @JoinColumn(name = "CARGO_ID", referencedColumnName= "id")
    private Cargo cargo;
}

Browser other questions tagged

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