mapping entities with jpa?

0

I'm new to jpa, what I've been trying is to map a table of my DB of the user table which is divided into 2 types, which are natural and legal users but legal persons have data of ruc and organization to which belongs

public class Usuario implements Serializable {

    @Id
    @Column(name = "id_usuario")
    private int id_usuario;

    private String nombre;

    private String apellido;

    @Column(name = "dni", length = 8)
    private int dni;

    @Column(name = "user_name")
    private String user_name;

    @Column(name = "Clave")
    private String Clave;

    @Column(name = "Correo_Electronico", insertable = false)
    private String Correo_Electronico;

    @Column(name = "telefono", insertable = false)
    private String Telefono;

    @Column(name = "ruc", insertable = false, length = 11)
    private int ruc;

    @Column(name = "organizacion", insertable = false)
    private String Organizacion;

    @ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST,
            CascadeType.MERGE, CascadeType.REMOVE, CascadeType.DETACH })
    @JoinColumn(name = "persona_id_tipo_persona")
    private Tipo_Persona tipoPersona;
.
.
.
}

I would like to know if it could be done in another way, because I see that it is not optimized since when entering the users I will have to see the theme of the ruc and create an object with that attribute. in advance thank you

    
asked by Ventur 05.04.2017 в 21:13
source

1 answer

2

You should make a simple inheritance. Contarias with 3 classes:

  • TipoPersona : Contain all data shared between users.
  • UsuariosNaturales : You will not have extra attributes since you will inherit them
  • UsuariosJuridicos : It has the corresponding extra attributes

Both Users would inherit from TipoPersona in the following way:

@MappedSuperclass
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
 public class TipoPersona implements Serializable{
    @Id
    @Column(name = "id_usuario")
    private int id_usuario;

    private String nombre;

    private String apellido;

    @Column(name = "dni", length = 8)
    private int dni;

    @Column(name = "user_name")
    private String user_name;

    @Column(name = "Clave")
    private String Clave;

    @Column(name = "Correo_Electronico", insertable = false)
    private String Correo_Electronico;

    @Column(name = "telefono", insertable = false)
    private String Telefono;
 }


@Entity
@Table(name="Usuarios_Naturales")
public class UsuariosNaturales extends TipoPersona {

}

@Entity
@Table(name="Usuarios_Juridicos")
public class UsuariosJuridicos extends TipoPersona {
    @Column(name = "ruc", insertable = false, length = 11)
    private int ruc;

    @Column(name = "organizacion", insertable = false)
    private String Organizacion;
}

The result is 2 tables: Usuarios_Naturales and Usuarios_Juridicos with unique id sharing the necessary attributes.

I hope it's useful!

    
answered by 06.04.2017 в 08:12