How to display collections inside entities on a REST service - java

I have this entity:
#Entity
#Table(name = "aspecto")
public class Aspecto implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Size(max = 2147483647)
#Column(name = "codigo")
private String codigo;
#Size(max = 2147483647)
#Column(name = "nombre")
private String nombre;
#Column(name = "creacion")
#Temporal(TemporalType.TIMESTAMP)
private Date creacion;
#OneToMany(mappedBy = "aspecto")
private Collection<AspectoItem> aspectoItemCollection;
public Aspecto() {
}
public Aspecto(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public Date getCreacion() {
return creacion;
}
public void setCreacion(Date creacion) {
this.creacion = creacion;
}
#XmlTransient
public Collection<AspectoItem> getAspectoItemCollection() {
return aspectoItemCollection;
}
public void setAspectoItemCollection(Collection<AspectoItem> aspectoItemCollection) {
this.aspectoItemCollection = aspectoItemCollection;
}
}
I use a REST web project and I fetch the results like this:
public List<Aspecto> cargarAspectos() {
List<Aspecto> aspectos = null;
try{
aspectos = aspectoFacade.findByQuery("select a from Aspecto a order by a.id");
}
catch (Exception e) {
e.printStackTrace();
}
return aspectos;
}
#GET
#Path("getAspectosTotal")
#Produces({"application/json; charset=utf-8"})
public List<Aspecto> getAspectosTotal() {
List<Aspecto> aspectos = cargarAspectos();
return aspectos;
}
But the problem is that when I fetch the results, the inner collection of the entity (aspectoItemCollection) doesn't show up in the JSON document.

Related

Cannot delete or update a parent row a foreign key constraint fails JPA Spring Boot

I have a request table related to 2 tables where I save the request number according to the type of request that can be a request for water analysis and request for soil analysis, but when I try to delete or update the request table I get the error
Cannot delete or update a parent row: a foreign key constraint fails
My code that implements the relationships is the following is the following
//class for request
#Entity
#Table(name = "solicitud")
public class Solicitud implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
//#Column(unique=true)
//private String codigo;
#ManyToOne(fetch = FetchType.LAZY)
private Estado estado;
#DateTimeFormat(pattern = "yyyy-MM-dd")
#Temporal(TemporalType.DATE)
#NotNull
#Column(name="fecha")
private Date fecha;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
private Usuario usuario;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
private Usuario teclab;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
private TipoMuestra tmuestra;
//#Min(value = 0L, message = "Debe ingresar un valor positivo")
//#Pattern(regexp = "[\\s]*[0-9]*[1-9]+",message="msg")
#NotNull
private Integer numMuestras;
int year = 0;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Estado getEstado() {
return estado;
}
public void setEstado(Estado estado) {
this.estado = estado;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
public TipoMuestra getTmuestra() {
return tmuestra;
}
public void setTmuestra(TipoMuestra tmuestra) {
this.tmuestra = tmuestra;
}
public Integer getNumMuestras() {
return numMuestras;
}
public void setNumMuestras(Integer numMuestras) {
this.numMuestras = numMuestras;
}
public Usuario getTeclab() {
return teclab;
}
public void setTeclab(Usuario teclab) {
this.teclab = teclab;
}
/*#PostPersist
public void generateCode() {
CodigoAgua agua=new CodigoAgua();
agua.setSolicitud(this);
agua.generateCode();
}*/
/**
*
*/
private static final long serialVersionUID = 1L;
}
//class for save number for type request water analysis
#Entity
#Table(name = "cagua")
public class CodigoAgua implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(unique=true)
private String codigo;
#OneToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="solicitud_id")
private Solicitud solicitud;
int year = 0;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public Solicitud getSolicitud() {
return solicitud;
}
public void setSolicitud(Solicitud solicitud) {
this.solicitud = solicitud;
}
#PostPersist
public void generateCode() {
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
year = localDate.getYear();
this.codigo=year +" - "+id+" - A";
System.out.println("Codigo solicitud creado"+id+this.getSolicitud().getId());
}
/**
*
*/
private static final long serialVersionUID = 1L;
}
//class for save number for type request soil analysis
#Entity
#Table(name = "csuelo")
public class CodigoSuelo implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(unique=true)
private String codigo;
#OneToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="solicitud_id")
private Solicitud solicitud;
int year = 0;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public Solicitud getSolicitud() {
return solicitud;
}
public void setSolicitud(Solicitud solicitud) {
this.solicitud = solicitud;
}
#PostPersist
public void generateCode() {
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
year = localDate.getYear();
this.codigo=year +" - "+id+" - S";
System.out.println("Codigo solicitud creado"+id+this.getSolicitud().getId());
}
/**
*
*/
private static final long serialVersionUID = 1L;
}
This message indicates that you want to delete a row from table1, while its primary key is present as a foreign key in table2.
To delete a record from table1, you must delete all the lines that refer to it in the other tables in order to be able to delete this record.
I hope I've helped you

