Java Question

Send object in JSP as foreign key using Spring MVC and Hibernate

I want to create a bank account register related to a specific Person in a OneToMany relationship.

I have the clas Pessoa (Person):

@Entity
public class Pessoa {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private int idPessoa;
private String nome;
@OneToMany(mappedBy = "pessoa", targetEntity = ContaCorretora.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<ContaCorretora> contaCorretora;


...and the class ContaCorretora (Bank account):

@Entity
public class ContaCorretora {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private int idConta;
private TipoConta tipoConta;
private TipoRisco tipoRisco;
private String login;
private String senha;
private BigDecimal valorAtual;
@ManyToOne
@JoinColumn(name="idPessoa")
private Pessoa pessoa;


I'm using this method in Controller for start the process of registration:

@RequestMapping(value = "pessoacorretora/{id}")
public ModelAndView pessoaCorretora(@PathVariable("id") int id, ContaCorretora contaCorretora ) {
Map<String, Object> model = new HashMap<String, Object>();
Pessoa pessoa = pessoaDao.find(id);
model.put("pessoa", pessoa);
model.put("tipoConta", TipoConta.values());
model.put("tipoRisco", TipoRisco.values());
return new ModelAndView("corretora/contacorretora", "model", model);
}


Sumarizining, I have a specific page for recording bank accounts. So, I created this form:

<form:form action="${s:mvcUrl('CC#gravar').build() }" method="post" commandName="contaCorretora" enctype="multipart/form-data" >

<div class="form-group" >
<label>Conta</label>
<select name="tipoConta">
<c:forEach items="${model.tipoConta}" var="tipoConta">
<option value=${tipoConta}>${tipoConta}</option>
</c:forEach>
</select>
</div>

<div class="form-group" >
<label>Risco</label>
<select name="tipoRisco">
<c:forEach items="${model.tipoRisco}" var="tipoRisco">
<option value=${tipoRisco}>${tipoRisco}</option>
</c:forEach>
</select>
</div>

<div class="form-group">
<label>Login</label>
<form:input path="login" cssClass="form-control" />

</div>

<div class="form-group">
<label>Senha</label>
<form:input path="senha" cssClass="form-control" />

</div>

<div class="form-group">
<label>Valor Atual</label>
<form:input path="valorAtual" cssClass="form-control" />

</div>
<form:hidden path="pessoa" cssClass="form-control" value="${pessoa}"/>

<button type="submit" class="btn btn-primary">Cadastrar</button>
</form:form>


When I use the form in this way, I receive the error "description The request sent by the client was syntactically incorrect." I figured out that the problem is in this line, because when I delete, the form post ok:

<form:hidden path="pessoa" cssClass="form-control" value="${pessoa}"/>


Nevertheless, if I delete this line, the program doesn't save the idPessoa as a foreign key, this field is null. I would like to know how to pass an entire object in my JSP form. The post method is:

@RequestMapping(method=RequestMethod.POST)
public ModelAndView gravar(ContaCorretora contaCorretora) {
contaCorretoraDao.gravar(contaCorretora);
return new ModelAndView("pessoa/listageral");
}


all the DAO's methods are okay.

Answer Source

You only need to send the primary key of pessoa to the form. Change the form attribute

<form:hidden path="pessoa.idPessoa" cssClass="form-control" value="${model.pessoa.idPessoa}"/>

Before persisting the ContaCorretora, make sure you get the Pessoa object from db.

@RequestMapping(method=RequestMethod.POST) 
public ModelAndView gravar(ContaCorretora contaCorretora)   { 

    contaCorretora.setPessoa(pessoaDao.find(contaCorretora.getPessoa().getIdPessoa()));
    //I escaped  null check and not found exceptions, you should apply some logic to take care of that
    contaCorretoraDao.gravar(contaCorretora);
    return new ModelAndView("pessoa/listageral"); 
}

Using Entities as form model is not a good approach. Persistance layer should not be on the MVC layer.