如何使用Hibernate Annotations,Struts 2和JSP获取外键

时间:2012-07-03 03:59:04

标签: hibernate jsp struts2 annotations pojo

我已经设法在MVC模式中使用Hibernate(Annotations)和Struts 2构建Web应用程序。我已经设置了JSP页面,其中表单将由用户填写,然后在我的Action类中进行处理,该类将调用DAO,为user表传递POJO。我还有一个填充states的表,我需要将ID表中的user设置为外键。我通过创建一个新的state POJO变量并在查询中使用来自我的jsp表单的state名称来从数据库中获取state信息来完成它。问题是我了解到我不能在动作类中使用查询语言(HQL),因为我会破坏MVC和Struts 2结构,这是正确的吗?如果是这样,如果DAO希望收到state POJO而不仅仅是state名称,我如何通过操作类发送state名称;

这是jsp表单:

   <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>

这是我的动作类,遵循struts 2配置:

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和SETs

这是我的POJO给用户:

@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 个答案:

答案 0 :(得分:0)

你需要的是一个转换器。一个xwork转换器。这就是你如何去做的。 假设你的状态对象是这个

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

现在这样做。在您的操作类中,将状态添加为属性

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

在您的jsp中添加myState,就像您通常一样

现在,创建一个名为xwork-conversion.properties的文件。将此文件放在WEB-INF下的classes目录中。此课程负责将您的state字符串转换为State对象

接下来,创建一个转换器类。这个班级将负责转换。

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 "";
}
}

完成此操作后。接下来要做的是编辑以前创建的xwork-conversion.properties。格式是键值,即class_name_to_convert = converter_class

full_package_name_of_your_state_class.State=full_package_name_of_your_converter_class.MyStrutsTypeConverter

之后部署您的应用程序。

如果您有任何问题,请告诉我

相关问题