Send by jsp a command for the controller to update the database method

Asked

Viewed 194 times

0

I want to make a "deposit" into the account with Id "x". The controller sends the "account" to the jsp that returns the deposit value to be updated in the database. That was the logic I used, but I think I was wrong about something, I believe in JSP or Controller. Because by clicking on "deposit" goes to the next page as if everything had happened well but the BD is not updated. What logic should I have used?

Edit 1: At the beginning was occurring the error "Detached Entity passed to persist: br.com.bitbank.modelo.Client" using "persist". I searched a little and even though the "find" returns an Entity "maneged" the error continued, so I changed the command to "merge". There is no more error in the console, but the table "Account" wins another registration all "NULL".

+----+---------+--------+-------+
| id | agencia | numero | saldo |
+----+---------+--------+-------+
|  1 |      10 |   4645 |     0 | Cadastro normal
|  2 |    NULL |   NULL |     0 | Após tentar "depositar"

The link to my complete project: https://github.com/BryanMotta/FormacaoJava/tree/master/src/main/java/br/com/bitbank

The parts I’m modifying:

@Controller
@RequestMapping("/transacao")

public class TransacaoController {

@Autowired
private ClienteDAO clienteDAO;

@RequestMapping(method = RequestMethod.GET, value = "/deposita/{id}")
public ModelAndView form(@PathVariable("id") int id) {
    ModelAndView modelAndView = new ModelAndView("transacao/transacao");

    Cliente cliente = clienteDAO.find(id);
    modelAndView.addObject("cliente", cliente);
    return modelAndView;
}

@RequestMapping(method = RequestMethod.POST, value = "/deposita/{id}")
public ModelAndView deposita(@PathVariable("id") int id, Cliente cliente) {
    ModelAndView modelAndView = new ModelAndView("redirect:/");

    //Cliente cliente = clienteDAO.find(id);
    clienteDAO.atualiza(cliente);
    modelAndView.addObject("cliente", cliente);
    return modelAndView;
}

Jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
  <form:form action="${s:mvcUrl('TC#deposita').arg(0,cliente.id).build() }" 
     method="post"
    modelAttribute="cliente">
    <div>
    <input type="number" name="conta.deposita" />        
    <button type="submit">Depositar</button>
    </div>
</form:form>
</body>
</html>

DAO

@Repository
@Transactional
public class ClienteDAO {

@PersistenceContext
private EntityManager manager;

public void gravar(Cliente cliente) {
    manager.persist(cliente);
}
public void atualiza(Cliente cliente) {
    manager.merge(cliente);
}

public Cliente getProduto(Integer id) {
    Cliente cliente = manager.find(Cliente.class, id);
    return cliente;
}
public List<Cliente> listar() {
    return manager.createQuery("select c from Cliente c", Cliente.class)
            .getResultList();
}

public Cliente find(int id) {
    return manager.find(Cliente.class, id);
}
  • gives some Exception?

  • Yes, using "persist" from the error "Detached Entity passed to persist: br.com.bitbank.modelo.Client", and using "merge" does not occur any in the console, but the table account gains a whole "NULL" registration. I will add this information in the main question.

  • and its intention is to actually insert a new state or just update the original?

  • Update the original. When I register a new customer automatically his balance is set to 0, the deposit method would add a value to the balance.

  • I get it, is that persist and merge do not serve for this, you commented there that when recovers by find by id the object comes Managed right? then it would just be changing the information of that object and give a commit, maybe even the commit need if that Transactional is working

  • I think I get it, I don’t need to use persist and merge in my controller. But how do I make the logic? It’s done in jsp or controller?

Show 1 more comment

1 answer

0


I simplified my jsp form a little bit and sent the client id to be modified along with the value to be deposited

<form:form action="${s:mvcUrl('TC#deposita').arg(0,cliente.id).build() }" 
method="post"
        modelAttribute="cliente">
        <div>
            Nome:${cliente.titular.nome} Id:${cliente.conta.id}
            <input type="number" name="deposita" />
            <form:hidden path="id" value="${cliente.id}"/>  
        </div>
        <button type="submit">Depositar</button>
    </form:form>

And in my controller I started using Webrequest to get the parameters passed by the jsp thus staying

@RequestMapping(method = RequestMethod.POST, value = "/deposita/{id}") 
  public ModelAndView deposita(@PathVariable("id") int id, WebRequest request) {
    ModelAndView modelAndView = new ModelAndView("redirect:/");

    //pega o id enviado pelo form e da um find no cliente
    Cliente cliente =clienteDAO.find(Integer.parseInt(request.getParameter("id")));
    //pega o valor do deposisto enviado pelo form e chama o metodo da classe passadno 
    //esse valor 

   cliente.getConta().deposita(Double.parseDouble(request.getParameter("deposita")));
        //atualiza esse valor utilizando o merge
    clienteDAO.atualizar(cliente);      

    //modelAndView.addObject("cliente", cliente);
    return modelAndView;
}

And regarding Merge I used this answer as an explanation

"Using the merge Basically, merge() takes an object created outside of JPA, either directly in its code or in some automatic process such as a JSON deserializer or a MVC framework that maps the request to a Java Bean.

Upon receiving this object, JPA checks whether an instance already exists in the context or retrieves one from the database.

Then it takes the values of the instance you passed and assigns it to the instance of the persistence context, effectively updating the data of the true entity. Note that it will update all attributes and not only those that have value.

Then the merge() method returns to you the updated entity. At this point, the object you passed to it can be discarded."

source:/a/60035/152788

Browser other questions tagged

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