How to create a relationship using JPA that contains attributes?

3
Hello, I'm working on a Java Web project with Hibernate, Postgres, Glassfish, and use JPA / JSF. 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 created a relationship with the Proposition entity, generating a relationship table, but I have no control over it. All in done via hibernate by annotation.

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

I see that it seems that I need to redo the relationships, as I will need to create an entity class for this relationship, manually shaping to my need. Can anyone confirm if I'm on the right track?

Thank you!

    
asked by anonymous 07.07.2018 / 23:53

1 answer

0

Yes, that's the way.

You have a UserEntity class right? One tip, user is already an entity, and you will persist the objects of this class in a database, for the name of your classes get leaner 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 given 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 relationship is a user can have several opinions.

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

    
09.07.2018 / 13:06