How to get the value bound to a selectOneRadio and assign it to an attribute in a Bean

4

I want to implement a method / way to get the value bound to a selectOneRadio (which is an Enum) and assign it to an attribute inside a Bean.

After getting the value bound to selectOneRadio, I will pass it as a parameter to a method called newPessoa and thus instantiate an attribute of type Person located in a Client class.

I am studying and developing a Java EE application using JSF, PrimeFaces and JPA. The main focus of learning is the use of Inheritance with JPA (hence the Java inheritance) as well as Composition. I chose to use the inheritance strategy JOINED, because I understand that in this way the database tables become more standardized. Faced with this, I implemented 4 classes:

Person (abstract) Person (inherits from Person) PersonJuridica (inherited from Pessoa) Client (has an attribute of Person, since it can be either PersonPass or PersonJuridica)

At first I defined in the Person class an attribute typePattern, which is an enum composed of FISICA and JURIDICA, where the idea is: to bind the values of this enum to a "p: selectOneRadio" so that depending on the type that is selected or LEGAL) to instantiate the Person object as Physical Person or Legal Person.

For this, I also implemented a class (using Design Patterns of FactoryFactory Creation) PessoaFactoty. This class has the method newPessoa that receives as parameter a PersonType and depending on the type (PHYSICAL or LEGAL) a type of person is instantiated.

Below is the image of a class diagram to demonstrate the relationship scenario between classes. Below are also the codes for class implementation.

PS: After completing this part of the implementation, I want to develop a way so that once the page is re-indexed, the PHYSICS option is already selected, this type will be the default type, and there will also be a form for each type of person, if PHYSICS is selected, there will be fields of CPF, RG, etc., if it is LEGAL, there will be the fields CNPJ, Insc. State, etc., ie the form will be dynamic.

Thank you in advance.

Person

@Entity@Table(name="PESSOAS")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "PESS_TIPO")
public abstract class Pessoa implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "PESS_CODIGO", nullable = false)
private Integer codigo;

@Enumerated(EnumType.STRING)
@Column(name = "PESS_TIPO_DE_PESSOA")
private PessoaType tipoDePessoa;

@Column(name = "PESS_NOME", length = 100, nullable = false)
private String nome;

@Column(name = "PESS_FONE", length = 20, nullable = false)
private String telefone;

@OneToOne(mappedBy = "pessoa")
private Endereco endereco;

@Column(name = "PESS_OBSERVACAO", length = 255, nullable = true)
private String observacao;

@Column(name = "PESS_STATUS", length = 1, nullable = false)
private Boolean status;

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "PESS_DATA_CADASTRO", nullable = false)
private Date dataCadastro;

@Version
@Column(name = "PESS_DATA_ALTERACAO", nullable = false)
private Timestamp dataAlteracao;

protected Pessoa() {

}
// Gets e Sets

Individuals

