I have a table GROCERY which has following structure:
CREATE TABLE grocery
(
gro_id NUMBER,
gro_name VARCHAR(32),
gro_dep_name VARCHAR(32),
gro_price NUMBER(16, 2),
gro_max_discount NUMBER(16, 2),
CONSTRAINT gro_pk PRIMARY KEY (gro_id, gro_dep_name)
)
My problem is that, when I am trying to fetch the data from the table (saved in my oracle data base) , I am getting the following error :
org.hibernate.id.IdentifierGenerationException: null id generated
for:class com.domain.Grocery
I have generated following entity classes according to the structure of the table :
Grocery.java
package com.domain;
import java.math.BigDecimal;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;
/**
* Grocery generated by hbm2java
*/
#SuppressWarnings("serial")
#Entity
#Table(name = "GROCERY", schema = "TPRDBA")
public class Grocery implements java.io.Serializable {
#EmbeddedId
private GroceryId id;
private String groName;
private BigDecimal groPrice;
private BigDecimal groMaxDiscount;
public Grocery() {
}
public Grocery(GroceryId id) {
this.id = id;
}
public Grocery(GroceryId id, String groName, BigDecimal groPrice, BigDecimal groMaxDiscount) {
this.id = id;
this.groName = groName;
this.groPrice = groPrice;
this.groMaxDiscount = groMaxDiscount;
}
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "groId", column = #Column(name = "GRO_ID", nullable = false, precision = 22, scale = 0)),
#AttributeOverride(name = "groDepName", column = #Column(name = "GRO_DEP_NAME", nullable = false, length = 32)) })
public GroceryId getId() {
return this.id;
}
public void setId(GroceryId id) {
this.id = id;
}
#Column(name = "GRO_NAME", length = 32)
public String getGroName() {
return this.groName;
}
public void setGroName(String groName) {
this.groName = groName;
}
#Column(name = "GRO_PRICE", precision = 16)
public BigDecimal getGroPrice() {
return this.groPrice;
}
public void setGroPrice(BigDecimal groPrice) {
this.groPrice = groPrice;
}
#Column(name = "GRO_MAX_DISCOUNT", precision = 16)
public BigDecimal getGroMaxDiscount() {
return this.groMaxDiscount;
}
public void setGroMaxDiscount(BigDecimal groMaxDiscount) {
this.groMaxDiscount = groMaxDiscount;
}
}
GroceryId.java
package com.domain;
// Generated Nov 12, 2018 11:42:16 AM by Hibernate Tools 4.3.1.Final
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
* GroceryId generated by hbm2java
*/
#SuppressWarnings("serial")
#Embeddable
public class GroceryId implements java.io.Serializable {
private BigDecimal groId;
private String groDepName;
public GroceryId() {
}
public GroceryId(BigDecimal groId, String groDepName) {
this.groId = groId;
this.groDepName = groDepName;
}
#Column(name = "GRO_ID", nullable = false, precision = 22, scale = 0)
public BigDecimal getGroId() {
return this.groId;
}
public void setGroId(BigDecimal groId) {
this.groId = groId;
}
#Column(name = "GRO_DEP_NAME", nullable = false, length = 32)
public String getGroDepName() {
return this.groDepName;
}
public void setGroDepName(String groDepName) {
this.groDepName = groDepName;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof GroceryId))
return false;
GroceryId castOther = (GroceryId) other;
return ((this.getGroId() == castOther.getGroId()) || (this.getGroId() != null && castOther.getGroId() != null
&& this.getGroId().equals(castOther.getGroId())))
&& ((this.getGroDepName() == castOther.getGroDepName())
|| (this.getGroDepName() != null && castOther.getGroDepName() != null
&& this.getGroDepName().equals(castOther.getGroDepName())));
}
public int hashCode() {
int result = 17;
result = 37 * result + (getGroId() == null ? 0 : this.getGroId().hashCode());
result = 37 * result + (getGroDepName() == null ? 0 : this.getGroDepName().hashCode());
return result;
}
}
I have followed this example.
Please help me out, I am not able to figure out what is wrong in it.
Following is my service to take the data from database, which has GroceryRepository which extends CrudRepository :
#Service
public class GroceryService {
#Autowired
GroceryRepository groceryRepository;
public List<Grocery> getAllGrocery()
{
List<Grocery> groceries = new ArrayList<>();
groceryRepository.findAll().forEach(groceries::add);
return groceries;
}
public void addGrocery(Grocery grocery)
{
groceryRepository.save(grocery);
}
}
Missed #EmbeddedId annotation in Grocery.java. Update your code as below.
#EmbeddedId
private GroceryId id;
Just use #EmbeddedId.There must be only one EmbeddedId annotation and no Id annotation when the EmbeddedId annotation is used.
#EmbeddedId
private GroceryId id;
Related
My configuration is the same as the Quarkus guide. I can now query from my database, but trying to insert produces this exception. I am VERY experienced in JPA using Eclipselink, so I know my Entity class is not the problem, as I can query the database with it using a standard JPQL syntax.
The insert fails on a simple em.persist(entity).
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not insert
Caused by: org.postgresql.util.PSQLException: Unsupported Types value: 1,426,407,511
My pom.xml:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jdbc-postgresql</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-orm</artifactId>
</dependency>
My Entity code:
package com.lmco.is3.nc.micro.datasvc.jpa.entity;
import com.lmco.is3.data.uci.NotificationSeverityType;
import com.lmco.is3.data.uci.NotificationStateType;
import com.lmco.is3.nc.micro.datasvc.jpa.converter.PostgresUuidConverter;
import java.io.Serializable;
import java.util.Objects;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "ALERT_NOTIFICATION")
#SuppressWarnings("unused")
public class AlertNotificationEntity implements Serializable {
#Id
#Convert(converter = PostgresUuidConverter.class)
#Column(name = "ALERT_NOTIFICATION_UID", nullable = false, updatable = false)
private UUID alertNotificationUid;
public UUID getAlertNotificationUid() {
return alertNotificationUid;
}
public void setAlertNotificationUid(UUID alertNotificationUid) {
this.alertNotificationUid = alertNotificationUid;
}
#Convert(converter = PostgresUuidConverter.class)
#Column(name = "SUBJECT_UID")
private UUID subjectUid;
public UUID getSubjectUid() {
return subjectUid;
}
public void setSubjectUid(UUID subjectUid) {
this.subjectUid = subjectUid;
}
/*
#ElementCollection
#CollectionTable(name = "ALERT_NOTIF_ENTITY_PERSPECTIVE",
joinColumns = #JoinColumn(name = "ALERT_NOTIFICATION_UID", referencedColumnName = "ALERT_NOTIFICATION_UID"))
#Enumerated(EnumType.ORDINAL)
#OrderColumn
#Column(name = "ENTITY_PERSPECTIVE_TYPE")
private List<EntityPerspectiveType> entityPerspectiveTypes;
public List<EntityPerspectiveType> getEntityPerspectiveTypes() {
return entityPerspectiveTypes;
}
public void setEntityPerspectiveTypes(List<EntityPerspectiveType> entityPerspectiveTypes) {
this.entityPerspectiveTypes = entityPerspectiveTypes;
}
*/
#Enumerated(EnumType.ORDINAL)
#Column(name = "NOTIFICATION_STATE")
private NotificationStateType state;
public NotificationStateType getState() {
return state;
}
public void setState(NotificationStateType state) {
this.state = state;
}
#Enumerated(EnumType.ORDINAL)
#Column(name = "NOTIFICATION_SEVERITY")
private NotificationSeverityType severity;
public NotificationSeverityType getSeverity() {
return severity;
}
public void setSeverity(NotificationSeverityType severity) {
this.severity = severity;
}
#Column(name = "NOTIFICATION_TIME")
private double notificationTime;
public double getNotificationTime() {
return notificationTime;
}
public void setNotificationTime(double notificationTime) {
this.notificationTime = notificationTime;
}
#Convert(converter = PostgresUuidConverter.class)
#Column(name = "SYSTEM_UID")
private UUID systemUid;
public UUID getSystemUid() {
return systemUid;
}
public void setSystemUid(UUID systemUid) {
this.systemUid = systemUid;
}
/*
#ElementCollection
#CollectionTable(name = "ALERT_NOTIF_APPLIES_TO_ENTITY",
joinColumns = #JoinColumn(name = "ALERT_NOTIFICATION_UID", referencedColumnName = "ALERT_NOTIFICATION_UID"))
#Convert(converter = PostgresUuidConverter.class)
#OrderColumn
#Column(name = "APPLIES_TO_ENTITY_UID")
private List<UUID> appliesToEntityUids;
public List<UUID> getAppliesToEntityUids() {
return appliesToEntityUids;
}
public void setAppliesToEntityUids(List<UUID> appliesToEntityUids) {
this.appliesToEntityUids = appliesToEntityUids;
}
*/
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AlertNotificationEntity that = (AlertNotificationEntity) o;
return Objects.equals(alertNotificationUid, that.alertNotificationUid);
}
#Override
public int hashCode() {
return Objects.hash(alertNotificationUid);
}
}
Well, I resolved my own problem, simpler than I expected.
I changed my usage of PostresUuidConverter to #Type(type = "pg-uuid") and all works now.
i'm not able to delete an entity from my database with Spring-data Jpa (hibernate). When i call the method delete of hibernate from JpaRepository, there is no mistake or exception but my FactureSortie entity isn't deleted.
Here is my models:
Facture, superclass of FactureSortie :
package be.afelio.GEDFacture.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author johan
*/
#Entity
#Table(name = "facture")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Facture.findAll", query = "SELECT f FROM Facture f")
, #NamedQuery(name = "Facture.findByIdFacture", query = "SELECT f FROM Facture f WHERE f.idFacture = :idFacture")
, #NamedQuery(name = "Facture.findByMontantHTVA", query = "SELECT f FROM Facture f WHERE f.montantHTVA = :montantHTVA")
, #NamedQuery(name = "Facture.findByMontantTVAC", query = "SELECT f FROM Facture f WHERE f.montantTVAC = :montantTVAC")
, #NamedQuery(name = "Facture.findByMontantTVA", query = "SELECT f FROM Facture f WHERE f.montantTVA = :montantTVA")
, #NamedQuery(name = "Facture.findByDateFacturation", query = "SELECT f FROM Facture f WHERE f.dateFacturation = :dateFacturation")
, #NamedQuery(name = "Facture.findByNumerocomptable", query = "SELECT f FROM Facture f WHERE f.numerocomptable = :numerocomptable")
, #NamedQuery(name = "Facture.findByUuid", query = "SELECT f FROM Facture f WHERE f.uuid = :uuid")
, #NamedQuery(name = "Facture.findByNumeroPiece", query = "SELECT f FROM Facture f WHERE f.numeroPiece = :numeroPiece")
, #NamedQuery(name = "Facture.findByValidee", query = "SELECT f FROM Facture f WHERE f.validee = :validee")})
public class Facture implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id_Facture")
private Integer idFacture;
#Basic(optional = false)
#Column(name = "Montant_HTVA")
private double montantHTVA;
#Basic(optional = false)
#Column(name = "Montant _TVAC")
private double montantTVAC;
#Basic(optional = false)
#Column(name = "Montant_TVA")
private double montantTVA;
#Basic(optional = false)
#Column(name = "Date_Facturation")
#Temporal(TemporalType.DATE)
private Date dateFacturation;
#Column(name = "Numero_comptable")
private Integer numerocomptable;
#Basic(optional = false)
#Column(name = "uuid")
private String uuid;
#Basic(optional = false)
#Column(name = "numero_piece")
private int numeroPiece;
#Column(name = "validee")
private Boolean validee;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "facture")
private FactureSortie factureSortie;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "facture")
private FactureEntree factureEntree;
#JoinColumn(name = "imputation", referencedColumnName = "Imputation")
#ManyToOne
private Projet imputation;
public Facture() {
}
public Facture(Integer idFacture) {
this.idFacture = idFacture;
}
public Facture(Integer idFacture, double montantHTVA, double montantTVAC, double montantTVA, Date dateFacturation, String uuid, int numeroPiece) {
this.idFacture = idFacture;
this.montantHTVA = montantHTVA;
this.montantTVAC = montantTVAC;
this.montantTVA = montantTVA;
this.dateFacturation = dateFacturation;
this.uuid = uuid;
this.numeroPiece = numeroPiece;
}
public Integer getIdFacture() {
return idFacture;
}
public void setIdFacture(Integer idFacture) {
this.idFacture = idFacture;
}
public double getMontantHTVA() {
return montantHTVA;
}
public void setMontantHTVA(double montantHTVA) {
this.montantHTVA = montantHTVA;
}
public double getMontantTVAC() {
return montantTVAC;
}
public void setMontantTVAC(double montantTVAC) {
this.montantTVAC = montantTVAC;
}
public double getMontantTVA() {
return montantTVA;
}
public void setMontantTVA(double montantTVA) {
this.montantTVA = montantTVA;
}
public Date getDateFacturation() {
return dateFacturation;
}
public void setDateFacturation(Date dateFacturation) {
this.dateFacturation = dateFacturation;
}
public Integer getNumerocomptable() {
return numerocomptable;
}
public void setNumerocomptable(Integer numerocomptable) {
this.numerocomptable = numerocomptable;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public int getNumeroPiece() {
return numeroPiece;
}
public void setNumeroPiece(int numeroPiece) {
this.numeroPiece = numeroPiece;
}
public Boolean getValidee() {
return validee;
}
public void setValidee(Boolean validee) {
this.validee = validee;
}
public FactureSortie getFactureSortie() {
return factureSortie;
}
public void setFactureSortie(FactureSortie factureSortie) {
this.factureSortie = factureSortie;
}
public FactureEntree getFactureEntree() {
return factureEntree;
}
public void setFactureEntree(FactureEntree factureEntree) {
this.factureEntree = factureEntree;
}
public Projet getImputation() {
return imputation;
}
public void setImputation(Projet imputation) {
this.imputation = imputation;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idFacture != null ? idFacture.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Facture)) {
return false;
}
Facture other = (Facture) object;
if ((this.idFacture == null && other.idFacture != null) || (this.idFacture != null && !this.idFacture.equals(other.idFacture))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Models.Facture[ idFacture=" + idFacture + " ]";
}
}
FactureSortie :
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package be.afelio.GEDFacture.entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
/**
*
* #author johan
*/
#Entity
#Table(name = "facture_sortie")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "FactureSortie.findAll", query = "SELECT f FROM FactureSortie f")
, #NamedQuery(name = "FactureSortie.findByIdFacture", query = "SELECT f FROM FactureSortie f WHERE f.idFacture = :idFacture")})
public class FactureSortie implements Serializable {
private static final long serialVersionUID = 1L;
#Id
// #GeneratedValue(strategy = GenerationType.IDENTITY)
// #Basic(optional = false)
#GeneratedValue(generator="sharedKeyFactureSort")
#GenericGenerator(name="sharedKeyFactureSort", strategy = "foreign", parameters = #Parameter(name="property", value="facture"))
#Column(name = "id_facture")
private Integer idFacture;
#JoinColumn(name = "id_client", referencedColumnName = "id_client")
#ManyToOne(optional = false)
private Client idClient;
#JoinColumn(name = "id_commande", referencedColumnName = "id_commande")
#ManyToOne(optional = false)
private Commande idCommande;
#JoinColumn(name = "id_facture", referencedColumnName = "id_Facture", insertable = false, updatable = true)
#OneToOne(optional = false)
private Facture facture;
#JoinColumn(name = "id_prestation", referencedColumnName = "id_prestation")
#ManyToOne
private Prestation idPrestation;
#JoinColumn(name = "id_type_vente", referencedColumnName = "id")
#ManyToOne(optional = false)
private TypeVente idTypeVente;
public FactureSortie() {
}
public FactureSortie(Integer idFacture) {
this.idFacture = idFacture;
}
public Integer getIdFacture() {
return idFacture;
}
public void setIdFacture(Integer idFacture) {
this.idFacture = idFacture;
}
public Client getIdClient() {
return idClient;
}
public void setIdClient(Client idClient) {
this.idClient = idClient;
}
public Commande getIdCommande() {
return idCommande;
}
public void setIdCommande(Commande idCommande) {
this.idCommande = idCommande;
}
public Facture getFacture() {
return facture;
}
public void setFacture(Facture facture) {
this.facture = facture;
}
public Prestation getIdPrestation() {
return idPrestation;
}
public void setIdPrestation(Prestation idPrestation) {
this.idPrestation = idPrestation;
}
public TypeVente getIdTypeVente() {
return idTypeVente;
}
public void setIdTypeVente(TypeVente idTypeVente) {
this.idTypeVente = idTypeVente;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idFacture != null ? idFacture.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof FactureSortie)) {
return false;
}
FactureSortie other = (FactureSortie) object;
if ((this.idFacture == null && other.idFacture != null) || (this.idFacture != null && !(this.idFacture == other.idFacture))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Models.FactureSortie[ idFacture=" + idFacture + " ]";
}
}
Here is my FactureSortieService that call FactureSortieDAO:
package be.afelio.GEDFacture.business.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import be.afelio.GEDFacture.business.ClientService;
import be.afelio.GEDFacture.business.CommandeService;
import be.afelio.GEDFacture.business.FactureService;
import be.afelio.GEDFacture.business.FactureSortieService;
import be.afelio.GEDFacture.business.ProjectService;
import be.afelio.GEDFacture.dao.FactureSortieDAO;
import be.afelio.GEDFacture.dto.ClientDto;
import be.afelio.GEDFacture.dto.FactureSortieDto;
import be.afelio.GEDFacture.dto.ProjetDto;
import be.afelio.GEDFacture.entities.Client;
import be.afelio.GEDFacture.entities.FactureSortie;
import be.afelio.GEDFacture.entities.Projet;
import be.afelio.GEDFacture.tools.DtoConverter;
#Component
public class FactureSortieServiceImpl implements FactureSortieService {
#Autowired
private FactureSortieDAO factureSortieDAO;
#Autowired
private ProjectService projetService;
#Autowired
private FactureService factureService;
#Autowired
private CommandeService commandeService;
#Autowired
private ClientService clientService;
private Mapper mapper = new DozerBeanMapper();
/**
* #param facture
*
* call the add method of different services to add data in
* database. call createProjet to add a project in database and
* get the new projectid call add of factureService to add a
* facture in database and get the new factureid call addCommande
* of the commandeService to add a commande and get the new
* commandeid Set the id of the facture to null because hibernate
* doesn't handle the non-null id to add save the facture and get
* it.
*/
#Override
#Transactional
public FactureSortieDto addFacture(FactureSortieDto facture) {
try {
FactureSortie sortie = DtoConverter.convertFactureDto(facture);
sortie.getFacture().setImputation(projetService.createProjet(sortie.getFacture().getImputation()));
sortie.setIdClient(clientService.createClient(sortie.getIdClient()));
sortie.setFacture(factureService.add(sortie.getFacture()));
sortie.setIdCommande(commandeService.addCommande(sortie.getIdCommande()));
// facture.setIdFacture(fa.getFacture().getIdFacture());
sortie = factureSortieDAO.save(sortie);
return DtoConverter.convertFacture(sortie);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Transactional
#Override
public List<FactureSortieDto> FindAll(int page, int size) {
int numeroPage = 0;
int taille = size == 0 ? 10 : size;
numeroPage = page / taille;
List<FactureSortie> factures = factureSortieDAO.findAll(new PageRequest(numeroPage, taille)).getContent();
List<FactureSortieDto> facturesDto = new ArrayList<>();
for (FactureSortie facture : factures) {
facturesDto.add(DtoConverter.convertFacture(facture));
}
return facturesDto;
}
#Override
public List<FactureSortieDto> find(Date dateStart, Date dateEnd, Integer pieceNumberStart, Integer pieceNumberEnd,
ClientDto idClient, ProjetDto projet, Double montantTVACStart, Double montantTVACEnd, List<String> UUIDs,
int first, int max, String sortField, String sortOrder) {
Mapper mapper = new DozerBeanMapper();
List<FactureSortie> factures;
Client client=null;
if(idClient!=null)
client= mapper.map(idClient, Client.class);
Projet project=null;
if(projet!=null)
project = mapper.map(projet, Projet.class);
factures = this.factureSortieDAO.findWithCriterias(dateStart, dateEnd, pieceNumberStart, pieceNumberEnd, client,
project, montantTVACStart, montantTVACEnd, UUIDs, first, max, sortField, sortOrder);
List<FactureSortieDto> facturesDto = new ArrayList<>();
for (FactureSortie facture : factures) {
facturesDto.add(DtoConverter.convertFacture(facture));
}
return facturesDto;
}
#Override
public long count(Date dateStart, Date dateEnd, Integer pieceNumberStart, Integer pieceNumberEnd,
ClientDto idClient, ProjetDto projet, Double montantTVACStart, Double montantTVACEnd, List<String> UUIDs) {
Client client=null;
if(idClient!=null)
client= mapper.map(idClient, Client.class);
Projet project=null;
if(projet!=null)
project = mapper.map(projet, Projet.class);
return this.factureSortieDAO.Count(dateStart, dateEnd, pieceNumberStart, pieceNumberEnd, client, project,
montantTVACStart, montantTVACEnd, UUIDs);
}
#Override
public long countAll() {
return this.factureSortieDAO.count();
}
#Override
#Transactional(readOnly=false)
public void deleteFacture(FactureSortieDto f) {
FactureSortie facture = DtoConverter.convertFactureDto(f);
facture=this.factureSortieDAO.findOne(facture.getIdFacture());
this.factureSortieDAO.delete(facture);
this.factureService.delete(facture.getFacture());
}
}
Here is my FactureSortieDAO:
package be.afelio.GEDFacture.dao;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
import be.afelio.GEDFacture.entities.FactureSortie;
public interface FactureSortieDAO extends JpaRepository<FactureSortie, Integer>,FactureSortieDAOCustom{
List<FactureSortie> findAll(Sort sort);
}
i dont know who send image server to web service, using json, my method for send:
#POST
#Path("imagenGuardar")
#Consumes({("application/json")})
#Produces("text/plain")
public int guarda(Imagenes entity) {
em.persist(entity);
return entity.getIdImagenes();
}
This my entity from database:
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author Valar_Morgulis
*/
#Entity
#Table(name = "imagenes")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Imagenes.findAll", query = "SELECT i FROM Imagenes i"),
#NamedQuery(name = "Imagenes.findByIdImagenes", query = "SELECT i FROM Imagenes i WHERE i.idImagenes = :idImagenes"),
#NamedQuery(name = "Imagenes.findByDescripcion", query = "SELECT i FROM Imagenes i WHERE i.descripcion = :descripcion")})
public class Imagenes implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "ID_IMAGENES")
private Integer idImagenes;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "DESCRIPCION")
private String descripcion;
#Lob
#Column(name = "IMAGEN")
private byte[] imagen;
#JoinColumn(name = "ID_ACTIVO", referencedColumnName = "ID_ACTIVO")
#ManyToOne(optional = false)
private Activo idActivo;
public Imagenes() {
}
public Imagenes(Integer idImagenes) {
this.idImagenes = idImagenes;
}
public Imagenes(Integer idImagenes, String descripcion) {
this.idImagenes = idImagenes;
this.descripcion = descripcion;
}
public Integer getIdImagenes() {
return idImagenes;
}
public void setIdImagenes(Integer idImagenes) {
this.idImagenes = idImagenes;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public byte[] getImagen() {
return imagen;
}
public void setImagen(byte[] imagen) {
this.imagen = imagen;
}
int activo;
public int getIdActivo() {
return idActivo.getIdActivo();
}
public void setIdActivo(int idActivo) {
this.activo = idActivo;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idImagenes != null ? idImagenes.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Imagenes)) {
return false;
}
Imagenes other = (Imagenes) object;
if ((this.idImagenes == null && other.idImagenes != null) || (this.idImagenes != null && !this.idImagenes.equals(other.idImagenes))) {
return false;
}
return true;
}
#Override
public String toString() {
return "activo.entities.Imagenes[ idImagenes=" + idImagenes + " ]";
}
}
And send data as follows:
[{"descripcion":"Imagen trasera","idActivo":84,"idImagenes":7,"imagen":"R0lGODlhEAAQAPfAAAgAAPgAAP8JCQhUAAZBAABgmAAGCg6ZAI/W//X79Pf89wAQGju3/+/3+z9wjQCc+GbG/+/x8uPz4Q6YAAAGAAAaKgCR5gpoAACH1u/5//YAABehCSanGEWzOePw4e/z9SgAAABWiP+Hh/9eXpXLjwBMebDAr+/2+gMkAKgAAGkAAP8uLvH5/5CZj+zx7Pz+/P8eHnkAAIgAAOT1/5gAABGn//+cnC9WbO/y9Njv1vz+/zmvLPT7/wAtSEkAAMnr/4+eprgAAAB1uu/1+LPdr5Cej4+aoAA4Wuf2/wCS5//Pz8joxP/T04/H6I/H583rygZAAAAkOkJhP+cAAK3eqP9zc/L68d/y3Yp/fwCI10u2QP8zM+P04f9ISP+ysq+zr0eUP/L68gleADRdLwIaAAARHAU2AGjCXkBKPxkAAIGXfw2PAAoAAAU3AFkAAI+epy9EUQAHAI/M74+ntgEQAI++2QAbK+Dy3rrl/wyl/zkAAPR/f+Tw4y+NxIXOfk++/wppAHDFZ//c3ABCai+f4ACS6DeELwB+x//Hx4S3f/j8+G7J/0qsPwBqqENiP//x8QyGAEV4P93x2ssPD3vKcwdLAAyFAACI2EeVP7LQrwt7AOf15tgAANoPDwldAIKgf4Suf6jcome0X8gAAGWbX3HFaN7x3O/y7yAkH9HszghTAC9+rMDlvOvx6glfAJTGjy9FUcLfvwt8AA2OAJTTjS+e3wpyAEV/P+34/1O5SNzw2Y/Shw2QAMXnwf8AAP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAMAALAAAAAAQABAAAAjGAIEJFDjhgMEDEwYqBLZmDZFfEH8RabjQEgkJgThs2MAhkAQSlgZqepVjB4eTKHfkeKVJ4IVNWjrIhCizg5ZNF4BdyEQrl89cEH/mopXpgphfpc4oPQNx6ZlSv8QM+EWJUsSrVK0OqPRr1y6sEb3+qkTgV6hQByEePPuLQBsTqYjIfShxbioTbYBJUfCk7xOIfp8okCIQRREFd65cMaj4joIiKAaSafEiQRgrVsIkeNGCzEI6aL5c/YKGzsKBcSigokAhzsKAADs="}]
The image is format BASE64, but throws me the following error:
javax.servlet.ServletException: Exception [EclipseLink-6065] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.QueryException
Exception Description: Cannot add the object [activo.entities.Imagenes[ idImagenes=0 ]], of class [class activo.entities.Imagenes], to container [class activo.entities.Imagenes].
Internal Exception: java.lang.ClassCastException: activo.entities.Imagenes cannot be cast to java.util.Collection
as it should send the form? Thanks
I just needed to remove the brackets , remove the GlassFish default has netbeans , delete all records and install a new one.
So I stick to insert the image into base64 to database
{"descripcion":"Imagen trasera","idActivo":{"idActivo":"84"},"idImagenes":0,"imagen":"R0lGODlhEAAQAPfAAAgAAPgAAP8JCQhUAAZBAABgmAAGCg6ZAI/W//X79Pf89wAQGju3/+/3+z9wjQCc+GbG/+/x8uPz4Q6YAAAGAAAaKgCR5gpoAACH1u/5//YAABehCSanGEWzOePw4e/z9SgAAABWiP+Hh/9eXpXLjwBMebDAr+/2+gMkAKgAAGkAAP8uLvH5/5CZj+zx7Pz+/P8eHnkAAIgAAOT1/5gAABGn//+cnC9WbO/y9Njv1vz+/zmvLPT7/wAtSEkAAMnr/4+eprgAAAB1uu/1+LPdr5Cej4+aoAA4Wuf2/wCS5//Pz8joxP/T04/H6I/H583rygZAAAAkOkJhP+cAAK3eqP9zc/L68d/y3Yp/fwCI10u2QP8zM+P04f9ISP+ysq+zr0eUP/L68gleADRdLwIaAAARHAU2AGjCXkBKPxkAAIGXfw2PAAoAAAU3AFkAAI+epy9EUQAHAI/M74+ntgEQAI++2QAbK+Dy3rrl/wyl/zkAAPR/f+Tw4y+NxIXOfk++/wppAHDFZ//c3ABCai+f4ACS6DeELwB+x//Hx4S3f/j8+G7J/0qsPwBqqENiP//x8QyGAEV4P93x2ssPD3vKcwdLAAyFAACI2EeVP7LQrwt7AOf15tgAANoPDwldAIKgf4Suf6jcome0X8gAAGWbX3HFaN7x3O/y7yAkH9HszghTAC9+rMDlvOvx6glfAJTGjy9FUcLfvwt8AA2OAJTTjS+e3wpyAEV/P+34/1O5SNzw2Y/Shw2QAMXnwf8AAP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAMAALAAAAAAQABAAAAjGAIEJFDjhgMEDEwYqBLZmDZFfEH8RabjQEgkJgThs2MAhkAQSlgZqepVjB4eTKHfkeKVJ4IVNWjrIhCizg5ZNF4BdyEQrl89cEH/mopXpgphfpc4oPQNx6ZlSv8QM+EWJUsSrVK0OqPRr1y6sEb3+qkTgV6hQByEePPuLQBsTqYjIfShxbioTbYBJUfCk7xOIfp8okCIQRREFd65cMaj4joIiKAaSafEiQRgrVsIkeNGCzEI6aL5c/YKGzsKBcSigokAhzsKAADs="}
Trying to create a one to one on a table with a composite key.
I'm unable to get it to work and getting this error:
Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext-dao.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: broken column mapping for: compensation.id of: com.ciwise.model.Focus
Compensation.java:
package com.ciwise.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name = "commissions")
public class Compensation implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Composite key
*/
private CompensationPK compensationPK;
/**
* This year monthly net sales
*/
private double tYMonthlyNetSales;
/**
* Last year monthly net sales
*/
private double lYMonthlyNetSales;
/**
* This year YTD net sales
*/
private double tYYTDNetSales;
private Focus focus;
/**
* Getters and Setters
*/
#OneToOne( mappedBy = "compensation", fetch = FetchType.EAGER)
#JoinColumn(name = "FOCUS_ID")
public Focus getFocus() {
return focus;
}
public void setFocus(Focus focus) {
this.focus = focus;
}
#EmbeddedId
public CompensationPK getCompensationPK() {
return compensationPK;
}
public void setCompensationPK(CompensationPK compensationPK) {
this.compensationPK = compensationPK;
}
#Column(name = "TY_MONTHLY_NET_SALES")
public double gettYMonthlyNetSales() {
return tYMonthlyNetSales;
}
public void settYMonthlyNetSales(double tYMonthlyNetSales) {
this.tYMonthlyNetSales = tYMonthlyNetSales;
}
#Column(name = "LY_MONTHLY_NET_SALES")
public double getlYMonthlyNetSales() {
return lYMonthlyNetSales;
}
public void setlYMonthlyNetSales(double lYMonthlyNetSales) {
this.lYMonthlyNetSales = lYMonthlyNetSales;
}
#Column(name = "TY_YTD_NET_SALES")
public double gettYYTDNetSales() {
return tYYTDNetSales;
}
public void settYYTDNetSales(double tYYTDNetSales) {
this.tYYTDNetSales = tYYTDNetSales;
}
}
CompensationPK.java
package com.ciwise.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable
public class CompensationPK implements Serializable {
private String divisionId;
private String repId;
private int focusId;
private int repTypeId;
private int commissionYear;
private int commissionMonth;
#Column(name = "DIVISION_ID")
public String getDivisionId() {
return divisionId;
}
#Column(name = "REP_ID")
public String getRepId() {
return repId;
}
#Column(name = "FOCUS_ID")
public int getFocusId() {
return focusId;
}
#Column(name = "REPTYPE_ID")
public int getRepTypeId() {
return repTypeId;
}
#Column(name = "COMMISSION_YEAR")
public int getCommissionYear() {
return commissionYear;
}
#Column(name = "COMMISSION_MONTH")
public int getCommissionMonth() {
return commissionMonth;
}
public void setDivisionId(String divisionId) {
this.divisionId = divisionId;
}
public void setRepId(String repId) {
this.repId = repId;
}
public void setFocusId(int focusId) {
this.focusId = focusId;
}
public void setRepTypeId(int repTypeId) {
this.repTypeId = repTypeId;
}
public void setCommissionYear(int commissionYear) {
this.commissionYear = commissionYear;
}
public void setCommissionMonth(int commissionMonth) {
this.commissionMonth = commissionMonth;
}
#Override
public boolean equals(Object o) {
return false;
}
#Override
public int hashCode() {
return 0;
}
}
Focus.java:
package com.ciwise.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "CT_FOCUS")
public class Focus implements Serializable {
private int focusId;
private String focusDesc;
private String focusYN;
private Compensation compensation;
#OneToOne
#PrimaryKeyJoinColumn
public Compensation getCompensation() {
return compensation;
}
public void setCompensation(Compensation compensation) {
this.compensation = compensation;
}
public Focus() {
};
#Id
#Column(name = "FOCUS_ID")
public int getFocusId() {
return focusId;
}
public void setFocusId(int focusId) {
this.focusId = focusId;
}
#Column(name = "FOCUS_DESC", length = 16)
public String getFocusDesc() {
return focusDesc;
}
public void setFocusDesc(String focusDesc) {
this.focusDesc = focusDesc;
}
#Column(name = "FOCUS_YN", length = 1)
public String getFocusYN() {
return focusYN;
}
public void setFocusYN(String focusYN) {
this.focusYN = focusYN;
}
}
Since you used an embeddable type (CompositionPK) as your primary key for Composition entity, you should annotate the corresponding primary key field in your Composition entity with #EmbeddedId.
#EmbeddedId
private CompensationPK compensationPK;
On the Focus entity, you need not specify a #PrimaryKeyJoinColumn on the one-to-one mapping. It will just use the default join column names for the foreign keys.
So this code should be fine without the #PrimaryKeyJoinColumn:
#OneToOne
public Compensation getCompensation() {
return compensation;
}
This is a sample Hibernate generated schema based on your mappings (target DB is MySQL):
Hibernate:
create table CT_FOCUS (
FOCUS_ID integer not null,
FOCUS_DESC varchar(16),
FOCUS_YN varchar(1),
compensation_COMMISSION_MONTH integer,
compensation_COMMISSION_YEAR integer,
compensation_DIVISION_ID varchar(255),
compensation_FOCUS_ID integer,
compensation_REP_ID varchar(255),
compensation_REPTYPE_ID integer,
primary key (FOCUS_ID)
)
Hibernate:
create table commissions (
COMMISSION_MONTH integer not null,
COMMISSION_YEAR integer not null,
DIVISION_ID varchar(255) not null,
FOCUS_ID integer not null,
REP_ID varchar(255) not null,
REPTYPE_ID integer not null,
LY_MONTHLY_NET_SALES double precision,
TY_MONTHLY_NET_SALES double precision,
TY_YTD_NET_SALES double precision,
primary key (COMMISSION_MONTH, COMMISSION_YEAR, DIVISION_ID, FOCUS_ID, REP_ID, REPTYPE_ID)
)
Hibernate:
alter table CT_FOCUS
add constraint FK_d6d2c9n91dlw59uiuqswfueg5
foreign key (compensation_COMMISSION_MONTH, compensation_COMMISSION_YEAR, compensation_DIVISION_ID, compensation_FOCUS_ID, compensation_REP_ID, compensation_REPTYPE_ID)
references commissions (COMMISSION_MONTH, COMMISSION_YEAR, DIVISION_ID, FOCUS_ID, REP_ID, REPTYPE_ID)
#PrimaryKeyJoinColumn can be used on a #OneToOne mapping, if you want the primary keys of Focus entity to be referencing the primary keys of Commission entity. However, you already have defined a primary key for your Focus entity, which the focusId annotated by #Id. So there's no need to specify a #PrimaryKeyJoinColumn.
I have created an object which maps two tables in my database, the Dictionary table and the Token table. The object (class) that represents the join between these two tables is called DictionaryToken.
Here is the class:
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.apache.log4j.Logger;
#Entity
#Table(name="dictionary", catalog="emscribedxcode")
public class DictionaryToken {
private static Logger LOG = Logger.getLogger(DictionaryToken.class);
private Long _seq;
private String _code;
private String _acute;
private String _gender;
private String _codeType;
private String _papplydate;
private String _capplydate;
private Long _tokenLength;
private List <TokenDictionary> _token;
private int _type;
private String _system;
private String _physicalsystem;
/*
* type of 0 is a straight line insert type of 1 is a language dictionary
* entyr type of 2 is a multiple token entry
*/
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "seq")
public Long getSeq() {
return _seq;
}
public void setSeq(Long seq_) {
_seq = seq_;
}
#Column(name = "code")
public String getCode() {
return _code;
}
public void setCode(String code_) {
_code = code_;
}
#Column(name = "acute")
public String getAcute() {
return _acute;
}
public void setAcute(String acute_) {
_acute = acute_;
}
#Column(name = "gender")
public String getGender() {
return _gender;
}
public void setGender(String gender_) {
_gender = gender_;
}
#Column(name = "codetype")
public String getCodeType() {
return _codeType;
}
public void setCodeType(String codeType_) {
_codeType = codeType_;
}
#Column(name = "papplydate")
public String getPapplydate() {
return _papplydate;
}
public void setPapplydate(String papplydate_) {
_papplydate = papplydate_;
}
#Column(name = "capplydate")
public String getCapplydate() {
return _capplydate;
}
public void setCapplydate(String capplydate_) {
_capplydate = capplydate_;
}
#Column(name = "token_length")
public Long getTokenLength() {
return _tokenLength;
}
public void setTokenLength(Long tokenLength_) {
_tokenLength = tokenLength_;
}
#OneToMany (mappedBy = "dictionarytoken", targetEntity = TokenDictionary.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public List<TokenDictionary> get_token() {
return _token;
}
public void set_token(List<TokenDictionary> _token) {
this._token = _token;
}
public void addToToken(TokenDictionary token){
this._token.add(token);
}
#Column(name = "type")
public int getType() {
return _type;
}
public void setType(int _type) {
this._type = _type;
}
#Column(name = "physicalsystem")
public String get_physicalsystem() {
return _physicalsystem;
}
public void set_physicalsystem(String _physicalsystem) {
this._physicalsystem = _physicalsystem;
}
#Column(name = "codingsystem")
public String get_system() {
return _system;
}
public void set_system(String _system) {
this._system = _system;
}
}
Here is my problem. I can perform queries using a service with this object with no problems UNLESS I add a criteria. Here is the method which retrieves the entries
public List<DictionaryToken> getDictionaryTokenEntries(String system) {
Session session = null;
List<DictionaryToken> dictonaries = new ArrayList<DictionaryToken>();
try {
session = HibernateUtils.beginTransaction("emscribedxcode");
session.createCriteria(Dictionary.class).addOrder(Order.desc("codeType"))
Criteria criteria = session.createCriteria(DictionaryToken.class);
/*******THIS IS THE PROBLEM STATEMENT*************************/
if (system != null) {
criteria.add(Restrictions.eq("codingsystem", system));
}
/****************************************************************/
// dictonaries = criteria.list();
Order order = Order.asc("seq");
criteria.addOrder(order);
dictonaries = criteria.list();
System.out.println("Dictionaryentries = " + dictonaries.size());
// System.out.println("Dictionaries entries EVICT start...");
// for(Dictionary dic : dictonaries){
// session.evict(dic);
// }
// System.out.println("Dictionaries entries EVICT end");
} catch (HibernateException e_) {
e_.printStackTrace();
NTEVENT_LOG.error("Error while getting List of Dictionary entries");
} finally {
if (session != null && session.isOpen()) {
try {
HibernateUtils.closeSessions();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return dictonaries;
}
When I add the criteria, I get the following error:
org.hibernate.QueryException: could not resolve property: coding system of : com.artificialmed.domain.dictionary.model.DictionaryToken
I know that it has something to do with the nature of the object which is really a join between my dictionary class and the underlying table and my token class and table.
The field codingsystem is a field in my dictionary class. I think I am suppose to use aliases but I don't know how to do this under the current circumstances. Any help would be greatly appreciated.
Elliott
This was a newbie problem. Hibernate requires the getters and setters of the models that reflect the tables to be of a specific format. The getter MUST BE get+ where name is the fieldname in the underlying table. The setter MUST BE set+ where name is the fieldname of the underlying table. And yes the first letter of Name must capitalized.