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.
Related
I have problem with my web application. I need to display in Listthings from 4 tables.
My main table is "umowienia" "appointment" and it have connection one to many with klienci AS "clients", pracownik AS "employee", usługi AS "services", and stanowiska AS "positions"
I want to connect this tables to display it on List on one of the application pages.
When I connect tables program say to me error like this
Error creating bean with name 'realizacjeRepository' defined in figura.zaklad_fryzjerski_v3.repository.RealizacjeRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: java.util.List, at table: klienci, for columns: [org.hibernate.mapping.Column(umowienia)]
My application look like this:
construction of the application
Data base is on secodn screen screen of database
And my files:
Umowienia.java
package figura.zaklad_fryzjerski_v3.model;
import javax.persistence.*;
import java.sql.Time;
import java.util.Date;
#Entity
#Table(name = "umowienia")
public class Umowienia {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_umowienia")
private Integer id_umowienia;
#Column
private Date data_umowienia;
#Column
private Time czas_trwania;
#Column
private String komentarz;
#ManyToOne()
#JoinColumn(name = "id_klienta", referencedColumnName = "id_klienta", insertable = false, updatable = false)
private Klienci klienci;
public Klienci getKlienci() {
return klienci;
}
public void setKlienci(Klienci klienci) {
this.klienci = klienci;
}
public Integer getId_umowienia() {
return id_umowienia;
}
public void setId_umowienia(Integer id_umowienia) {
this.id_umowienia = id_umowienia;
}
public Date getData_umowienia() {
return data_umowienia;
}
public void setData_umowienia(Date data_umowienia) {
this.data_umowienia = data_umowienia;
}
public Time getCzas_trwania() {
return czas_trwania;
}
public void setCzas_trwania(Time czas_trwania) {
this.czas_trwania = czas_trwania;
}
public String getKomentarz() {
return komentarz;
}
public void setKomentarz(String komentarz) {
this.komentarz = komentarz;
}
}
Klienci.java
package figura.zaklad_fryzjerski_v3.model;
import javax.persistence.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
#Entity
#Table(name = "klienci")
public class Klienci {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_klienta")
private Integer id_klienta;
#Column(name = "imie")
private String imieKlienta;
#Column(name = "nazwisko")
private String nazwiskoKlienta;
#Column(name = "nr_telefonu_klienta")
private Integer nrTelefonuKlienta;
#Column(name = "adres_email")
private String adresEmailKlienta;
private List<Umowienia> umowienia;
#OneToMany(targetEntity = Umowienia.class, mappedBy = "klienci",cascade=CascadeType.ALL, fetch = FetchType.LAZY)
public List<Umowienia> getUmowienia() {
return umowienia;
}
public void setUmowienia(List<Umowienia> umowienia) {
this.umowienia = umowienia;
}
public Klienci(){
}
public Integer getId_klienta() {
return id_klienta;
}
public void setId_klienta(Integer id_klienta) {
this.id_klienta = id_klienta;
}
public String getImieKlienta() {
return imieKlienta;
}
public void setImieKlienta(String imieKlienta) {
this.imieKlienta = imieKlienta;
}
public String getNazwiskoKlienta() {
return nazwiskoKlienta;
}
public void setNazwiskoKlienta(String nazwiskoKlienta) {
this.nazwiskoKlienta = nazwiskoKlienta;
}
public Integer getNrTelefonuKlienta() {
return nrTelefonuKlienta;
}
public void setNrTelefonuKlienta(Integer nrTelefonuKlienta) {
this.nrTelefonuKlienta = nrTelefonuKlienta;
}
public String getAdresEmailKlienta() {
return adresEmailKlienta;
}
public void setAdresEmailKlienta(String adresEmailKlienta) {
this.adresEmailKlienta = adresEmailKlienta;
}
}
Pracownicy.java
package figura.zaklad_fryzjerski_v3.model;
import javax.persistence.*;
#Entity
#Table(name = "pracownik")
public class Pracownicy {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_pracownika")
private Integer id_pracownika;
#Column(name = "imie")
private String imiePracownika;
#Column(name = "nazwisko")
private String nazwiskoPracownika;
#Column(name = "nr_tele_pracownika")
private Integer nrTelefonuPracownika;
#Column(name = "typ_pracownika")
private String typPracownika;
+getters and setters
Stanowiska.java
package figura.zaklad_fryzjerski_v3.model;
import javax.persistence.*;
#Entity
#Table(name = "stanowiska")
public class Stanowiska {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_stanowiska")
private Integer id_stanowiska;
#Column(name = "numer_stanowiska")
private Integer numerStanowiska;
+getters and setters
Uslugi.java
package figura.zaklad_fryzjerski_v3.model;
import javax.persistence.*;
#Entity
#Table(name = "uslugi")
public class Uslugi {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_uslugi")
private Integer id_uslugi;
#Column(name = "nazwa_uslugi")
private String nazwaUslugi;
#Column(name = "cena_uslugi")
private Integer cenaUslugi;
FILE TO DISPLAY LIST
UmowieniaRepository
package figura.zaklad_fryzjerski_v3.repository;
import figura.zaklad_fryzjerski_v3.model.Umowienia;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UmowieniaRepository extends JpaRepository<Umowienia, Integer> {
}
UmowieniaService
package figura.zaklad_fryzjerski_v3.service.umowienia;
import figura.zaklad_fryzjerski_v3.model.Umowienia;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public interface UmowieniaService {
List<Umowienia> getAllUmowienia();
void saveUmowienia(Umowienia umowienia);
}
UmowieniaServiceImpl
package figura.zaklad_fryzjerski_v3.service.umowienia;
import figura.zaklad_fryzjerski_v3.model.Umowienia;
import figura.zaklad_fryzjerski_v3.repository.UmowieniaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Service
#Transactional
public class UmowieniaServiceImpl implements UmowieniaService {
#Autowired
private UmowieniaRepository umowieniaRepository;
#Override
public List<Umowienia> getAllUmowienia() {
return umowieniaRepository.findAll();
}
#Override
public void saveUmowienia(Umowienia umowienia) {
this.umowieniaRepository.save(umowienia);
}
}
If you need more code just write and I'll add it
You are using field access strategy (determined by #Id annotation). Put any JPA related annotation right above each field instead of getter property like this in your kilenci entity
#OneToMany(targetEntity = Umowienia.class, mappedBy = "klienci",cascade=CascadeType.ALL, fetch = FetchType.LAZY)
public List<Umowienia> umowienias;
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;
package com.ccdm.vo;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* ViewModel generated by hbm2java
*/
#Entity
#Table(name = "lb", catalog = "ccdmdb")
public class LoadBal implements java.io.Serializable {
private static final long serialVersionUID = -767868186084580713L;
private Integer lbID;
#JsonIgnore
private AppUser appUser;
private ViewModel templates;
private String lbname;
private String lbdescription;
private String lbtype;
private int clientId;
public LoadBal() {
}
public LoadBal(AppUser appUser, String lbname, String lbdescription, String lbtype, ViewModel templates,
int clientId) {
this.appUser = appUser;
this.lbname = lbname;
this.lbdescription = lbdescription;
this.lbtype = lbtype;
this.templates = templates;
this.clientId = clientId;
System.out.println(this.lbname);
System.out.println(this.lbdescription);
System.out.println(this.lbtype);
System.out.println(this.templates);
System.out.println(this.clientId);
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "LB_ID", unique = true, nullable = false)
public Integer getlbID() {
return this.lbID;
}
public void setlbID(Integer lbID) {
this.lbID = lbID;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "USER_ID", nullable = false)
public AppUser getAppUser() {
return this.appUser;
}
public void setAppUser(AppUser appUser) {
this.appUser = appUser;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "VM_ID", nullable = false)
public ViewModel getTemplates() {
System.out.println("here2" + templates);
return this.templates;
}
public void setTemplates(ViewModel VmTemplates) {
System.out.println("here3" + VmTemplates);
this.templates= VmTemplates;
}
#Column(name = "LB_NAME", nullable = false, length = 100)
public String getlbname() {
return this.lbname;
}
public void setlbname(String lbname) {
this.lbname = lbname;
}
#Column(name = "LB_DESCRIPTION", nullable = false, length = 100)
public String getlbdescription() {
return this.lbdescription;
}
public void setlbdescription(String lbdescription) {
this.lbdescription = lbdescription;
}
#Column(name = "LB_TYPE", nullable = false, length = 100)
public String getlbtype() {
return this.lbtype;
}
public void setlbtype(String lbtype) {
this.lbtype = lbtype;
}
#Column(name = "CLIENT_ID", nullable = false)
public int getClientId() {
return this.clientId;
}
public void setClientId(int clientId) {
this.clientId = clientId;
}
}
package com.ccdm.vo;
// Generated 19 Dec, 2016 5:50:57 PM by Hibernate Tools 5.2.0.CR1
import static javax.persistence.GenerationType.IDENTITY;
import java.util.HashSet;
import java.util.Set;
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.OneToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* ViewModel generated by hbm2java
*/
#Entity
#Table(name = "view_model", catalog = "ccdmdb")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class ViewModel implements java.io.Serializable {
private static final long serialVersionUID = -7778681960884580713L;
private Integer vmId;
#JsonIgnore
private AppUser appUser;
#JsonIgnore
private OperatingSystem operatingSystem;
#JsonIgnore
private VirtualMachine virtualMachine;
private String name;
private int clientId;
#JsonIgnore
private Set<SolutionVmMap> solutionVmMaps = new HashSet<SolutionVmMap>(0);
#JsonIgnore
private Set<LoadBal> VmTemplates = new HashSet<LoadBal>(0);
public ViewModel() {
}
public ViewModel(AppUser appUser, OperatingSystem operatingSystem, VirtualMachine virtualMachine, String name,
int clientId) {
this.appUser = appUser;
this.operatingSystem = operatingSystem;
this.virtualMachine = virtualMachine;
this.name = name;
this.clientId = clientId;
}
public ViewModel(AppUser appUser, OperatingSystem operatingSystem, VirtualMachine virtualMachine, String name,
int clientId, Set<SolutionVmMap> solutionVmMaps, Set<LoadBal> VmTemplates) {
this.appUser = appUser;
this.operatingSystem = operatingSystem;
this.virtualMachine = virtualMachine;
this.name = name;
this.clientId = clientId;
this.solutionVmMaps = solutionVmMaps;
this.VmTemplates = VmTemplates;
System.out.println("vmtem------" + VmTemplates);
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "VM_ID", unique = true, nullable = false)
public Integer getVmId() {
return this.vmId;
}
public void setVmId(Integer vmId) {
this.vmId = vmId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "USER_ID", nullable = false)
public AppUser getAppUser() {
return this.appUser;
}
public void setAppUser(AppUser appUser) {
this.appUser = appUser;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "OS_ID", nullable = false)
public OperatingSystem getOperatingSystem() {
return this.operatingSystem;
}
public void setOperatingSystem(OperatingSystem operatingSystem) {
System.out.println("os" + operatingSystem);
this.operatingSystem = operatingSystem;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "VIRTUAL_MACHINE_ID", nullable = false)
public VirtualMachine getVirtualMachine() {
return this.virtualMachine;
}
public void setVirtualMachine(VirtualMachine virtualMachine) {
this.virtualMachine = virtualMachine;
}
#Column(name = "NAME", nullable = false, length = 100)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "CLIENT_ID", nullable = false)
public int getClientId() {
return this.clientId;
}
public void setClientId(int clientId) {
this.clientId = clientId;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "viewModel")
public Set<SolutionVmMap> getSolutionVmMaps() {
return this.solutionVmMaps;
}
public void setSolutionVmMaps(Set<SolutionVmMap> solutionVmMaps) {
this.solutionVmMaps = solutionVmMaps;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "templates")
public Set<LoadBal> getTemplates() {
return this.VmTemplates;
}
public void setTemplates(Set<LoadBal> VmTemplates) {
this.VmTemplates = VmTemplates;
}
}
well, I'm new to spring. When I try to compile these codes, I'm getting the below-mentioned error. so please help me to sort out this problem. Thanks in advance!
org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: failed to lazily initialize a collection of role: com.ccdm.vo.ViewModel.templates, could not initialize proxy - no Session (through reference chain: com.ccdm.infrastructure.model.CCDMResponse["content"]->java.util.ArrayList[0]->com.ccdm.vo.ViewModel["templates"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.ccdm.vo.ViewModel.templates, could not initialize proxy - no Session (through reference chain:
\\\com.ccdm.infrastructure.model.CCDMResponse["content"]->java.util.ArrayList[0]->com.ccdm.vo.ViewModel["templates"])
It's not enough details in your question to help you resolve it right away, however you should
Google for LazyInitializationException - it's a common newbie problem. And it's a runtime exception, not compile time
Read the docs of the framework you're using (pure Spring or Spring Boot, JPA) how to open a transaction/session
Read about lazily initialized collections in JPA/Hibernate
Make sure you either open session/transaction in view (usually anti-pattern) or put a #Transactional annotation on your code.
Looking at your code, you're trying to serialize JPA entity rihght away to JSON so open-session-in-view will work for you, however you need to be VERY CAREFUL. This pattern is useful only in very simple applications.
LazyInitializationException is occurred while you getting #ManyToMany and #OneToMany objects
Hibernate is LAZY loading in case of(#ManyToMany and #OneToMany)
So while getting #ManyToMany or #OneToMany relation objects you should first iterate in DAO layer , and get the data other wise it shows LazyInitializationException
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="}
I have this file:
#XmlRootElement(name="Projects")
public class Projects extends ResponseWrapper {
private ArrayList<Project> project;
#XmlElement(name="Project")
public ArrayList<Project> getProject() {
return project;
}
public void setProject(List<Project> list) {
this.project = (ArrayList<Project>)list;
}
}
Project has an #XMLInverseReference
System.out.println(JAXBContext.newInstance(Projects.class).getClass()); //error
Exception Description: The method [setProject] or [getProject] is not defined in the object [com.tps.www.data.Projects].
While printing out Project.class:
System.out.println(JAXBContext.newInstance(Project.class).getClass()); //OK
20:27:01,118 INFO [stdout] (http-localhost-127.0.0.1-8180-1) class org.eclipse.persistence.jaxb.JAXBContext
package com.tps.www.data;
import java.io.Serializable;
import java.util.Date;
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.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlInverseReference;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.hibernate.annotations.NamedQueries;
import org.hibernate.annotations.NamedQuery;
import com.tps.www.util.ResponseWrapper;
#NamedQueries({
#NamedQuery(name = "findProjectById", query = "select p from Project p where p.projectCode = ?"),
#NamedQuery(name="findAllProject",query="from Project p")})
#Entity
#Table(name = "Project")
#XmlRootElement(name = "Project",namespace="http://www.w3.org/2001/XMLSchema-instance")
public class Project extends ResponseWrapper implements Serializable {
#Id
#GeneratedValue
#Column(name = "Project_Code")
private String projectCode;
#Column(name = "Project_Name")
private String projectName;
#Column(name = "Starting_Date")
private Date startingDate;
#Column(name = "Expected_End_Date")
private Date expectedEndDate;
#Column(name = "Created_By")
private String createdBy;
#LazyCollection(LazyCollectionOption.FALSE)
#OneToOne(mappedBy = "project",fetch = FetchType.EAGER,cascade=CascadeType.ALL)
private Contract contract;
#OneToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "Service_Id")
private Service service;
#OneToOne(mappedBy = "project",fetch = FetchType.EAGER,cascade=CascadeType.ALL)
private BudgetRequestInfo budgetRequestInfo;
#LazyCollection(LazyCollectionOption.FALSE)
#OneToMany(mappedBy = "project",cascade=CascadeType.ALL)
private List<MaterialRequestAssignment> materialRequestAssignment;
#XmlElement(name = "Project_Code", nillable=true)
public String getProjectCode() {
return projectCode;
}
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
#XmlElement(name = "Project_Name", nillable=true)
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
#XmlElement(name = "Starting_Date", nillable=true)
public Date getStartingDate() {
return startingDate;
}
public void setStartingDate(Date startingDate) {
this.startingDate = startingDate;
}
#XmlElement(name = "Expected_End_Date", nillable=true)
public Date getExpectedEndDate() {
return expectedEndDate;
}
public void setExpectedEndDate(Date expectedEndDate) {
this.expectedEndDate = expectedEndDate;
}
#XmlElement(name = "Created_By", nillable=true)
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#XmlElement(name = "Contract", nillable=true)
#XmlInverseReference(mappedBy="project")
public Contract getContract() {
return contract;
}
public void setContract(Contract contract) {
this.contract = contract;
}
#XmlElement(name = "Service_Id", nillable=true)
#XmlInverseReference(mappedBy="project")
public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}
#XmlElement(name = "Budget_Request_Info", nillable=true)
#XmlInverseReference(mappedBy="project")
public BudgetRequestInfo getBudgetRequestInfo() {
return budgetRequestInfo;
}
public void setBudgetRequestInfo(BudgetRequestInfo budgetRequestInfo) {
this.budgetRequestInfo = budgetRequestInfo;
}
#XmlElement(name = "Material_Request_Assignment", nillable=true)
#XmlInverseReference(mappedBy="project")
public List<MaterialRequestAssignment> getMaterialRequestAssignment() {
return materialRequestAssignment;
}
public void setMaterialRequestAssignment(
List<MaterialRequestAssignment> materialRequestAssignment) {
this.materialRequestAssignment = materialRequestAssignment;
}
}
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-22) expert group.
I have not been able to reproduce the issue you are seeing. Could you help provide more information so that I can reproduce the problem? Here is what I have tried:
Removed JPA & Hibernate annotations from Project class to get it to compile.
Created empty ResponseWrapper class for Project and Projects to extend.
Created classes for each class referenced by Project.
When a property is marked with #XmlInverseReference added the project property on the corresponding type:
public class Contract {
private Project project;
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
}
Ran the following demo code:
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Projects.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum19953731/input.xml");
Projects projects = (Projects) unmarshaller.unmarshal(xml);
}
}