How to get foreign keys, using Hibernate Annotations, Struts 2 and JSP

偶尔善良 提交于 2019-12-18 09:38:14

问题


I have managed to build a web application using Hibernate (Annotations) and Struts 2 in an MVC pattern. I have set the JSP page where a form is to be filled out by the user, then it gets processed in my Action class, which will call the DAO, passing a POJO, for the user table. I also have a table filled with states and I need to set its ID in the user table as a foreign key. I have done it by creating a variable that is a new state POJO and using the state name that comes from my jsp form in a query to get the state information from the database. The problem is that I learnt that i cannot use query language (HQL) in the action class as I would be breaking the MVC and Struts 2 structure, is it correct? If so, how can i send the state name through the action class if the DAO expects to receive a state POJO, not just the state name;

Here´s the jsp form:

   <s:form action="cadVoluntario" method="post">
        <s:textfield name="dtCadastro" label="Data de Cadastro"/>
        <s:textfield name="nomeCivil" label="Nome Civil"/>
        <s:textfield name="nomeSocial" label="Nome Social"/>
        <s:textfield name="cpf" label="CPF"/>
        <s:textfield name="rg" label="RG"/>
        <s:textfield name="orgExp" label="Órgão Expedidor"/>
        <s:textfield name="dtNascimento" label="Data de Nascimento"/>
        <s:textfield name="celular" label="Celular"/>
        <s:textfield name="telComercial" label="Telefone Comercial"/>
        <s:textfield name="telResidencial" label="Telefone Residencial"/>
        <s:textfield name="endereco" label="Endereço"/>
        <s:textfield name="bairro" label="Bairro"/>
        <s:textfield name="cidade" label="Cidade"/>
        <s:textfield name="estado" label="Estado"/>
        <s:submit/>
    </s:form>

here´s my action class, following struts 2 configuration:

public class CadVoluntarioAction {

private String dtCadastro;
private String nomeCivil;
private String nomeSocial;
private String cpf;
private String rg;
private String orgExp;
private String dtNascimento;
private String celular;
private String telComercial;
private String telResidencial;
private String endereco;
private String bairro;
private String cidade;
private String estado;

    public String add() throws Exception {

        VoluntarioPojo pojoVol = new VoluntarioPojo();
        CadVoluntarioDAO daoVol = new CadVoluntarioDAO();

        pojoVol.setDtCadastro(getDtCadastro());
        pojoVol.setNomeCivil(getNomeCivil());
        pojoVol.setNomeSocial(getNomeSocial());
        pojoVol.setCpf(getCpf());
        pojoVol.setRg(getRg());
        pojoVol.setOrgExp(getOrgExp());
        pojoVol.setDtNascimento(getDtNascimento());
        pojoVol.setCelular(getCelular());
        pojoVol.setTelComercial(getTelComercial());
        pojoVol.setTelResidencial(getTelResidencial());
        pojoVol.setEndereco(getEndereco());
        pojoVol.setBairro(getBairro());
        pojoVol.setCidade(getCidade());
        pojoVol.setEstadoPojo(getEstado());

        try {
            daoVol.salvarVoluntario(pojoVol);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "sucesso";
    }

//GETs and SETs

here's my POJO for the user:

@Entity
@Table (name="voluntario")
@Inheritance(strategy = InheritanceType.JOINED)

public class VoluntarioPojo implements Serializable{   
    private Long idVoluntario;
    private String dtCadastro;
    private String cpf;
    private String rg;
    private String orgExp;
    private String nomeCivil;
    private String nomeSocial;
    private String dtNascimento;
    private String areaAtuacao;
    private String celular;
    private String telResidencial;
    private String telComercial;
    private String endereco;
    private String cidade;
    private String bairro;
    private String cep;
    private String email;
    private String senha;
    private String perfil;
    private EstadoPojo estadoPojo;
    private IdentidadeGeneroPojo identidadeGeneroPojo;
    private OrientacaoSexualPojo orientacaoSexualPojo;

    public VoluntarioPojo () 
    {
    }

    @Id
    @SequenceGenerator(name="vol_seq", sequenceName="voluntario_volid_seq")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "vol_seq")
    @Column(updatable = true, name = "volid", nullable = false)
    public Long getIdVoluntario() {
        return idVoluntario;
    }
    public void setIdVoluntario(Long idVoluntario) {

        this.idVoluntario = idVoluntario;
    }

    @ManyToOne 
    @JoinColumn(name = "estadosestid")
    public EstadoPojo getEstadoPojo ()
    {   
        return this.estadoPojo;
    }
    public void setEstadoPojo (EstadoPojo estadoPojo)
    {
        this.estadoPojo = estadoPojo;
    }

    @ManyToOne 
    @JoinColumn(name ="orisexualoriid")
    public OrientacaoSexualPojo getOrientacaoSexualPojo()
    {   
        return this.orientacaoSexualPojo;
    }
    public void setOrientacaoSexualPojo(OrientacaoSexualPojo orientacaoSexualPojo)
    {
        this.orientacaoSexualPojo = orientacaoSexualPojo;
    }

    @ManyToOne
    @JoinColumn(name ="idegeneroideid")
    public IdentidadeGeneroPojo getIdentidadeGeneroPojo()
    {   
        return this.identidadeGeneroPojo;
    }
    public void setIdentidadeGeneroPojo (IdentidadeGeneroPojo identidadeGeneroPojo)
    {
        this.identidadeGeneroPojo = identidadeGeneroPojo;
    }

    @Column(updatable = true, name = "volcpf", nullable = false, length = 11)
    public String getCpf() {
        return this.cpf;
    }
    public void setCpf(String cpf) {
        this.cpf = cpf;
    }

//All the other required Colunms...

回答1:


what you need is a converter. An xwork converter. This is how you go about it. Let's say that your state object is this

public class State implements Serializable
{
     private String stateName;
     private Long stateId;
     //getters and setters
}

Now do this. In your action class, add state as a property

public class CadVoluntarioAction extends ActionSupport{
     private State myState;
     //getters and setters
}

in your jsp add myState like you will usually do

Now, create a file called xwork-conversion.properties. Put this file in your classes directory under WEB-INF. This class will be responsible for converting your state string to State Object

Next, create a converter class. this class will be responsible for doing the conversion.

public abstract class MyStrutsTypeConverter extends StrutsTypeConverter
{
    public Object convertFromString(Map map, String strings[], Class type)
    {
        String value = strings[0];
        if(value != null && value.equals("state_string_from_jsp"))
        {
          //Use your dao to retrieve your state object and return the state object
        }
        return null;
    }

public String convertToString(Map map, Object o)
{
        if(o instanceof State)
        {
            State data = (State)o;
            //return the  state string
        }
        return "";
}
}

Once you are done with this. The next thing to do is to edit the previously created xwork-conversion.properties. The format is a key-value i.e. the class_name_to_convert=converter_class

full_package_name_of_your_state_class.State=full_package_name_of_your_converter_class.MyStrutsTypeConverter

After that deploy your application.

Let me know if you have any issues



来源:https://stackoverflow.com/questions/11304255/how-to-get-foreign-keys-using-hibernate-annotations-struts-2-and-jsp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!