How to create a relationship using JPA that contains attributes?

Asked

Viewed 68 times

3

Hello, I am working on a Java Web project with Hibernate, Postgres, Glassfish, and JPA/JSF usage. The problem is that my relationships were being generated with the following strategy:

 @JoinTable(name = "prop_user", joinColumns = {@JoinColumn(name = "id_prop", referencedColumnName = "idproposicao")}, 
        inverseJoinColumns = {@JoinColumn(name = "id_user", referencedColumnName = "cpf")})
@PrimaryKeyJoinColumn
private UsuarioEntity userProp;

Using the above code in the User entity, I would create a relationship with the Proposition entity, generating a relationship table, but I have no control over it. Everything done via Ibernate by annotation.

And now I need to create an extra field in this relationship, an "Opinion" attribute like String and I don’t know how to do it with JPA.

I saw that it seems that I need to remake relationships, because I will need to create an entity class for this relationship, manually shaping for my need. Someone can confirm I’m on the right track?

Thanks!

1 answer

0

Yes, that’s the way.

You have a Usuarioentity class right? A hint, user is already an entity,and you will persist the objects of this class in a database, for the name of your classes to be more streamlined there is no need to put Entity in front of the name of your class, set only as User.

Returning to your question, you want to assign one or several opinions to a particular user, in which case you create a new Opinion class and define the objects

@Entity
public class Opiniao implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long id;
    private String opiniao;

    @ManyToOne //para cada opinião você define o usuário responsável pela opinião
    private Usuario usuario;
....

User class

@Entity
public class Usuario implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long id;
    private String nome;
    ....

In this case the relation is a user can have several opinions.

This is just a summary, I advise you to research a little more, on JPA mapping, there are good content on the internet look this: jpa and good youtube lessons like that: video

  • Hello Edjane, thank you so much for your contribution. I wanted to attribute the attribute "opinion" in the relationship I have between User and Proposition. I’m seeing an example with the annotation @Associationoverride to map the relationship with this field more than the primary and foreign keys.

Browser other questions tagged

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