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);
}
}
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 two entities called FeeTerms.java and FeeTermDates.java
I want to get all matched records from these two entities using pure HQL
Look at entities:
FeeTerms.java
package com.rasvek.cg.entity;
// Generated May 14, 2018 11:39:07 PM by Hibernate Tools 5.1.7.Final
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
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.OneToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* FeeTerms generated by hbm2java
*/
#Entity
#Table(name = "fee_terms", catalog = "campus_guru_01")
public class FeeTerms implements java.io.Serializable {
private Integer termId;
private String termName;
private String termCount;
private Set<FeeTermDates> feeTermDateses = new HashSet<FeeTermDates>(0);
private Set<AssocFeeTerms> assocFeeTermses = new HashSet<AssocFeeTerms>(0);
public FeeTerms() {
}
public FeeTerms(String termName, String termCount, Set<FeeTermDates> feeTermDateses,
Set<AssocFeeTerms> assocFeeTermses) {
this.termName = termName;
this.termCount = termCount;
this.feeTermDateses = feeTermDateses;
this.assocFeeTermses = assocFeeTermses;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "term_id", unique = true, nullable = false)
public Integer getTermId() {
return this.termId;
}
public void setTermId(Integer termId) {
this.termId = termId;
}
#Column(name = "term_name")
public String getTermName() {
return this.termName;
}
public void setTermName(String termName) {
this.termName = termName;
}
#Column(name = "term_count", length = 45)
public String getTermCount() {
return this.termCount;
}
public void setTermCount(String termCount) {
this.termCount = termCount;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "feeTerms")
public Set<FeeTermDates> getFeeTermDateses() {
return this.feeTermDateses;
}
public void setFeeTermDateses(Set<FeeTermDates> feeTermDateses) {
this.feeTermDateses = feeTermDateses;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "feeTerms")
public Set<AssocFeeTerms> getAssocFeeTermses() {
return this.assocFeeTermses;
}
public void setAssocFeeTermses(Set<AssocFeeTerms> assocFeeTermses) {
this.assocFeeTermses = assocFeeTermses;
}
}
FeeTermDates.java
package com.rasvek.cg.entity;
// Generated May 14, 2018 11:39:07 PM by Hibernate Tools 5.1.7.Final
import static javax.persistence.GenerationType.IDENTITY;
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.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* FeeTermDates generated by hbm2java
*/
#Entity
#Table(name = "fee_term_dates", catalog = "campus_guru_01")
public class FeeTermDates implements java.io.Serializable {
private int tdmId;
private FeeTerms feeTerms;
private String date;
public FeeTermDates() {
}
public FeeTermDates(int tdmId, FeeTerms feeTerms) {
this.tdmId = tdmId;
this.feeTerms = feeTerms;
}
public FeeTermDates(int tdmId, FeeTerms feeTerms, String date) {
this.tdmId = tdmId;
this.feeTerms = feeTerms;
this.date = date;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "tdm_id", unique = true, nullable = false)
public int getTdmId() {
return this.tdmId;
}
public void setTdmId(int tdmId) {
this.tdmId = tdmId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "term_id", nullable = false)
public FeeTerms getFeeTerms() {
return this.feeTerms;
}
public void setFeeTerms(FeeTerms feeTerms) {
this.feeTerms = feeTerms;
}
#Column(name = "date")
public String getDate() {
return this.date;
}
public void setDate(String date) {
this.date = date;
}
}
i have tried with following code but i am not getting it
String hql="select FT.termId , FT.termName , FT.termCount,FT.feeTermDateses from FeeTerms FT ,FeeTermDates FD where FT.termId=FD.feeTerms" ;
query = currentSession.createQuery(hql);
termDatesList= query.getResultList();
how to achieve it as pure HQL. i am very new to Hibernate and HQl.
i have got something like below in another post,
public List<Category> getCategoryList(int id) {
List<Category> groupList;
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("select c from Category c join fetch c.events where c.parentCategory.categoryId = 1");
//query.setParameter("id", id);
groupList = query.list();
return groupList;
}
Is it possible to achieve my query as above done?
You can receive a list of Object[] with the values that you want. Like:
String hql="select FT.termId , FT.termName , FT.termCount, FT.feeTermDateses from FeeTerms FT, FeeTermDates FD where FT.termId = FD.feeTerms.id";
Query query = currentSession.createQuery(hql);
List<Object[]> results = query.getResultList();
for (Object[] obj : results) {
Integer termId = obj[0];
String termName = obj[1];
String termCount = obj[2];
Set<FeeTermDates> feeTermDates = obj[4];
}
But, I could suggest a better version:
String hql = "SELECT ft FROM FeeTerms ft JOIN ft.feeTermDateses feeTermDateses";
Query query = currentSession.createQuery(hql);
List<FeeTerms> results = query.getResultList();
This already brings to you all FeeTerms that have FeeTermDates.
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
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;
}
}