Instantiate annotated class with Hibernate inheritance using CDI

2

Good afternoon,

I am creating a project using JSF , CDI , Bootstrap and Hibernate .

I would like to know how to work with the following problem, I created a set of classes to represent a person entity física or jurídica . The structure is as follows:

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="tipo", discriminatorType=DiscriminatorType.STRING, length=1)
@Named("clientePojo")
public abstract class Cliente extends Persistent {

    public enum TipoCliente {

        FISICA('F', "Física"), 
        JURIDICA('J', "Juridica");

        private final char tipo;
        private final String descricao;

        private TipoCliente(char tipo, String descricao) {
            this.tipo = tipo;
            this.descricao = descricao;
        }

        public static TipoCliente valueOf(char sigla) {

            switch (sigla) {
            case 'F':
                return TipoCliente.FISICA;
            case 'J':
                return TipoCliente.JURIDICA;
            default:
                return null;
            }
        }

        public char getTipo() {
            return tipo;
        }

        public String getDescricao() {
            return descricao;
        }
    }

    @Column(insertable=false, updatable=false)
    private String tipo;

    // getter e setter  
}

@Entity
@DiscriminatorValue(value="F")
public class ClienteFisico extends Cliente {

    private String nome;

    private Date dataNascimento;

    private String identidade;

    private String cpf;

    // getter e setter
}

@Entity
@DiscriminatorValue(value="J")
public class ClienteJuridico extends Cliente {

    private String razaoSocial;
    private String nomeFantasia;
    private String cnpj;

    // getter e setter
}

How should I handle this case to instantiate in bean ? Since the registration form you select if the type is physical or legal.

    
asked by anonymous 30.03.2016 / 18:16

1 answer

2

Retrieve if the type of person to be registered by the form is Physical or Legal and instantiate an object of the type you wish.

Ex:

if (TipoCliente.FISICO == form.getTipoPessoaValue()) {
   ClienteFisico cliente = new ClienteFisico();
   // insira seus setters aqui
}

You can instantiate an object from a child class, and even then, set attributes that are represented by the superclass (as in the case of Client and Physical Client).

Note: It is recommended that you do not manipulate entity data directly. To do this, use the Data Transfer Objects or DTO's. You would have something like "ClientDTO" and etc.

    
04.04.2016 / 05:47