We are getting a null object while retrieving data from Cassandra using JPA annotation OneToOne/OneToMany (see example below, where "item" is null).
[
{
"idProduct":"095102f1-a987-4f7c-88c3-153d80b6977f",
"item":{
"idItem":"b75acb06-eab6-48c1-99e9-fc7d48cf930b",
"shortDescription":"Item 71",
"longDescription":"An another item 71",
"name":"Item Named 71",
"image":"Image 71"
},
"options":[
{
"idProductOption":"0fa701dc-5394-47ea-86f6-e3dbf6c263da",
"idProduct":"095102f1-a987-4f7c-88c3-153d80b6977f",
"productOptionValue":[
{
"idProductOptionValue":"1b594b56-7767-4909-9d16-add51903c0f2",
"idProductOption":"0fa701dc-5394-47ea-86f6-e3dbf6c263da",
"item":null
}
]
}
]
}
]
If we access "ProductOptionValue" directly it loads perfectly.
See it loading correctly (so, we think that's a level limitation to load).
[
{
"idProductOptionValue":"1b594b56-7767-4909-9d16-add51903c0f2",
"idProductOption":"0fa701dc-5394-47ea-86f6-e3dbf6c263da",
"item":{
"idItem":"17803826-0be6-4b94-813d-76abf969fa97",
"shortDescription":"Item 41",
"longDescription":"An item 41",
"name":"Item Named 41",
"image":"Image 41"
}
}
]
We are using the following annotations to relate the objects.
#Entity
#Table(name = "Product", schema = "kunderaexamples#cassandra_pu")
public class Product {
#Id
#Column(name = "idProduct")
private String idProduct;
#OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
private List<ProductOption> productOption;
#OneToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
#JoinColumn(name = "idItem", table = "Item")
private Item item;
public String getIdProduct() {
return idProduct;
}
public void setIdProduct(String idProduct) {
this.idProduct = idProduct;
}
public List<ProductOption> getOptions() {
return productOption;
}
public void setOptions(List<ProductOption> options) {
this.productOption = options;
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public Product() {
}
}
#Entity
#Table(name = "ProductOption", schema = "kunderaexamples#cassandra_pu")
public class ProductOption {
#Id
#Column(name = "idProductOption")
private String idProductOption;
#Column(name = "idProduct")
private String idProduct;
#OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
private List<ProductOptionValue> productOptionValue;
public String getIdProductOption() {
return idProductOption;
}
public void setIdProductOption(String idProductOption) {
this.idProductOption = idProductOption;
}
public List<ProductOptionValue> getProductOptionValue() {
return productOptionValue;
}
public void setProductOptionValue(List<ProductOptionValue> productOptionValues) {
this.productOptionValue = productOptionValues;
}
public String getIdProduct() {
return idProduct;
}
public void setIdProduct(String idProduct) {
this.idProduct = idProduct;
}
public ProductOption() {
}
}
#Entity
#Table(name = "ProductOptionValue", schema = "kunderaexamples#cassandra_pu")
public class ProductOptionValue {
#Id
#Column(name = "idProductOptionValue")
private String idProductOptionValue;
#Column(name = "idProductOption")
private String idProductOption;
#OneToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
#JoinColumn(name = "idItem", table = "Item")
private Item item;
public String getIdProductOptionValue() {
return idProductOptionValue;
}
public void setIdProductOptionValue(String idProductOptionValue) {
this.idProductOptionValue = idProductOptionValue;
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public String getIdProductOption() {
return idProductOption;
}
public void setIdProductOption(String idProductOption) {
this.idProductOption = idProductOption;
}
public ProductOptionValue() {
}
}
#Entity
#Table(name = "Item", schema = "kunderaexamples#cassandra_pu")
public class Item {
#Id
#Column(name = "idItem")
private String idItem;
#Column(name = "short_description")
private String shortDescription;
#Column(name = "long_description")
private String longDescription;
#Column(name = "name")
private String name;
#Column(name = "image")
private String image;
// #Column(name = "context")
// private Context context;
//
// #Column(name = "inventory")
// private Inventory inventory;
//
// #Column(name = "price")
// private ItemPrice price;
/*
* GETTERS AND SETTERS
* */
public String getIdItem() {
return idItem;
}
public void setIdItem(String idItem) {
this.idItem = idItem;
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
public String getLongDescription() {
return longDescription;
}
public void setLongDescription(String longDescription) {
this.longDescription = longDescription;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
// public Context getContext() {
// return context;
// }
//
// public void setContext(Context context) {
// this.context = context;
// }
//
// public Inventory getInventory() {
// return inventory;
// }
//
// public void setInventory(Inventory inventory) {
// this.inventory = inventory;
// }
//
// public ItemPrice getPrice() {
// return price;
// }
//
// public void setPrice(ItemPrice price) {
// this.price = price;
// }
public Item() {
}
}
Looks like there is some problem related with name of the atributes.
Check this link https://github.com/impetus-opensource/Kundera/issues/158
Related
I'm having some trouble to find out how to use an specific query on Springboot
SELECT tb_excursao.fk_cliente, tb_cliente.nome, tb_cliente.documento, tb_cliente.org_emissor, tb_cliente.data_nascimento, tb_excursao.fk_viagem, tb_viagens.destino, tb_viagens.data_viagem
FROM ((tb_excursao
INNER JOIN tb_cliente ON fk_cliente = tb_cliente.id_cliente)
INNER JOIN tb_viagens ON fk_viagem = tb_viagens.id_viagem))
This works fine on MySQL, but the examples that I saw it's always something like "SELECT u FROM User u", and as a beginner I can't relate using columns from different tables using #Query.
The models are below:
Cliente.java
#Entity
#Table(name = "tb_cliente")
public class Cliente {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long idCliente;
#NotBlank
#Size(min = 3)
private String nome;
#NotNull
private String documento;
#NotNull
private String orgEmissor;
#NotBlank
#JsonFormat(pattern = "dd/MM/yyyy")
private Date dataNascimento;
#Temporal(TemporalType.TIMESTAMP)
private Date dataCadastro = new java.sql.Date(System.currentTimeMillis());
#OneToMany(mappedBy = "fkCliente")
Set<Excursao> excursao;
public long getIdCliente() {
return idCliente;
}
public void setIdCliente(long idCliente) {
this.idCliente = idCliente;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDocumento() {
return documento;
}
public void setDocumento(String documento) {
this.documento = documento;
}
public String getOrgEmissor() {
return orgEmissor;
}
public void setOrgEmissor(String orgEmissor) {
this.orgEmissor = orgEmissor;
}
public Date getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(Date dataNascimento) {
this.dataNascimento = dataNascimento;
}
public Date getDataCadastro() {
return dataCadastro;
}
public void setDataCadastro(Date dataCadastro) {
this.dataCadastro = dataCadastro;
}
}
Viagem.java
#Entity
#Table(name = "tb_viagens")
public class Viagem {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long idViagem;
#NotBlank
private String destino;
#NotBlank
#JsonFormat(pattern = "dd/MM/yyyy")
private Date dataViagem;
#NotBlank
private int quantidadeMaxPessoas;
#OneToMany(mappedBy = "fkViagem")
private Set<Excursao> excursao;
public long getIdViagem() {
return idViagem;
}
public void setIdViagem(long idViagem) {
this.idViagem = idViagem;
}
public String getDestino() {
return destino;
}
public void setDestino(String destino) {
this.destino = destino;
}
public Date getDataViagem() {
return dataViagem;
}
public void setDataViagem(Date dataViagem) {
this.dataViagem = dataViagem;
}
public int getQuantidadeMaxPessoas() {
return quantidadeMaxPessoas;
}
public void setQuantidadeMaxPessoas(int quantidadeMaxPessoas) {
this.quantidadeMaxPessoas = quantidadeMaxPessoas;
}
}
ExcursaoEmbeddable.java
#Embeddable
public class ExcursaoEmb implements Serializable {
#Column(name = "fkCliente")
private Long fkCliente;
#Column(name = "fkViagem")
private Long fkViagem;
public Long getFkCliente() {
return this.fkCliente;
}
public void setFkCliente(Long fkCliente) {
this.fkCliente = fkCliente;
}
public Long getFkViagem() {
return this.fkViagem;
}
public void setFkViagem(Long fkViagem) {
this.fkViagem = fkViagem;
}
}
Excursao.java This is the table that the query in the beginning of the post goes
#Entity
#Table(name = "tb_excursao")
public class Excursao {
#EmbeddedId
ExcursaoEmb idExcursao;
#ManyToOne
#JoinColumn(name = "id_cliente")
private Cliente fkCliente;
#ManyToOne
#JoinColumn(name = "id_viagem")
private Viagem fkViagem;
#NotNull
private boolean primeiraParcela;
#NotNull
private boolean segundaParcela;
private boolean terceiraParcela;
public ExcursaoEmb getIdExcursao() {
return this.idExcursao;
}
public void setIdExcursao(ExcursaoEmb idExcursao) {
this.idExcursao = idExcursao;
}
public Cliente getFkCliente() {
return this.fkCliente;
}
public void setFkCliente(Cliente fkCliente) {
this.fkCliente = fkCliente;
}
public Viagem getFkViagem() {
return this.fkViagem;
}
public void setFkViagem(Viagem fkViagem) {
this.fkViagem = fkViagem;
}
public boolean isPrimeiraParcela() {
return this.primeiraParcela;
}
public boolean getPrimeiraParcela() {
return this.primeiraParcela;
}
public void setPrimeiraParcela(boolean primeiraParcela) {
this.primeiraParcela = primeiraParcela;
}
public boolean isSegundaParcela() {
return this.segundaParcela;
}
public boolean getSegundaParcela() {
return this.segundaParcela;
}
public void setSegundaParcela(boolean segundaParcela) {
this.segundaParcela = segundaParcela;
}
public boolean isTerceiraParcela() {
return this.terceiraParcela;
}
public boolean getTerceiraParcela() {
return this.terceiraParcela;
}
public void setTerceiraParcela(boolean terceiraParcela) {
this.terceiraParcela = terceiraParcela;
}
}
I have three tables which called SLSNotification,SLSWorkflow and Importer These tables are not any relationships... I want to get three tables for jasper report.. So I create a native query for it.. It works fine on MySQL... But when i add it to the SLSWorkflowRepository retrieve only workflow class only.. I want to get other classes also from this repository... I think it retrieves only because i write this like this
#Query(value = "select * from slsnotification a join sls_wrkflw b on a.snumber = b.snumber join importers c on c.importer_vat_number = a.importervat where a.importervat = :importerVatNumber and a.snumber = :snumber", nativeQuery = true)
Object getForPrint(#Param("snumber") Long snumber,#Param("importerVatNumber") String importerVatNumber);
can i get other classes for SLSIWorkflow getForPrint() methord...
If i wrong please give some onother way...
This is my models
SLSNotification Model
#Entity
#Table(name = "slsnotification")
public class SLSNotification {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(length = 16)
private Long snumber;
#Column(length = 100)
private String serialCord;
private String date;
// #JsonFormat(pattern = "yyyy-MM-dd")
// private Date appPostdate = new Date();
#Column(nullable = false)
private String appPostdate;
#Column(length = 8)
private String cusOffice;
#Column(length = 1)
private String cusSerial;
#Column(length = 50)
private String cusDecNo;
#JsonFormat(pattern = "yyyy-MM-dd")
private Date cusDate;
#Column(length = 300)
private String manufacturer;
#Column(length = 300)
private String exporterAddress;
#Column(length = 20, nullable = false)
private String importerVAT;
#NotEmpty
#Column(length = 20, nullable = false)
private String declarantVAT;
private String declarantDetails;
private String vessel;
private String blNo;
private String loadingPort;
private String tradingCountry;
private String countryOrigin;
private String invoiceNo;
#JsonFormat(pattern = "yyyy-MM-dd")
private Date invoiceDate;
private Double invoiceValue;
public Long getSnumber() {
return snumber;
}
public void setSnumber(Long snumber) {
this.snumber = snumber;
}
public String getSerialCord() {
return serialCord;
}
public void setSerialCord(String serialCord) {
this.serialCord = serialCord;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCusOffice() {
return cusOffice;
}
public void setCusOffice(String cusOffice) {
this.cusOffice = cusOffice;
}
public String getCusSerial() {
return cusSerial;
}
public void setCusSerial(String cusSerial) {
this.cusSerial = cusSerial;
}
public String getCusDecNo() {
return cusDecNo;
}
public void setCusDecNo(String cusDecNo) {
this.cusDecNo = cusDecNo;
}
public Date getCusDate() {
return cusDate;
}
public void setCusDate(Date cusDate) {
this.cusDate = cusDate;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getExporterAddress() {
return exporterAddress;
}
public void setExporterAddress(String exporterAddress) {
this.exporterAddress = exporterAddress;
}
public String getImporterVAT() {
return importerVAT;
}
public void setImporterVAT(String importerVAT) {
this.importerVAT = importerVAT;
}
public String getDeclarantVAT() {
return declarantVAT;
}
public void setDeclarantVAT(String declarantVAT) {
this.declarantVAT = declarantVAT;
}
public String getVessel() {
return vessel;
}
public void setVessel(String vessel) {
this.vessel = vessel;
}
public String getBlNo() {
return blNo;
}
public void setBlNo(String blNo) {
this.blNo = blNo;
}
public String getLoadingPort() {
return loadingPort;
}
public void setLoadingPort(String loadingPort) {
this.loadingPort = loadingPort;
}
public String getTradingCountry() {
return tradingCountry;
}
public void setTradingCountry(String tradingCountry) {
this.tradingCountry = tradingCountry;
}
public String getCountryOrigin() {
return countryOrigin;
}
public void setCountryOrigin(String countryOrigin) {
this.countryOrigin = countryOrigin;
}
public String getInvoiceNo() {
return invoiceNo;
}
public void setInvoiceNo(String invoiceNo) {
this.invoiceNo = invoiceNo;
}
public Date getInvoiceDate() {
return invoiceDate;
}
public void setInvoiceDate(Date invoiceDate) {
this.invoiceDate = invoiceDate;
}
public Double getInvoiceValue() {
return invoiceValue;
}
public void setInvoiceValue(Double invoiceValue) {
this.invoiceValue = invoiceValue;
}
SLSWorkflow Model
#Entity
#Table(name = "sls_wrkflw")
public class SLSIWorkflow {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long SNumber;
private String qc;
private String inv;
private String manuTr;
private String packList;
private String blAttached;
private String otherDoc;
private String otherDocName;
private String ad;
private String MAUsername;
private String appMan;
private String accptdQc;
private String accptTR;
private String manufacturer;
private String validMark;
private String otherDocBoolean;
private String cnfrmtyTest;
private String dtSampling;
private String otherDocDet;
private String adUsername;
private String recom;
private String reaRec;
private String tests;
private String wfStatus;
public Long getSNumber() {
return SNumber;
}
public void setSNumber(Long SNumber) {
this.SNumber = SNumber;
}
public String getQc() {
return qc;
}
public void setQc(String qc) {
this.qc = qc;
}
public String getInv() {
return inv;
}
public void setInv(String inv) {
this.inv = inv;
}
public String getManuTr() {
return manuTr;
}
public void setManuTr(String manuTr) {
this.manuTr = manuTr;
}
public String getPackList() {
return packList;
}
public void setPackList(String packList) {
this.packList = packList;
}
public String getBlAttached() {
return blAttached;
}
public void setBlAttached(String blAttached) {
this.blAttached = blAttached;
}
public String getMaattachUser() {
return maattachUser;
}
public void setMaattachUser(String maattachUser) {
this.maattachUser = maattachUser;
}
public String getMauser() {
return mauser;
}
public void setMauser(String mauser) {
this.mauser = mauser;
}
public String getMareattachUser() {
return mareattachUser;
}
public void setMareattachUser(String mareattachUser) {
this.mareattachUser = mareattachUser;
}
public String getOtherDoc() {
return otherDoc;
}
public void setOtherDoc(String otherDoc) {
this.otherDoc = otherDoc;
}
public String getOtherDocName() {
return otherDocName;
}
public void setOtherDocName(String otherDocName) {
this.otherDocName = otherDocName;
}
}
Importer Model
#Entity
#Table(name = "importers")
public class Importer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "importer_id")
private long importerId;
private String importerBrc;
#NotEmpty
#Column(unique = true, nullable = false)
private String importerVatNumber;
#Column(nullable = false)
private String category;
private String importerSVatNumber;
#NotEmpty
private String importerName;
private String importerAddress1;
#NotEmpty
private String officePhoneNumber;
#NotEmpty
private String mobilePhoneNumber;
#Email
#NotEmpty
private String email;
#Email
private String optemail1;
#Email
private String optemail2;
#NotEmpty
private String userIDandTime;
#NotEmpty
private String recentUpdateBy;
public String getOptemail1() {
return optemail1;
}
public void setOptemail1(String optemail1) {
this.optemail1 = optemail1;
}
public String getOptemail2() {
return optemail2;
}
public void setOptemail2(String optemail2) {
this.optemail2 = optemail2;
}
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinTable(name = "importer_agents",
joinColumns = {
#JoinColumn(name = "importerId")},
inverseJoinColumns = {
#JoinColumn(name = "agentId")})
private List<Agent> agentList;
public String getImporterBrc() {
return importerBrc;
}
public void setImporterBrc(String importerBrc) {
this.importerBrc = importerBrc;
}
public String getImporterVatNumber() {
return importerVatNumber;
}
public void setImporterVatNumber(String importerVatNumber) {
this.importerVatNumber = importerVatNumber;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getImporterSVatNumber() {
return importerSVatNumber;
}
public void setImporterSVatNumber(String importerSVatNumber) {
this.importerSVatNumber = importerSVatNumber;
}
public String getImporterName() {
return importerName;
}
public void setImporterName(String importerName) {
this.importerName = importerName;
}
public String getImporterAddress1() {
return importerAddress1;
}
public void setImporterAddress1(String importerAddress1) {
this.importerAddress1 = importerAddress1;
}
}
SLSIWorkflowRepository
public interface SLSIWorkflowRepository extends CrudRepository<SLSIWorkflow,Long> {
#Override
SLSIWorkflow save(SLSIWorkflow slsiWorkflow);
#Override
SLSIWorkflow findOne(Long Long);
#Override
boolean exists(Long Long);
#Override
Iterable<SLSIWorkflow> findAll();
#Override
long count();
#Override
void delete(SLSIWorkflow entity);
#Query(value = "select * from slsnotification a join sls_wrkflw b on a.snumber = b.snumber join importers c on c.importer_vat_number = a.importervat where a.importervat = :importerVatNumber and a.snumber = :snumber", nativeQuery = true)
Object getForPrint(#Param("snumber") Long snumber,#Param("importerVatNumber") String importerVatNumber);
WorkflowServices
public class WorkflowServices {
private static final Logger serviceLogger = LogManager.getLogger(WorkflowServices.class);
private static final String INIT_WORKFLOW_STATUS = "INIT";
#Autowired
private SLSIWorkflowRepository workflowRepository;
#Autowired
private FileSystemStorageService storageService;
#Autowired
private SLSNotificationRepository slsNotificationRepository;
public void initWorkflow(Long slsNumber) {
SLSIWorkflow workflow = new SLSIWorkflow();
workflow.setSNumber(slsNumber);
workflow.setWfStatus(INIT_WORKFLOW_STATUS);
workflowRepository.save(workflow);
}
public SLSIWorkflow getApplicationForPrint(Long SNumber, String importerVatNumber) {
return workflowRepository.getForPrint(SNumber, importerVatNumber);
}
}
Workflow Controller //this is large and i gives my cord only
#RequestMapping(path = "/viewTAXInvoice/{snumber}/{importerVatNumber}", method = RequestMethod.POST)
public ModelAndView getPDFReport(#PathVariable("snumber") String snumber, #PathVariable("importerVatNumber") String importerVatNumber) {
File reportsDir = Paths.get(servletContext.getRealPath(reportDataLocation)).toFile();
if (!reportsDir.exists()) {
throw ProductWithSameSerialExistsException.getInstance();
}
JRDataSource dataSource = new JRBeanCollectionDataSource(Arrays.asList(workflowServices.getApplicationForPrint(Long.parseLong(snumber), importerVatNumber)));
Map<String, Object> parameterMap = new HashMap<>();
parameterMap.put("datasource", dataSource);
parameterMap.put("JasperCustomSubReportDatasource", dataSource);
parameterMap.put(JRParameter.REPORT_FILE_RESOLVER, new SimpleFileResolver(reportsDir));
System.out.println("Dt Source1 "+dataSource);
return new ModelAndView("pdfReportforVAT", parameterMap);
}
How to connect three tables... Please help me someone...
You are getting a SLSIWorkflow only because you are returning that Entity only in the following code in WorkflowServices.
public SLSIWorkflow getApplicationForPrint(Long SNumber, String importerVatNumber) {
return workflowRepository.getForPrint(SNumber, importerVatNumber);
}
If you return an Object it will have all the fields from tables slsnotification, sls_wrkflw, importers as a Object[].
Plus using a Plain JOIN it will result in an INNER JOIN by default. This will not return anything if one joined table doesn't satisfy the ON criteria. It is good if you use LEFT JOIN so that the null will be returned.
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.
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).
Here i have two JPA Classes: TimeSheet and TimeSheetDetails
In this case i have a trouble with updation of timesheet, while updation the timesheet (master table) updated smoothly, but timesheet details (child table) generate new rows instead of updation and the link table also updated with the new values.....
Here what is the re
1)TimeSheet.java
#Entity
#Table(name = AMAM_Constants.tb_name.TIMESHEET, schema = AMAM_Constants.db_name)
public class TimeSheet implements Serializable {
private long ts_Id;
private String ts_Candidate;
private Date ts_Sdate;
private Date ts_Edate;
private String active;
private String ts_Type;
private String ts_Status;
private List<TimeSheetDetails> timesheetDetails = new ArrayList<TimeSheetDetails>();
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinTable(name = AMAM_Constants.tb_name.TIMESHEET_LINK_DETAILS, joinColumns = {
#JoinColumn(name = "TS_ID")}, inverseJoinColumns = {
#JoinColumn(name = "TSD_ID")
})
public List<TimeSheetDetails> getTimesheetDetails() {
return timesheetDetails;
}
public void setTimesheetDetails(List<TimeSheetDetails> timesheetDetails) {
this.timesheetDetails = timesheetDetails;
}
#Column(name = "ACTIVE", length = 1)
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
#Column(name = "TS_CANDIDATE", length = 25)
public String getTs_Candidate() {
return ts_Candidate;
}
public void setTs_Candidate(String ts_Candidate) {
this.ts_Candidate = ts_Candidate;
}
#Column(name = "TS_EDATE")
public Date getTs_Edate() {
return ts_Edate;
}
public void setTs_Edate(Date ts_Edate) {
this.ts_Edate = ts_Edate;
}
#Id
#GeneratedValue
#Column(name = "TS_ID")
public long getTs_Id() {
return ts_Id;
}
public void setTs_Id(long ts_Id) {
this.ts_Id = ts_Id;
}
#Column(name = "TS_SDATE")
public Date getTs_Sdate() {
return ts_Sdate;
}
public void setTs_Sdate(Date ts_Sdate) {
this.ts_Sdate = ts_Sdate;
}
#Column(name = "TS_STATUS", length = 25)
public String getTs_Status() {
return ts_Status;
}
public void setTs_Status(String ts_Status) {
this.ts_Status = ts_Status;
}
#Column(name = "TS_TYPE", length = 10)
public String getTs_Type() {
return ts_Type;
}
public void setTs_Type(String ts_Type) {
this.ts_Type = ts_Type;
}
}
#Entity
#Table(name = AMAM_Constants.tb_name.TIMESHEET_DETAILS, schema = AMAM_Constants.db_name)
public class TimeSheetDetails implements Serializable {
private long tsd_Id;
private String tsd_Po;
private Date tsd_Date;
private String tsd_DayName;
private int tsd_Hours;
private String tsd_HourType;
private String tsd_DayType;
#Column(name = "TSD_DATE")
public Date getTsd_Date() {
return tsd_Date;
}
public void setTsd_Date(Date tsd_Date) {
this.tsd_Date = tsd_Date;
}
#Column(name = "TSD_DAYNAME", length = 25)
public String getTsd_DayName() {
return tsd_DayName;
}
public void setTsd_DayName(String tsd_DayName) {
this.tsd_DayName = tsd_DayName;
}
#Column(name = "TSD_DAYTYPE", length = 25)
public String getTsd_DayType() {
return tsd_DayType;
}
public void setTsd_DayType(String tsd_DayType) {
this.tsd_DayType = tsd_DayType;
}
#Column(name = "TSD_HOURTYPE", length = 25)
public String getTsd_HourType() {
return tsd_HourType;
}
public void setTsd_HourType(String tsd_HourType) {
this.tsd_HourType = tsd_HourType;
}
#Column(name = "TSD_HOURS")
public int getTsd_Hours() {
return tsd_Hours;
}
public void setTsd_Hours(int tsd_Hours) {
this.tsd_Hours = tsd_Hours;
}
#Id
#GeneratedValue
#Column(name = "TSD_ID")
public long getTsd_Id() {
return tsd_Id;
}
public void setTsd_Id(long tsd_Id) {
this.tsd_Id = tsd_Id;
}
#Column(name = "TSD_PO", length = 25)
public String getTsd_Po() {
return tsd_Po;
}
public void setTsd_Po(String tsd_Po) {
this.tsd_Po = tsd_Po;
}
}
public class TimeSheetDao extends HibDao {
public void insertTimeSheet(TimeSheet objTimeSheet) throws Exception {
try {
begin();
getSession().save(objTimeSheet);
commit();
} catch (Exception ex) {
rollback();
throw new Exception(ex.getMessage());
} finally {
flush();
close();
}
}
public void updateTimeSheet(TimeSheet objTimeSheet) throws Exception {
try {
begin();
TimeSheet obj =(TimeSheet)getSession().get(TimeSheet.class,objTimeSheet.getTs_Id());
obj.setActive("Y");
obj.setTimesheetDetails(objTimeSheet.getTimesheetDetails());
obj.setTs_Candidate(objTimeSheet.getTs_Candidate());
obj.setTs_Edate(objTimeSheet.getTs_Edate());
obj.setTs_Sdate(objTimeSheet.getTs_Sdate());
obj.setTs_Status(objTimeSheet.getTs_Status());
obj.setTs_Type(objTimeSheet.getTs_Type());
getSession().update(obj);
commit();
} catch (Exception ex) {
rollback();
throw new Exception(ex.getMessage());
} finally {
flush();
close();
}
}
}
The problem is in this line:
obj.setTimesheetDetails(objTimeSheet.getTimesheetDetails());
You should do the same to update the child to what you are doing to update the parent. I.e:
obj.getTimesheetDetails().setTsd_Date(objTimeSheet.getTimesheetDetails().getTsd_Date);
...