Modeling Spring JPA Person - PersonFisica - Official

0

I did the data modeling (UML) but at the time of implementation I'm doubtful how to do it.

I wanted you to have only one Person table.

In this person table I would have the field tipoPessoa("p","f") and the fields if the person is client, barber, attendant, vendor, manufacturer, etc.

I wanted to do this implementation in Spring JPA that I saw that is very easy to use.

Here's basically how I want the table to be in the database:

HereishowIwantittobeinjava:

Iknowthatthisrelationshipbetweenpeopleandtypescouldbemanytomanygeneratingonemoretable,butforthisprojectIwanttodoitanyway.

ThequestionishowdoImakeSpringunderstandthatIwanteverythingtobeinthesametablewithExfields:pess.forn="f", "t"

    
asked by anonymous 16.07.2018 / 06:03

2 answers

2

You can use the Single Table JOIN strategy, where Hibernate creates a single table for each hierarchy. This is also the default strategy chosen by JPA if you do not explicitly specify one.

For didactic effect, I will show an example set this strategy explicitly:

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="tipoPessoa", 
    discriminatorType = DiscriminatorType.STRING)
public class Pessoa {
    @Id
    private long idPessoa;
    private String contato;
    // demais campos
}

Above I created a Pessoa table and said that to differentiate between different people (legal and physical) I will use the tipoPessoa field. The information that goes in tipoPessoa is defined in child classes by the @DiscriminatorValue annotation. See below:

@Entity
@DiscriminatorValue("pf")
public class PessoaFisica extends Pessoa {
    private String cpf;
    // demais campos
}

@Entity
@DiscriminatorValue("pj")
public class PessoaJuridica extends Pessoa {
    private String cnpj;
    // demais campos
}

@Entity
@DiscriminatorValue("cliente")
public class Cliente extends PessoaFisica {
    // demais campos do cliente
}
    
16.07.2018 / 13:32
-1

You can create a pess table as follows:

create table pess(
id NUMBER not null,
email              VARCHAR2(100),
forn VARCHAR2(1) default 'f')

NOTE: The above script has ORACLE as an example.

The Person class:

public class Person{
 private Long id;
 private String email;
 private String forn;
}

When you make the inserts you apply your logic to insert only values of type 'f' or 'j'. You can use flyway to read your sql scripts. If you do not know the flaway, I recommend you to search. It will give you a freedom to create your tables.

    
16.07.2018 / 12:38