如何使用 Hibernate Annotations、Struts 2 和 JSP 获取外键 [英] How to get foreign keys, using Hibernate Annotations, Struts 2 and JSP

查看:17
本文介绍了如何使用 Hibernate Annotations、Struts 2 和 JSP 获取外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

这是 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 配置:

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

//GET 和 SET

//GETs and SETs

这是我给用户的 POJO:

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

推荐答案

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

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
}

在你的 jsp 中添加 myState 就像你通常会做的那样

in your jsp add myState like you will usually do

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

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

一旦你完成了这个.接下来要做的是编辑之前创建的 xwork-conversion.properties.格式是键值,即 class_name_to_convert=converter_class

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

这篇关于如何使用 Hibernate Annotations、Struts 2 和 JSP 获取外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