package com.maroclance.university.service;
import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ModuleServiceTest {
public class ModuleServiceTest {
private static ClassPathXmlApplicationContext context;
private static ModuleService moduleService;
#BeforeClass
public static void setUpBeforeClass() throws Exception {
context = new ClassPathXmlApplicationContext("application-context.xml");
moduleService=(ModuleService) context.getBean("moduleService");
}
#AfterClass
public static void tearDownAfterClass() throws Exception {
context.close();
}
#Test
public void test() {
fail("Not yet implemented");
}
}
i have the warning that moduleService is not used
when i execute my code i have this error
rg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [application-context.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class: com.maroclance.model.Matiere.profMats[com.maroclance.model.ProfMat]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1401)
.
.
.
.
aused by: org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class: com.maroclance.model.Matiere.profMats[com.maroclance.model.ProfMat]
at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1068)
I'm really blocked
One of the classes ProfMat or Module has not mapped with Hibernate. The mapping should be defined via configuration. If you are using annotation configuration then put a #Table annotation on the associated classes and make sure that classes are scanned for annotations.
package com.maroclance.university.model;
// Generated 19 sept. 2014 13:34:26 by Hibernate Tools 3.4.0.CR1
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* Matiere generated by hbm2java
*/
#SuppressWarnings("serial")
#Entity
#Table(name = "matiere", catalog = "gestionmatiere")
public class Matiere implements java.io.Serializable {
private int id;
private String nomMatiere;
private int coefficient;
private Set<ProfMat> profMats = new HashSet<ProfMat>(0);
private Set<Module> modules = new HashSet<Module>(0);
public Matiere() {
}
public Matiere(int id, String nomMatiere, int coefficient) {
this.id = id;
this.nomMatiere = nomMatiere;
this.coefficient = coefficient;
}
public Matiere(int id, String nomMatiere, int coefficient,
Set<ProfMat> profMats, Set<Module> modules) {
this.id = id;
this.nomMatiere = nomMatiere;
this.coefficient = coefficient;
this.profMats = profMats;
this.modules = modules;
}
#Id
#Column(name = "id", unique = true, nullable = false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "nom_matiere", nullable = false, length = 20)
public String getNomMatiere() {
return this.nomMatiere;
}
public void setNomMatiere(String nomMatiere) {
this.nomMatiere = nomMatiere;
}
#Column(name = "coefficient", nullable = false)
public int getCoefficient() {
return this.coefficient;
}
public void setCoefficient(int coefficient) {
this.coefficient = coefficient;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "matiere")
public Set<ProfMat> getProfMats() {
return this.profMats;
}
public void setProfMats(Set<ProfMat> profMats) {
this.profMats = profMats;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "matiere")
public Set<Module> getModules() {
return this.modules;
}
public void setModules(Set<Module> modules) {
this.modules = modules;
}
}
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;
So im implmenting an API using springboot, spring-data and Jackson, but im having some troubles when im trying to POST a request to an endpoint who have a Bidirection relationship of #OneToMany.
I dont have so much background so i need really help.
I have two Entities:
Partida
package lucas.duarte.jazz.model.bean;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
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 com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.JsonProperty;
#Entity
public class Partida implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String timeA;
private String timeB;
private boolean visitante;
#OneToMany(mappedBy = "partida", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<Set> sets;
public List<Set> getSets() {
return sets;
}
public void setSets(List<Set> sets) {
this.sets = sets;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTimeA() {
return timeA;
}
// Mocado o valor pois o Time A sempre e a Sao Judas
public void setTimeA(String timeA) {
this.timeA = timeA;
}
public String getTimeB() {
return timeB;
}
public void setTimeB(String timeB) {
this.timeB = timeB;
}
public boolean isVisitante() {
return visitante;
}
public void setVisitante(boolean visitante) {
this.visitante = visitante;
}
}
and SET
package lucas.duarte.jazz.model.bean;
import java.io.Serializable;
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.Table;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
#Entity
#Table(name = "meu_set")
public class Set implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "ponto_a")
private long pontoA;
#Column(name = "ponto_b")
private long pontoB;
#Column(name = "set_finalizado")
private boolean setFinalizado;
#ManyToOne
#JoinColumn(name = "partida_id")
private Partida partida;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public long getPontoA() {
return pontoA;
}
public void setPontoA(long pontoA) {
this.pontoA = pontoA;
}
public long getPontoB() {
return pontoB;
}
public void setPontoB(long pontoB) {
this.pontoB = pontoB;
}
public boolean isSetFinalizado() {
return setFinalizado;
}
public void setSetFinalizado(boolean setFinalizado) {
this.setFinalizado = setFinalizado;
}
public Partida getPartida() {
return partida;
}
public void setPartida(Partida partida) {
this.partida = partida;
}
}
This is my SetControler
package lucas.duarte.jazz.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.UriComponentsBuilder;
import lucas.duarte.jazz.model.bean.Set;
import lucas.duarte.jazz.model.service.SetService;
#Controller
#RequestMapping("/api")
public class SetController {
private SetService setServ;
#RequestMapping(value = "/set/", method = RequestMethod.POST)
public ResponseEntity<?> salvarSet(#RequestBody Set set, UriComponentsBuilder ucBuilder) {
System.out.println("Vou cadastrar um set vinculado a uma partida");
System.out.println(set.getPartida().getId());
setServ.salvarSet(set);
return new ResponseEntity(HttpStatus.CREATED);
}
}
When i POST to the URL, i get the following return
{
"timestamp": "2019-03-28T04:17:46.857+0000",
"status": 400,
"error": "Bad Request",
"message": "JSON parse error: Cannot construct instance of `lucas.duarte.jazz.model.bean.Partida` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `lucas.duarte.jazz.model.bean.Partida` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1)\n at [Source: (PushbackInputStream); line: 5, column: 14] (through reference chain: lucas.duarte.jazz.model.bean.Set[\"partida\"])",
"path": "/api/set/"
}
I Already have a Partida inside my database, but i cannot POST to this method, need really help.
This issue has nothing to do with JPA bi-directional mapping. Its raising error at the time of de serializing.
Partida -> should have zero argument constructor
Request payload should have { "partida":{"id":123}} in order to populate partida object property.
for details check this link Jackson library.
#Entity
public class Partida implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String timeA;
private String timeB;
private boolean visitante;
public Partida(){
//Default constructor required here
}
#OneToMany(mappedBy = "partida", fetch = FetchType.LAZY, cascade =
CascadeType.ALL)
private List<Set> sets;
public List<Set> getSets() {
return sets;
}
public void setSets(List<Set> sets) {
this.sets = sets;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTimeA() {
return timeA;
}
// Mocado o valor pois o Time A sempre e a Sao Judas
public void setTimeA(String timeA) {
this.timeA = timeA;
}
public String getTimeB() {
return timeB;
}
public void setTimeB(String timeB) {
this.timeB = timeB;
}
public boolean isVisitante() {
return visitante;
}
public void setVisitante(boolean visitante) {
this.visitante = visitante;
}
}
if issue not not resolved then try JSON creator
#JsonCreator
public Partida(#JsonProperty("id") Long id, #JsonProperty("timeA") String
timeA, #JsonProperty("timeB") String timeB, #JsonProperty("desc") boolean
visitante) {
this.id = id;
this.timeA = timeA;
this.timeB= timeB;
this.visitante= visitante;
}
I am developing Spring Boot app with Spring Data JPA and H2 database. I was writing my model entity classes and I got to the moment where I need to make ManyToMany relationship between FreetimeActivity and Goal entities. In Goal class I have collection of Goalable objects. Goalable is my interface. This interface is implemented by 3 classes. I want objects of any of this classes to be stored in that collection. FreetimeActivity is one of them (but the only implemented so far). Can Spring Data make some magic and make that kind of relationship for me or do I have to make separate colletion for all of these 3 classes and merge them into one interface type collection in the end?
I tried with #ManyToMany and #JoinColumn annotations and added some testing code to starting class, but when run It throws an exception:
#OneToMany or #ManyToMany targeting an unmapped class: com.github.mesayah.assista.model.Goal.activityList[com.github.mesayah.assista.model.Goalable]
Are there any annotations that can make that for me?
FreetimeActivity.java
package com.github.mesayah.assista.model;
import javax.persistence.*;
import java.util.List;
/**
* Created by Mesayah on 03.07.2017.
*/
#Entity
#Table(name = "freetime_activity")
public class FreetimeActivity extends Activity {
#Id
#GeneratedValue
private long id;
private String name;
#ManyToMany(mappedBy = "freetime_activities")
private List<Goal> goals;
#Override
public long getId() {
return id;
}
#Override
public void setId(long id) {
this.id = id;
}
#Override
public String getName() {
return name;
}
#Override
public void setName(String name) {
this.name = name;
}
public List<Goal> getGoals() {
return goals;
}
public void setGoals(List<Goal> goalList) {
this.goals = goalList;
}
public FreetimeActivity(String name) {
this.name = name;
}
}
Goal.java
package com.github.mesayah.assista.model;
import javax.persistence.*;
import java.util.List;
/**
* Created by Mesayah on 02.07.2017.
*/
#Entity
public class Goal {
#Id
#GeneratedValue
private long id;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "goal_freetime_activity", joinColumns = #JoinColumn(name = "goal_id", referencedColumnName =
"id"),
inverseJoinColumns = #JoinColumn(name = "freetime_activity_id", referencedColumnName = "id"))
private List<FreetimeActivity> activityList;
private List<Milestone> milestoneList;
public Goal() {
}
public Goal(List<FreetimeActivity> activityList) {
this.activityList = activityList;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public List<FreetimeActivity> getActivityList() {
return activityList;
}
public void setActivityList(List<FreetimeActivity> activityList) {
this.activityList = activityList;
}
public List<Milestone> getMilestoneList() {
return milestoneList;
}
public void setMilestoneList(List<Milestone> milestoneList) {
this.milestoneList = milestoneList;
}
}
AssistaApplication.java
package com.github.mesayah.assista;
import com.github.mesayah.assista.model.Course;
import com.github.mesayah.assista.model.Exam;
import com.github.mesayah.assista.repository.CourseRepository;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.transaction.annotation.Transactional;
import javax.sql.DataSource;
import java.util.List;
#SpringBootApplication
#EnableJpaRepositories("com.github.mesayah.assista.model")
public class AssistaApplication {
private final static Logger logger = LoggerFactory.getLogger(AssistaApplication.class);
public static void main(String[] args) {
SpringApplication.run(AssistaApplication.class, args);
}
#Bean
#Transactional
public CommandLineRunner commandLineRunner(CourseRepository courseRepository, ExamRepository examRepository) {
return (args) -> {
Course course = new Course("Dancing Course");
Exam exam = new Exam("Dancing Test", course);
// testing save
courseRepository.save(course);
examRepository.save(exam);
course.getGrades().add(4.0);
course.getGrades().add(4.5d);
course.getGrades().add(3.5d);
// testing update
courseRepository.save(course);
// using Spring Data JPA automated repositories
List<Course> courses = (List<Course>) courseRepository.findAll();
List<Exam> result = examRepository.findByCourse(course);
Exam theExam = result.get(0);
// testing relations
logger.info("Courses in database: " + courses.size() + "\nExam's Course Id: " + theExam.getCourse().getId() + "\nCourse grades: " + theExam.getCourse().getGrades());
};
}
#Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
}
}
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 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);
}
}