error with jpa spring many to many with extra columns

My issue is "Could not set field value [2] value by reflection : [class com.shopctr7.backend.entity.ShopimportProductId.productId] setter of com.shopctr7.backend.entity.ShopimportProductId.productId"
ShopimportProductId class:
#Embeddable
public class ShopimportProductId implements Serializable {
/**
*
*/
private static final long serialVersionUID = -5618056056848194639L;
#Column(name = "shopimport_id")
private Long shopimportId;
#Column(name = "product_id")
private Long productId;
public ShopimportProductId() {
}
public Long getShopimportId() {
return shopimportId;
}
public void setShopimportId(Long shopimportId) {
this.shopimportId = shopimportId;
}
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
}
ShopimportProduct class:
#Entity
#Table(name = "shopimport_product")
public class ShopimportProduct implements Serializable {
/**
*
*/
private static final long serialVersionUID = 17304033239166680L;
#EmbeddedId
private ShopimportProductId shopimportProductId;
#ManyToOne
#MapsId("shopimportId")
private Shopimport shopimport;
#ManyToOne
#MapsId("productId")
private Product product;
private Long price;
public ShopimportProduct() {
}
private Integer amount;
public ShopimportProductId getShopimportProductId() {
return shopimportProductId;
}
public void setShopimportProductId(ShopimportProductId shopimportProductId) {
this.shopimportProductId = shopimportProductId;
}
public Shopimport getShopimport() {
return shopimport;
}
public void setShopimport(Shopimport shopimport) {
this.shopimport = shopimport;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Long getPrice() {
return price;
}
public void setPrice(Long price) {
this.price = price;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
}
Shopimport class
#Entity
#Table(name = "shopimport")
public class Shopimport extends UserDateAudit {
/**
*
*/
private static final long serialVersionUID = -7067616970499289402L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne
#JoinColumn(name = "user_id")
private User user;
#OneToMany(mappedBy = "product")
private List<ShopimportProduct> shopimportProducts;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<ShopimportProduct> getShopimportProducts() {
return shopimportProducts;
}
public void setShopimportProducts(List<ShopimportProduct> shopimportProducts) {
this.shopimportProducts = shopimportProducts;
}
}
Product class
#Entity
#Table(name = "product")
public class Product extends UserDateAudit {
/**
*
*/
private static final long serialVersionUID = -979803757359739557L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
private String name;
#NotNull
private Long price;
#NotNull
private Integer amount;
private String imageUrl;
#OneToMany(mappedBy = "shopimport")
private List<ShopimportProduct> shopimportProducts;
#Enumerated(EnumType.STRING)
#Column(length = 60)
private ProductType productType;
public Product() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getPrice() {
return price;
}
public void setPrice(Long price) {
this.price = price;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public ProductType getProductType() {
return productType;
}
public void setProductType(ProductType productType) {
this.productType = productType;
}
public List<ShopimportProduct> getShopimportProducts() {
return shopimportProducts;
}
public void setShopimportProducts(List<ShopimportProduct> shopimportProducts) {
this.shopimportProducts = shopimportProducts;
}
}
My test
User user = userRepository.findById(2L)
.orElseThrow(() -> new UsernameNotFoundException("User not found with id : "));
Shopimport shopImport = new Shopimport();
shopImport.setUser(user);
Shopimport ShopImportResult = shopImportRepository.save(shopImport);
Product product1 = productRepository.findById(2L)
.orElseThrow(() -> new UsernameNotFoundException("User not found with id : "));
ShopimportProduct shopimportProduct = new ShopimportProduct();
shopimportProduct.setShopimport(ShopImportResult);
shopimportProduct.setProduct(product1);
shopimportProduct.setAmount(100);
shopimportProduct.setPrice(1000L);
shopImportProductRepository.save(shopimportProduct);
Product product2 = productRepository.findById(2L)
.orElseThrow(() -> new UsernameNotFoundException("User not found with id : "));
ShopimportProduct shopimportProduct2 = new ShopimportProduct();
shopimportProduct2.setShopimport(ShopImportResult);
shopimportProduct2.setProduct(product2);
shopimportProduct2.setAmount(200);
shopimportProduct2.setPrice(2000L);
shopImportProductRepository.save(shopimportProduct2);
My issue at shopImportProductRepository.save(shopimportProduct);
Could not set field value [2] value by reflection : [class com.shopctr7.backend.entity.ShopimportProductId.productId] setter of com.shopctr7.backend.entity.ShopimportProductId.productId

Columns are not populating in tableview on javafx

I have been trying to make the columns show a string of paciente and empleado but still they show empty, the other columns are fine, they show what they supposed to show, but these 2 (paciente and empleado) are still empty. I thought it was because of their properties, that they have different names, i tried that and still they came up empty, can i have some tips on how to do it the right way?
columnaCitasFecha.setCellValueFactory(new PropertyValueFactory<Cita, Date>("fecha"));
columnaCitasHora.setCellValueFactory(new PropertyValueFactory<Cita, Time>("hora"));
columnaCitasPaciente.setCellValueFactory(new PropertyValueFactory<Paciente, String>("nombrePaciente"));
columnaCitasDentista.setCellValueFactory(new PropertyValueFactory<Empleado, String>("nombreEmpleado"));
columnaCitasTratamiento.setCellValueFactory(new PropertyValueFactory<Cita, Set<Tratamiento>>("listaTratamientos"));
#Entity
#Table(name = "CITA")
public class Cita implements Serializable{
private long id;
private Date fecha;
private Time hora;
private Paciente paciente;
private Empleado empleado;
private Set<Tratamiento> listaTratamientos;
public Cita() {
fecha = null;
hora = null;
paciente = null;
empleado = null;
listaTratamientos = null;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "CITA_ID", nullable = false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Column(name = "FECHA", nullable = false)
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
#Column(name = "HORA", nullable = false)
public Time getHora() {
return hora;
}
public void setHora(Time hora) {
this.hora = hora;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "PACIENTE_ID")
public Paciente getPaciente() {
return paciente;
}
public void setPaciente(Paciente paciente) {
this.paciente = paciente;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "EMPLEADO_ID")
public Empleado getEmpleado() {
return empleado;
}
public void setEmpleado(Empleado empleado) {
this.empleado = empleado;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "CITA_TRATAMIENTO", joinColumns = {#JoinColumn(name = "CITA_ID", referencedColumnName = "CITA_ID")}, inverseJoinColumns = {#JoinColumn(name = "TRATAMIENTO_ID", referencedColumnName = "T_ID", unique = true)})
public Set<Tratamiento> getListaTratamientos() {
return listaTratamientos;
}
public void setListaTratamientos(Set<Tratamiento> listaTratamientos) {
this.listaTratamientos = listaTratamientos;
}
}
The 2 columns that are not populating are Persona and Paciente, here are the classes:
#Entity
#Table(name = "PERSONA")
#Inheritance(strategy = InheritanceType.JOINED)
public class Persona implements Serializable{
private long id;
private String nombre;
private String apellido;
private Sexo sexo;
private Date fechaNacimiento;
private String estadoCivil;
private String ocupacion;
private String nacionalidad;
private String telefono;
private String celular;
private String direccion;
private String correoElectronico;
private Date fechaRegistrado;
private Date fechaActualizado;
public Persona(){
nombre = "";
apellido = "";
sexo = null;
fechaNacimiento = null;
estadoCivil = "";
ocupacion = "";
nacionalidad = "";
telefono = "";
celular = "";
direccion = "";
correoElectronico = "";
fechaRegistrado = null;
fechaActualizado = null;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID", nullable = false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Column(name = "NOMBRE", nullable = false)
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
#Column(name = "APELLIDO", nullable = false)
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
#Enumerated(EnumType.STRING)
#Column(name = "SEXO", nullable = false)
public Sexo getSexo() {
return sexo;
}
public void setSexo(Sexo sexo) {
this.sexo = sexo;
}
#Column(name = "FECHA_NACIMIENTO", nullable = false)
public Date getFechaNacimiento() {
return fechaNacimiento;
}
public void setFechaNacimiento(Date fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
#Column(name = "ESTADO_CIVIL")
public String getEstadoCivil() {
return estadoCivil;
}
public void setEstadoCivil(String estadoCivil) {
this.estadoCivil = estadoCivil;
}
#Column(name = "OCUPACION")
public String getOcupacion() {
return ocupacion;
}
public void setOcupacion(String ocupacion) {
this.ocupacion = ocupacion;
}
#Column(name = "NACIONALIDAD")
public String getNacionalidad() {
return nacionalidad;
}
public void setNacionalidad(String nacionalidad) {
this.nacionalidad = nacionalidad;
}
#Column(name = "TELEFONO")
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
#Column(name = "CELULAR")
public String getCelular() {
return celular;
}
public void setCelular(String celular) {
this.celular = celular;
}
#Column(name = "DIRECCION")
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
#Column(name = "CORREO_ELECTRONICO")
public String getCorreoElectronico() {
return correoElectronico;
}
public void setCorreoElectronico(String correoElectronico) {
this.correoElectronico = correoElectronico;
}
#Column(name = "FECHA_REGISTRADO", nullable = false)
public Date getFechaRegistrado() {
return fechaRegistrado;
}
public void setFechaRegistrado(Date fechaRegistrado) {
this.fechaRegistrado = fechaRegistrado;
}
#Column(name = "FECHA_ACTUALIZADO", nullable = false)
public Date getFechaActualizado() {
return fechaActualizado;
}
public void setFechaActualizado(Date fechaActualizado) {
this.fechaActualizado = fechaActualizado;
}
}
#Entity
#Table(name = "PACIENTE")
#PrimaryKeyJoinColumn(name = "PACIENTE_ID")
public class Paciente extends Persona implements Serializable {
private String nombrePaciente;
public Paciente() {
super();
}
#Transient
public String getNombrePaciente() {
return this.getNombre() + " " + this.getApellido();
}
public void setNombrePaciente(String nombrePaciente) {
this.nombrePaciente = nombrePaciente;
}
}
#Entity
#Table(name = "EMPLEADO")
#PrimaryKeyJoinColumn(name = "EMPLEADO_ID")
public class Empleado extends Persona implements Serializable {
private TipoEmpleado tipoEmpleado;
private String nombreEmpleado;
public Empleado(){
super();
tipoEmpleado = null;
}
#Column(name = "TIPO_EMPLEADO", nullable = false)
#Enumerated(EnumType.STRING)
public TipoEmpleado getTipoEmpleado() {
return tipoEmpleado;
}
public void setTipoEmpleado(TipoEmpleado tipoEmpleado) {
this.tipoEmpleado = tipoEmpleado;
}
#Transient
public String getNombreEmpleado() {
return this.getNombre() + " " + this.getApellido();
}
public void setNombreEmpleado(String nombreEmpleado) {
this.nombreEmpleado = nombreEmpleado;
}
}
You need:
TableColumn<Cita, String> columnaCitasPaciente ;
// ...
columnaCitasPaciente.setCellValueFactory(cellData ->
new SimpleStringProperty(cellData.getValue().getPaciente().getNombrePaciente()));
columnaCitasDentista.setCellValueFactory(cellData ->
new SimpleStringProperty(cellData.getValue().getEmpleado().getNombreEmpleado());

Deleting child entity from set in parent class

I am trying to attach image files to an entity called product. I can create a product along with the image pretty well but when i try to delete an image i get the following error.
HTTP 500 - Request processing failed; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.IJM.model.Product
Product Class
#Entity
#Table(name = "Product")
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "Id")
private Long id;
#NotNull
#Size(min = 3, max = 10)
#Column(name = "Code", nullable = false)
private String code;
#NotNull
#Size(min = 3, max = 50)
#Column(name = "Name", nullable = false)
private String name;
#Size( max = 50)
#Column(name = "Description", nullable = false)
private String description;
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "Id_Category")
private Category category;
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "Id_Unit")
private Unit unit;
#OneToMany(cascade = CascadeType.ALL,
fetch= FetchType.EAGER,
orphanRemoval = true,
mappedBy="product")
private Set<Image> images;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
if(this.category==null||!this.category.equals(category))
{
this.category=category;
}
return;
}
public Unit getUnit() {
return unit;
}
public void setUnit(Unit unit) {
if(this.unit==null||!this.unit.equals(unit))
{
this.unit=unit;
}
return;
}
public Set<Image> getImages() {
return images;
}
public void setImages(Set<Image> images) {
this.images = images;
}
}
Image Class
#Entity
#Table(name = "product_Image")
public class Image {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id", nullable = false)
private long id;
#Lob
#Column(name = "File", nullable = false)
private byte[] file;
#Column(name = "Checksum",nullable = false)
private String checksum;
#Column(name = "Extension",nullable = false)
private String extension;
#Column(name = "File_Name",nullable = false)
private String file_name;
#Column(name = "Size",nullable = false)
private int size;
#Column(name = "Last_Updated",nullable = false)
private Timestamp last_Updated;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="Id_Product")
private Product product;
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name="Id_Directory")
private Directory directory;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public byte[] getFile() {
return file;
}
public void setFile(byte[] file) {
this.file = file;
}
public String getChecksum() {
return checksum;
}
public void setChecksum(String checksum) {
this.checksum = checksum;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public String getFile_name() {
return file_name;
}
public void setFile_name(String file_name) {
this.file_name = file_name;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public Timestamp getLast_Updated() {
return last_Updated;
}
public void setLast_Updated(Timestamp last_Updated) {
this.last_Updated = last_Updated;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Directory getDirectory() {
return directory;
}
public void setDirectory(Directory directory) {
this.directory = directory;
}
And this is the code for the controller calling the deleting method
#RestController
#RequestMapping("/image")
public class ImageController {
#Autowired
ProductService productService;
#Autowired
ImageService imageService;
private static final String productImagePath="C:\\IJM\\Images\\Product\\";
#RequestMapping(value = "/product/{code}", method = RequestMethod.DELETE)
public ResponseEntity<Image> deleteProductImage(#PathVariable("code") String code) {
System.out.println("Fetching & Deleting Image for product " + code);
code = code.toUpperCase();
if (!productService.isProductExist(code)) {
System.out.println("Product with code " + code + " not found");
return new ResponseEntity<Image>(HttpStatus.NOT_FOUND);
}
else
{
Product product = productService.findProductByCode(code);
if(product.getImages()!=null)
{
for(Image image:product.getImages())
{
product.getImages().remove(image);
image.setProduct(null);
imageService.deleteImage(image.getId());
}
productService.saveProduct(product);
try{
File file = new File(productImagePath+code);
if(FileDeleter.removeDirectory(file)){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
return new ResponseEntity<Image>(HttpStatus.NO_CONTENT);
}
}
In case someone else is wondering.. the service just calls the DAO
#Override
public void deleteImage(long id) {
Image image = imageDao.findById(id);
imageDao.delete(image);
}
This is the Dao Class
#Repository("imageDao")
public class ImageDaoImpl extends AbstractDao<Long,Image> implements ImageDao{
#Override
public void delete(Image image) {
super.delete(image);
}
}
This is the code in my abstract DAO class
public void delete(T entity) {
getSession().delete(entity);
}
It seems these line are not in proper order.
product.getImages().remove(image);
image.setProduct(null);
imageService.deleteImage(image.getId());
Also not sure what imageService.deleteImage(image.getId()); is doing. It is not required.
Please try like below.
for(Image image:product.getImages())
{
image.setProduct(null);
product.getImages().remove(image);
}
productService.saveProduct(product);
This should be enough. I know it doesn't make any sense to change the order but It had worked for me.

How to prevent endless loop in hibernate

I have a rest server and client which uses this API. I have a list of hotels and it had passed well until I added bidirectional dependencies to other entities.After that I start receive an endless array of entities which just repeat the same row in database.
It is my first project with hibernate so may be I made trivial mistakes of novice.
Hotel:
#Entity
#Table(name = "hotels", schema = "", catalog = "mydb")
public class HotelsEntity implements HospitalityEntity{
private int idHotel;
private String name;
private String region;
private String description;
// private byte[] photo;
private HotelPropertyEntity property;
private List<RoomEntity> rooms;
#OneToOne(mappedBy = "hotel")
public HotelPropertyEntity getProperty() {
return property;
}
public void setProperty(HotelPropertyEntity property) {
this.property = property;
}
#OneToMany(mappedBy = "hotel")
public List<RoomEntity> getRooms() {
return rooms;
}
public void setRooms(List<RoomEntity> rooms) {
this.rooms = rooms;
}
#Id
#Column(name = "id_hotel", unique = true)
#GeneratedValue(strategy=GenerationType.AUTO)
public int getIdHotel() {
return idHotel;
}
public void setIdHotel(int idHotel) {
this.idHotel = idHotel;
}
#Basic
#Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "region")
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
#Basic
#Column(name = "description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
HotelProperty
#Entity
#Table(name = "hotel_property", schema = "", catalog = "mydb")
public class HotelPropertyEntity {
private int idHotelProperty;
private byte hasPool;
private byte hasTennisCourt;
private byte hasWaterslides;
private HotelsEntity hotel;
#Id
#Column(name = "id_hotel_property", unique = true)
#GeneratedValue(strategy=GenerationType.AUTO)
public int getIdHotelProperty() {
return idHotelProperty;
}
public void setIdHotelProperty(int idHotelProperty) {
this.idHotelProperty = idHotelProperty;
}
#Basic
#Column(name = "has_pool", columnDefinition = "BIT", length = 1)
public byte getHasPool() {
return hasPool;
}
public void setHasPool(byte hasPool) {
this.hasPool = hasPool;
}
#Basic
#Column(name = "has_tennis_court", columnDefinition = "BIT", length = 1)
public byte getHasTennisCourt() {
return hasTennisCourt;
}
public void setHasTennisCourt(byte hasTennisCourt) {
this.hasTennisCourt = hasTennisCourt;
}
#Basic
#Column(name = "has_waterslides", columnDefinition = "BIT", length = 1)
public byte getHasWaterslides() {
return hasWaterslides;
}
public void setHasWaterslides(byte hasWaterslides) {
this.hasWaterslides = hasWaterslides;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "id_hotel_property")
public HotelsEntity getHotel() {
return hotel;
}
public void setHotel(HotelsEntity hotel) {
this.hotel = hotel;
}
Room:
#Entity
#Table(name = "room", schema = "", catalog = "mydb")
public class RoomEntity {
private int idRoom;
private String roomType;
private int peopleCapacity;
private Boolean booked;
private Boolean locked;
private HotelsEntity hotel;
private InventoriesEntity inventory;
private RoomPropertyEntity roomProperty;
#OneToOne(mappedBy = "room")
public RoomPropertyEntity getRoom() {
return roomProperty;
}
public void setRoom(RoomPropertyEntity roomProperty) {
this.roomProperty = roomProperty;
}
#OneToOne
#JoinColumn(name = "id_room")
public InventoriesEntity getInventory() {
return inventory;
}
public void setInventory(InventoriesEntity inventory) {
this.inventory = inventory;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_hotel")
public HotelsEntity getHotel() {
return hotel;
}
public void setHotel(HotelsEntity hotel) {
this.hotel = hotel;
}
#Id
#Column(name = "id_room")
public int getIdRoom() {
return idRoom;
}
public void setIdRoom(int idRoom) {
this.idRoom = idRoom;
}
#Basic
#Column(name = "room_type")
public String getRoomType() {
return roomType;
}
public void setRoomType(String roomType) {
this.roomType = roomType;
}
#Basic
#Column(name = "people_capacity")
public int getPeopleCapacity() {
return peopleCapacity;
}
public void setPeopleCapacity(int peopleCapacity) {
this.peopleCapacity = peopleCapacity;
}
#Basic
#Column(name = "booked", columnDefinition = "BIT", length = 1)
public Boolean getBooked() {
return booked;
}
public void setBooked(Boolean booked) {
this.booked = booked;
}
#Basic
#Column(name = "locked", columnDefinition = "BIT", length = 1)
public Boolean getLocked() {
return locked;
}
public void setLocked(Boolean locked) {
this.locked = locked;
}
Could you please advise what is a way or ways to tell hibernate to stop this cycle?
p.s
This code contains another one issue. I f I remove one to one dependency and remain only one to many I receive failed to lazily initialize a collection of role: com.example.model.HotelsEntity.rooms, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.example.model.HotelsEntity["rooms"])
You need to mark entity as not serializable for JSON. Please use #JsonIgnore or #JsonIgnoreProperties("field") on one of the sides of the relations (the annotation is class-level).

Categories

Resources