@Entity
@Table(name = "PESSOA_FISICA")
@DiscriminatorValue(value = "PF")
@PrimaryKeyJoinColumn(name = "PESS_CODIGO")
public class PessoaFisica extends Pessoa implements Serializable {

private static final long serialVersionUID = 1L;

@Column(name = "PESF_CPF", length = 14, nullable = false)
private String cpf;

@Column(name = "PESF_RG", length = 14, nullable = false)
private String rg;

@Column(name = "PESF_ORGAO_EMISSOR_RG", length = 20, nullable = false)
private String orgaoEmissorRg;

@Column(name = "PESF_EMAIL", length = 65, nullable = true)
private String email;

@Column(name = "PESF_CELULAR", length = 14, nullable = true)
private String celular;

@Lob
@Column(name = "PESF_FOTO", nullable = true)
private byte[] foto;

@Temporal(TemporalType.DATE)
@Column(name = "PESF_DATA_NASCIMENTO", nullable = false)
private Date dataNascimento;

@Enumerated(EnumType.STRING)
@Column(name = "PESF_SEXO", nullable = false)
private SexoType sexo;

@OneToMany(mappedBy = "cliente")
private List<PedidoVenda> pedidos;

public PessoaFisica() {

}

Legal entity

@Entity
@Table(name = "PESSOA_JURIDICA")
@DiscriminatorValue(value = "PJ")
@PrimaryKeyJoinColumn(name = "PESS_CODIGO")
public class PessoaJuridica extends Pessoa implements Serializable {

private static final long serialVersionUID = 1L;

@Column(name = "PESJ_NOME_FANTASIA", length = 100, nullable = false)
private String nomeFantasia;

@Column(name = "PESJ_CNPJ", length = 14, nullable = false)
private String cnpj;

@Column(name = "PESJ_INSCRICAO_ESTADUAL", length = 15, nullable = false)
private String inscricaoEstadual;

@Temporal(TemporalType.DATE)
@Column(name = "PESJ_VALIDADE_INSCRICAO_ESTADUAL", nullable = false)
private Date validadeInscricaoEstadual;

@Column(name = "PESJ_INSCRICAO_MUNICIPAL", length = 15, nullable = true)
private String inscricaoMunicipal;

@Column(name = "PESJ_HOME_PAGE", length = 100, nullable = true)
private String homePage;

@Column(name = "PESJ_FAX", length = 15, nullable = true)
private String fax;

public PessoaJuridica() {

}

Factory class to instantiate a person according to the type passed by parameter.

public class PessoaFactory {
public static Pessoa newPessoa(PessoaType tipo) {
    if (tipo == PessoaType.FISICA) {
        return new PessoaFisica();
    } else if (tipo == PessoaType.JURIDICA) {
        return new PessoaJuridica();
    } else {
        return null;
    }
}
}

Bean

@Named(value = "clienteBean")
@SessionScoped
public class ClienteBean extends Bean {

private static final long serialVersionUID = 1L;

@Inject
private ClienteService clienteService;

private Cliente cliente;

private Pessoa pessoa;

private Cliente clienteSelecionado;

private List<Cliente> clientes;

public void instanciarPessoa(ValueChangeEvent event) {

    HtmlSelectOneRadio radio = (HtmlSelectOneRadio) event.getComponent();
    PessoaType tipo = (PessoaType) radio.getValue();

    System.out.println(tipo);
}

public List<PessoaType> getTiposDePessoa() {
    return Arrays.asList(PessoaType.values());
}

public List<Cliente> getClientes() {
    try {
        if (clientes == null) {
            clientes = clienteService.listarTodosClientes();
        }
        return clientes;
    } catch (Exception e) {
        handleException(e);
        return null;
    }
}

public String novoCliente() {
    cliente = new Cliente();
    return redirect(Outcome.CADASTRO_CLIENTE);
}
}

Part of the XHTML file

<h:panelGrid columns="3">
    <h:outputLabel value="Tipo de Pessoa" for="tipoPessoa" />
        <p:selectOneRadio 
            id="tipoPessoa" 
            value="#{clienteBean.pessoa.tipoDePessoa}" 
            valueChangeListener="#{clienteBean.instanciarPessoa}">
            <f:selectItems 
                value="#{clienteBean.tiposDePessoa}" 
                var="tipoDePessoa" 
                itemValue="tipoDePessoa"
                itemLabel="#{tipoDePessoa.descricao}">
            </f:selectItems>
        </p:selectOneRadio>
</h:panelGrid>
    
asked by anonymous 13.09.2015 / 04:53

1 answer

1

Assuming that you already have your ManagerBean to control the registration system, I assume that the name of your Bean is PersonNameBean, in it you should have a get method as follows:

 //
 private Pessoa pessoa;
 //Pega o tipo de pessoa que foi selecionada
 public Pessoa getPessoa() {
    return pessoa;
 }
 //Pega os valores de pessoas para exibir na página
 public TipoPessoa[] getTiposPessoas() {
    return TipoPessoa.values();
 }

On the registration page you should reference the method as below.

        <p:panelGrid columns="2" id="grid">
            <p:outputLabel value="Tipo" for="tipo" />
            <p:selectOneRadio id="tipo" 
                    value="#{CadastroPessoaBean.pessoa.tipoDePessoa}">
                    <f:selectItems value="#CadastroPessoaBean.tiposPessoas}"
                    var="tipoPessoa" itemValue="#{tipoPessoa}" 
                    itemLabel="#{tipoPessoa.descricao}" />
            </p:selectOneRadio>
        </p:panelGrid>

Enum:

public enum TipoPessoa {

  FISICA("Fisica"), 
  JURIDICA("Juridica");

  private String descricao;

  TipoPessoa(String descricao) {
      this.descricao = descricao;
  }

  public String getDescricao() {
      return descricao;
  }
}

Editing ...

Now that you've got the value, you should pass it to your Factory Method.

Something like this ...

public abstract class PessoaFactory{

    protected abstract TipoPessoaInterface newPessoa();
//Aqui vai criar o tipo de pessoa
    public void criacao(Pessoa tipo) {
        newPessoa().criar(tipo);
    }
}

Inteface of your FactoryMethod

public interface TipoPessoaInterface {
    public Pessoa criar(Pessoa tipo);
}

Since you are using FactoryMethod you have to have the classes that will be responsible for creating the object. Then you get this object created in the Client class to finish your registration.

    
13.09.2015 / 06:59