How to create a relationship using JPA that contains attributes?

Question:

Hi, I'm working on a Java Web project with Hibernate, Postgres, Glassfish, and I'm using 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 code above in the User entity, I created a relationship with the Proposition entity, generating a relationship table, but I have no control over this one. All in done via hibernate by annotation.

And now I need to create an extra field in this relationship, an "Opinion" attribute of type String and I don't know how to do that with JPA.

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

Appreciate!

Answer:

Yes, this is the way.

You have a UsuarioEntity class right? A tip, user is already an entity, and you will persist the objects of that class in a database, for the name of your classes to be more streamlined there is no need to put Entity in front of your class name, just define it 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;
....

Usuario 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 research a little more, about JPA mapping, there is good content on the internet look at this: jpa and good classes on youtube like this: video

Scroll to Top
AllEscort