I have a problem when I click on update a window appears and there I update the data but instead of updating it creates another record I don't know why, I leave the code below:
Model
user class
@Entity public class User extends AbstractPersistable {
private transient Long id;
private String usuarioId;
private String usuarioNombre;
private String clave;
@ManyToOne
@JoinColumn(name="rol_id")
private Rol rol;
@OneToMany(targetEntity=Direccion.class, mappedBy="usuario", fetch=FetchType.LAZY,cascade=CascadeType.ALL)
private Set<Direccion> direcciones;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsuarioId() {
return usuarioId;
}
public void setUsuarioId(String usuarioId) {
this.usuarioId = usuarioId;
}
public String getUsuarioNombre() {
return usuarioNombre;
}
public void setUsuarioNombre(String usuarioNombre) {
this.usuarioNombre = usuarioNombre;
}
public String getClave() {
return clave;
}
public void setClave(String clave) {
this.clave = clave;
}
public Rol getRol() {
return rol;
}
public void setRol(Rol rol) {
this.rol = rol;
}
en la clase direccion
@Entity public class Address extends AbstractPersistable{
private String ciudad;
private String distrito;
private String pais;
private transient Long usuarioId;
@ManyToOne
@JoinColumn(name="usuario_id")
private Usuario usuario;
public Long getUsuarioId() {
return usuarioId;
}
public void setUsuarioId(Long usuarioId) {
this.usuarioId = usuarioId;
}
public String getCiudad() {
return ciudad;
}
public void setCiudad(String ciudad) {
this.ciudad = ciudad;
}
public String getDistrito() {
return distrito;
}
public void setDistrito(String distrito) {
this.distrito = distrito;
}
public String getPais() {
return pais;
}
public void setPais(String pais) {
this.pais = pais;
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
Controller
@RequestMapping("/direccion")
@Controller
@EnableGlobalMethodSecurity(prePostEnabled=true,securedEnabled = true,
jsr250Enabled = true)
public class DireccionController {
private DireccionService direccionService;
private UsuarioService usuarioService;
public DireccionController(DireccionService direccionService,UsuarioService usuarioService) {
this.direccionService = direccionService;
this.usuarioService=usuarioService;
}
@GetMapping("/actualizar/{id}")
public String actualizarDireccion(@PathVariable Long id,Model model){
model.addAttribute("direccion",direccionService.getDireccion(id));
model.addAttribute("usuarios",usuarioService.getUsuario(id));
model.addAttribute("usuarios",usuarioService.usuarioLista());
return "direccion/lista";
}
@GetMapping("/lista")
public String direccionLista(Model model) {
model.addAttribute("direcciones",direccionService.direccionLista());
model.addAttribute("usuarios",usuarioService.usuarioLista());
return "direccion/lista";
}
@GetMapping("/lista/{id}")
public Optional<Direccion> getDireccion(@PathVariable Long id){
return direccionService.getDireccion(id);
}
@PostMapping("/agregar")
@PreAuthorize("hasRole('admin')")
public String agregarDireccion(@ModelAttribute("direcciones") Direccion direcciones,Model model)throws IOException {
model.addAttribute("direcciones", direccionService.agregarDireccion(direcciones).getUsuario().getUsuarioNombre());
return "redirect:/direccion/lista";
}
@GetMapping("/eliminar/{id}")
public String eliminarDireccion(@PathVariable Long id,Model model){
model.addAttribute("mensaje",direccionService.eliminarDireccion(id));
return "redirect:/direccion/lista";
}
}
JSPs
<div class="container">
<br>
<button class="btn btn-primary nBtn" >Nuevo</button>
<br>
<br>
<div class="card">
<div class="card-block">
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>Codigo</th>
<th>Ciudad</th>
<th>Distrito</th>
<th>Pais</th>
<th>Usuario</th>
<th>Actualizar</th>
<th>Eliminar</th>
</tr>
</thead>
<tbody>
<c:forEach items="${direcciones}" var="direccion">
<tr>
<td>${direccion.id}</td>
<td>${direccion.ciudad}</td>
<td>${direccion.distrito}</td>
<td>${direccion.pais}</td>
<td>${direccion.usuario.usuarioNombre}</td>
<td><a href="${path}/direccion/actualizar/${direccion.id}" class="btn btn-primary eBtn">Actualizar</a></td>
<td><a href="${path}/direccion/eliminar/${direccion.id}" class="btn btn-danger">Eliminar</a></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
<div class="myForm">
<form:form action="${path}/direccion/agregar" method="post" modelAttribute="<direcciones>,<usuarios>" >
<div class="modal fade" id="exampleModal"
tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Actualizar o Guardar</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="id" class="col-form-label">Codigo:</label>
<input type="text" class="form-control" id="id" name="id" value=""/>
</div>
<div class="form-group">
<label for="pais" class="col-form-label">Pais:</label>
<input type="text" class="form-control" id="pais" name="pais" value=""/>
</div>
<div class="form-group">
<label for="ciudad" class="col-form-label">Ciudad:</label>
<input type="text" class="form-control" id="ciudad" name="ciudad" value=""/>
</div>
<div class="form-group">
<label for="distrito" class="col-form-label">Distrito:</label>
<input type="text" class="form-control" id="distrito" name="distrito" value=""/>
</div>
<div class="form-group">
<label for="usuario" class="col-form-label">Usuario:</label>
<select name="usuario.id" id="usuario" required>
<c:forEach items="${usuarios}" var="usuario" >
<option value="${usuario.id}">${usuario.usuarioNombre}</option>
</c:forEach>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
<input type="submit" class="btn btn-primary" value="guardar"/>
</div>
</div>
</div>
</div>
</form:form>
</div>
</div>
JS
$(document).ready(function(){
$('.nBtn, .table .eBtn').on('click',function(event){
event.preventDefault();
var href=$(this).attr('href');
var text=$(this).text();
if(text=='Actualizar' ){
$.get(href,function(direccion,usuario,status){
$('.myForm #id').val(direccion.id);
$('.myForm #ciudad').val(direccion.ciudad);
$('.myForm #distrito').val(direccion.distrito);
$('.myForm #pais').val(direccion.ciudad);
$('.myForm #usuario').val(direccion.usuario);
});
$('.myForm #exampleModal').modal();
}else{
$('.myForm #id').val('');
$('.myForm #ciudad').val('');
$('.myForm #distrito').val('');
$('.myForm #pais').val('');
$('.myForm #usuario').val('');
$('.myForm #exampleModal').modal();
}
});
});
exit:
Hibernate: select address0_.id as id1_0_0_, address0_.city as city2_0_0_, address0_.district as district3_0_0_, address0_.country as country4_0_0_, address0_.user_id as user_5_0_0_, user1_.id as id1_3_1_, user1_.password as password2_3_1_, user1_.idrole_id_3 role_id , user1_.user_id as user_3_3_1_, user1_.user_name as user_4_3_1_, role2_.id as id1_2_2_, role2_.name as name2_2_2_ from address address0_ left outer join user user1_ on address0_.user_id=user1_.id left outer join role role2_ on user1_.rol_id= rol2_.id where address0_.id=? Hibernate: select user0_.id as id1_3_, user0_.password as password2_3_, user0_.role_id as role_id5_3_, user0_.user_id as user_3_3_, user0_.user_name as user_4_3_ from user user0_ Hibernate: select next_val as id_val from hibernate_sequence for update Hibernate: update hibernate_sequence set next_val= ? where next_val=? Hibernate: insert into address (city, district, country, user_id, id) values (?, ?, ?, ?, ?) Hibernate: select user0_.id as id1_3_0_, user0_.password as password2_3_0_, user0_.role_id as role_id5_3_0_, user0_ .user_id as user_3_3_0_, user0_.user_name as user_4_3_0_, role1_.id as id1_2_1_, role1_.name as name2_2_1_ from user user0_ left outer join role role1_ on user0_.rol_id=role1_.id where user0_.id=? Hibernate: select address0_.id as id1_0_, address0_.city as city2_0_, address0_.district as district3_0_, address0_.country as country4_0_, address0_.user_id as user_5_0_ from address address0_ Hibernate: select user0_.id as id1_3_0_, user0_.password as password2_3_0_, user0_.role_id as role_id5_3_0_, user0_.user_id as user_3_3_0_, user0_.user_name as user_4_3_0_, role1_.id as id1_2_1_, role1_.name as name2_2_1_ from user user0_ left outer join role role1_ on user0_.rol_id=role1_.id where user0_.id= ? Hibernate: select user0_.id as id1_3_, user0_.password as password2_3_, user0_.role_id as rol_id5_3_, user0_.user_id as user_3_3_, user0_.user_name as user_4_3_ from user user0_
In your case you have to make sure that the @PostMapping("/add") correctly receives the object you want to save and that it has a pre-established ID when it is the case to update, I'll give you a simple example that works:
Note: previously you had to load in a form everything related in your case to the address and its user so that when you click on save you can call this function from the view.
It is the same method for both updating and adding so it depends on the user id.
You will have in the implementation of
IClienteService
the following function:And the DAO will be as follows, very very simple:
Once updated, you will only have to redirect to the view where you make the list of the object you just updated.
All the best.
I already got the update and add button
In the Model I had to change the following code:
@Entity public class Address{