Return of select objects (Combobox) with Hibernate + JSP + Vraptor. Does not fill relationship between tables

Asked

Viewed 1,966 times

1

I have an object TabelaPrecoItem with all the structure formed and almost everything working, follows the model of the model.

    @Entity
    @Table(name = "fov_tabela_preco_itens")
    public class TabelaPrecoItem implements Serializable {


    /**
     * 
     */
    private static final long serialVersionUID = 7517120126809692389L;

    @Id
    @GeneratedValue
    private int id;

    //    @Column(name = "tab_id")
    //    private Integer tab_id;

    //    @Column(name = "pro_id")
    //    private Integer id_produto;

    @Column(name = "tpi_preco")
    private Double preco;

    @Column(name = "tpi_minimo")
    private Double minimo;

    @Column(name = "tpi_maximo")
    private Double maximo;

    @NotNull(message = "Campo \"Tabela de Preço\" precisa ser informado.")
    @JoinColumn(name = "tab_id")
    @OneToOne(targetEntity = TabelaPreco.class)
    @NotFound(action = NotFoundAction.EXCEPTION)
    private TabelaPreco tabelaPreco;

    @NotNull(message = "Campo \"Produto\" precisa ser informado.")
    @JoinColumn(name = "pro_id")
    @OneToOne(targetEntity = Produto.class)
    @NotFound(action = NotFoundAction.EXCEPTION)
    private Produto produto;

Basically everything is working. The method of controler that selects is returning all objects correctly, I’m in trouble is when I try to edit this object.

I created the JSP as follows

<div id="msgErroModal" class="alert alert-danger fade"
    style="display: none;" aria-hidden="true"></div>
<form id="formCadastro" method="post"  accept-charset="UTF-8" class="smart-form" onsubmit='<c:if test="${acao != \"exibir\"}">submitForm("tabelaprecoitem", "formCadastro");</c:if> return false;' action="#">
    <fieldset>
        <section>
            <div class="inline-group">
            <div class="col col-3"></div>
            </div>
        </section>
            <section>
            <div class="row">
                <label class="label col col-3 text-right"><i class="fa fa-asterisk text-danger"></i> Tabela de Preço</label>
                <div class="col col-9">
                    <label class="select">
                        <select name="tabelaPrecoItem.tabelaPreco.id" required  disabled="disabled">
                            <option value="">Selecione uma Tabela</option>
                            <c:forEach var="tabela" items="${tabelaPrecoList}">
                                <option value="${tabela.id}" <c:if test="${tabela.id eq tabelaPrecoItem.tabelaPreco.id}">selected="selected"</c:if>>${tabela.descricao}</option>
                            </c:forEach>
                        </select >
                        <i class="fa fa-group"></i>
                    </label>
                </div>
            </div>
        </section>    

        <section>
            <div class="row">
                <label class="label col col-3 text-right">ID</label>
                <div class="col col-9">
                    <label class="input"><i></i>
                        <input type="text" value="${tabelaPrecoItem.id}" disabled="disabled">
                        <input type="hidden" name="tabelaPrecoItem.id" value="${tabelaPrecoItem.id}">
                    </label>
                </div>
            </div>
        </section>        
            <section>
            <div class="row">
                <label class="label col col-3 text-right"><i class="fa fa-asterisk text-danger"></i> Produto</label>
                <div class="col col-9">
                    <label class="select">
                        <select name="tabelaPrecoItem.produto.id" required  disabled="disabled">
                            <option value="">Selecione um Produto</option>
                            <c:forEach var="produto" items="${produtoList}">
                                <option value="${produto.id}" <c:if test="${produto.id eq tabelaPrecoItem.produto.id}">selected="selected"</c:if>>${produto.descricao}</option>
                            </c:forEach>
                        </select >
                        <i class="fa fa-group"></i>
                    </label>
                </div>
            </div>
        </section>    
        <section>
            <div class="row">
                <label class="label col col-3 text-right"><i class="fa fa-asterisk text-danger"></i> Preço</label>
                <div class="col col-9">
                    <label class="input">
                        <input type="number" step="0.01" placeholder="Ex: 20" name="tabelaPrecoItem.preco" value="${tabelaPrecoItem.preco}" required>
                    </label>
                </div>
            </div>
        </section>
        <section>
            <div class="row">
                <label class="label col col-3 text-right"><i class="fa fa-asterisk text-danger"></i> Mínimo</label>
                <div class="col col-9">
                    <label class="input">
                        <input type="number" step="0.01" placeholder="Ex: 20" name="tabelaPrecoItem.minimo" value="${tabelaPrecoItem.minimo}" >
                    </label>
                </div>
            </div>
        </section>
        <section>
            <div class="row">
                <label class="label col col-3 text-right"><i class="fa fa-asterisk text-danger"></i> Máximo</label>
                <div class="col col-9">
                    <label class="input">
                        <input type="number" step="0.01" placeholder="Ex: 20" name="tabelaPrecoItem.maximo" value="${tabelaPrecoItem.maximo}">
                    </label>
                </div>
            </div>
        </section>

    </fieldset>

    <footer>
        <div class="col-md-4 text-danger pull-left">
            <i class="fa fa-asterisk"> Campo(s) Obrigatório(s).</i>
        </div>
        <c:if test="${acao != \"exibir\"}">
            <button id="salvarModal" class="btn btn-sm btn-success" type="submit"><i class="fa fa-save"></i> Salvar</button>
        </c:if>
        <button id="fecharModal" type="button" class="btn btn-sm btn-danger" data-dismiss="modal"><i class="fa fa-times"></i> Fechar</button>
    </footer>
</form>

When I fill in the objects with the method

    @Get("/{id}/editarproduto")
    public void editar(Integer id) {
        TabelaPrecoItem TabelaPrecoItemAux = null;

        try {
            TabelaPrecoItemAux = this.repository.loadById(id);

        } catch (Exception e) {
            this.showErrorViewExceptionValidator(e,
                    "Falha ao carregar dados do Item da Tabela de Preços id " + id
                            + ", por favor tente novamente!", "TabelaPrecoItem");
        }

        this.result.include("acao", "editar").
        include("tabelaPrecoItem", TabelaPrecoItemAux).
        include("tabelaPrecoList",this.tabelaPrecoRepository.loadAll()).
        include("produtoList",this.produtoRepository.loadAll()).
        forwardTo(this).cadastroProduto();
    }

The screen is filled in correctly. But when I call the editing method, to save the changes in the database, the objects of tabelaPrecoItem.produto and tabelaPrecoItem.tabelaPreco are returning as null.

@Post("")
    public void salvar(TabelaPrecoItem tabelaPrecoItem) {
        String message = "";
        try {
            // Realiza a validaçãoo Server-Side
            this.validator.validate(tabelaPrecoItem);

            // Verifica erros e retorna para camada de visão, caso contrario
            // segue o fluxo normal de cadastro
            if (this.validator.getErrors().size() == 0) {

                if (tabelaPrecoItem.getId() == 0) {
                    tabelaPrecoItem = repository.add(tabelaPrecoItem);
                    message = "Novo Produto da Tabela de Preços id " + tabelaPrecoItem.getId()
                            + " cadastrado com sucesso!";

                } else {
                    tabelaPrecoItem = repository.update(tabelaPrecoItem);
                    message = "Produto da Tabela de Preços id " + tabelaPrecoItem.getId()
                            + " alterado com sucesso!";
                }
            }

        } catch (Exception e) {
            this.showErrorViewExceptionValidator(
                    e,
                    "Falha ao tentar salvar dados do Produto da Tabela de Preços, por favor tente novamente!",
                    "TabelaPreco");
        }

        // retorna o objeto de retorno fora do try catch para evitar exception
        // desnecessárias
        if (!message.equals("")) {
            result.use(Results.json()).withoutRoot().from(message).serialize();

        } else {
            this.returnErrorValidatorMessage();
        }
    }

And with that doesn’t pass in the validate.

2 answers

1

at the time of loading your entity it is not loading the related entities, you can achieve this by using "Cascade" which is an attribute of the relationship annotations as for example:

@Onetoone(Cascade=Cascadetype.ALL)

this causes any transaction in the entity to be reproduced in the related entities,

but you can limit this to a single operation with the other types of Cascade: PERSIST,MERGE,REMOVE, REFRESH

  • I put the note in the model @OneToOne(cascade=CascadeType.ALL,targetEntity = Produto.class) and @OneToOne(cascade=CascadeType.ALL,targetEntity = TabelaPreco.class) even so in the return of the JSP object to the class it is still coming as null "tabelaPrecoItem" (pending) &#xA; id 1 &#xA; maximo Double (id=133) &#xA; minimo Double (id=137) &#xA; preco Double (id=138) &#xA; produto null &#xA; tabelaPreco null &#xA; I think the JSP selects (Combobox) are not filling the objects. There may be some error in their name ?

0

The comboBox on the screen was like Disabled, for this reason the Vraptor does not identify the object. To solve it I enabled the combobox before post and disabled again after post.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.