Map table without bean - java

I'm not sure if the title is right... But here is my problem
This is my bean class
#Entity
#Table(name = "Exercise")
public class Exercise {
private IntegerProperty exerciseID;
private ObjectProperty<String> name;
private ObjectProperty<ExerciseCategory> category;
private ObservableList<Parameter> parameters;
public Exercise(int exerciseID, String name, ExerciseCategory category){
this.exerciseID = new SimpleIntegerProperty(exerciseID);
this.name = new SimpleObjectProperty<>(name);
this.category = new SimpleObjectProperty<>(category);
parameters = FXCollections.observableArrayList();
}
public Exercise(){
this(0,null, null);
}
public Exercise(String name, ExerciseCategory category){
this(0, name, category);
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public int getExerciseID() {
return exerciseID.get();
}
public IntegerProperty exerciseIDProperty() {
return exerciseID;
}
public void setExerciseID(int exerciseID) {
this.exerciseID.set(exerciseID);
}
#Column(name = "name", nullable = false)
public String getName() {
return name.get();
}
public ObjectProperty<String> nameProperty() {
return name;
}
public void setName(String name) {
this.name.set(name);
}
#OneToOne
public ExerciseCategory getCategory() {
return category.get();
}
public ObjectProperty<ExerciseCategory> categoryProperty() {
return category;
}
public void setCategory(ExerciseCategory category) {
this.category.set(category);
}
public ObservableList<Parameter> getParameters() {
return parameters;
}
public void setParameters(ObservableList<Parameter> parameters) {
this.parameters = parameters;
}
}
One exercise can have one more parameters. This mapping is saved in the ExerciseParameter table, which looks like this:
ExerciseParameter
ExerciseID int(11) PK
ParameterID int(11) PK
My question is, how do I map this in the Exercise class? Because I don't want to make a ExerciseParamter class...
Thank you!

It is a many-to-many relationship. You can use #ManyToMany annotion to do that.
Add following Annotation into getParameters method of Employee Entity
#ManyToMany(cascade = {CascadeType.ALL})
#JoinTable(name="ExerciseParameter",
joinColumns={#JoinColumn(name="ExerciseID ")},
inverseJoinColumns={#JoinColumn(name="ParameterID")})
And also add following Annotation into getEmployees method of Parameter entity. (You have not presented the Parameter Entity. I assume that Parameter class contains the getEmployees method.)
#ManyToMany(mappedBy="parameters")

Related

Spring and Jackson: set json ignore dynamically

I have some JPA models: "Category" and "Article":
#Entity
#Table(name = "categories")
public class Category {
private int id;
private String caption;
private Category parent;
private List<Category> childrenList;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
#ManyToOne
#JoinColumn(name = "parent_id")
public Category getParent() {
return parent;
}
public void setParent(Category parent) {
this.parent = parent;
}
#OneToMany
#JoinColumn(name = "parent_id")
public List<Category> getChildrenList() {
return childrenList;
}
public void setChildrenList(List<Category> childrenList) {
this.childrenList = childrenList;
}
}
#Entity
#Table(name = "articles")
public class Article {
private int id;
private String caption;
private boolean isAvailable;
private String description;
private int price;
private Category category;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
#Column(name = "is_available")
#Type(type = "org.hibernate.type.NumericBooleanType")
public boolean getIsAvailable() {
return isAvailable;
}
public void setIsAvailable(boolean available) {
isAvailable = available;
}
#Column
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
#ManyToOne
#JoinColumn(name = "category_id")
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
Also i have some REST controller with two methods:
1)In the first method i need to get and serialize last 10 Articles, but i don't need "childrenList" and "parent" field in Categegory.
2)In the second method i need to get the same but serialize "parent" field.
How can i solve this?
If i will use #JsonIgnore annotation to these fields then they will be never serialized.
Or should i use DTO classes?
How can i dynamically set field for ignoring?
I never use my Entitys for generating JSON, I think another set DTO classes will make you happier in the long run. My DTO typically has a constructor which takes the Entity as argument (it still needs a default constructor if you plan to use it for parsing incoming JSON).
If you really want to use your Entities, I would recommend that you use MixIns, which allows you to register a MixIn class, that augments the serialization of a specific class.
Here is a link to a MixIn example I made for another answer.
Use a custom serializer, the psedo code is below.
public class CategorySerializer extends StdSerializer<Category> {
public CategorySerializer() {
this(null);
}
public CategorySerializer(Class<Category> t) {
super(t);
}
#Override
public void serialize(Category value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
// put the logic here to write the parent and child value or not
// here is the example to how the data is serialized
jgen.writeStartObject();
jgen.writeNumberField("id", value.id);
jgen.writeStringField("caption", value.caption);
jgen.writeEndObject();
}
}
Now, to utilize the custom serializer put this annotation above your Catagory entity class.
#JsonSerialize(using = CategorySerializer.class)

Spring JPA - Data integrity relationships

I'm new to Java and even more newer to Spring (Boot and JPA) but I was curious, I'm trying to debug an issue that says, "No identifier specified for entity".
For illustartion purposes, I've created the following tables from this diagram:
Originally, there was a M:N relationship between the user and vehicle table, so I created an associative entity (UserVehicleAsso) to split the two up. I was following this guide on M:N mapping in Java, http://viralpatel.net/blogs/hibernate-many-to-many-annotation-mapping-tutorial/
For the most part, it was pretty straight forward but my question is, within the associative entity (UserVehicleAsso), do I have to use the #Id annotation for each of the foreign keys? I assume that I didn't need to because those were automatically generated from each of the respective tables.
Let me know your thoughts or comments, thanks.
Also, below is the code that I used to generate these models:
For the User table/class:
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int userId;
private String fName;
private String lName;
#ManyToMany(cascade = {CascadeType.ALL})
#JoinTable(name="userVehicleAsso",
joinColumns={#JoinColumn(name="userID")},
inverseJoinColumns={#JoinColumn(name="vehicleID")})
private Set<Vehicle> vehicles = new HashSet<Vehicle>();
//constructor
protected User() {}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getFName() {
return fName;
}
public void setFName(String fName) {
this.fName = fName;
}
public String getLName() {
return lName;
}
public void setLName(String lName) {
this.lName = lName;
}
public Set<Vehicle> getVehicles() {
return vehicles;
}
public void setVehicles(Set<Vehicle> vehicles) {
this.vehicles = vehicles;
}
#Override
public String toString() {
return getFName() + "," + getLName();
}}
For the Vehicle table/class:
#Entity
public class Vehicle {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int vehicleId;
private String brand;
private String model;
//foreign key mappings
//mapping with associative
#ManyToMany(mappedBy="vehicles")
private Set<User> users = new HashSet<User>();
//constructors
protected Vehicle() {}
public Vehicle(int id) {
this.vehicleId = id;
}
public Vehicle (String brand, String model) {
this.brand = brand;
this.model = model;
}
/* public Vehicle() {
}*/
public int getVehicleId() {
return vehicleId;
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
public void setVehicleId(int vehicleId) {
this.vehicleId = vehicleId;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
#Override
public String toString() {
// + setBodyType() + "," +
return getBrand() + "," + getModel();
}
}
And then finally, my associtive table/class:
#Entity
public class UserVehicleAsso{
private int userID;
private int vehicleID;
public int getUserID() {
return userID;
}
public void setUserID(int userID) {
this.userID = userID;
}
public int getVehicleID() {
return vehicleID;
}
public void setVehicleID(int vehicleID) {
this.vehicleID = vehicleID;
}
}
In my opinion, it's not necessary to have an Entity class for the middle table in your case. The table will be generated automatically if configured correctly. In this table, there would not be column ID, only two columns with userID and vehicleID data.
Now, if your middle table has more than what are needed to establish the M:N relationship, then your middle Entity class is needed, and the ID of it, too. For example, if this class is intended to store the time stamp every time a relationship is established, you have to:
Create this Entity class,
Give it an ID field with proper generation strategy,
Map the time stamp with a field with adequate type, annotation/XML mapping and so on.
This part of JPA/Hibernate have confused me a lot and I used to get into them. If my memory serves me well this is the proper/perfect way how things should work.
You can specify a composite primary key class that is mapped to multiple fields or properties of the entity.
Here are sample codes:
public class ActivityRegPK implements Serializable {
private int activityId;
private int memberId;
public int getActivityId() {
return activityId;
}
public void setActivityId(int activityId) {
this.activityId = activityId;
}
public int getMemberId() {
return memberId;
}
public void setMemberId(int memberId) {
this.memberId = memberId;
}
}
associtive table/class:
#IdClass(ActivityRegPK.class)
#Entity
#Table(name="activity_reg")
#NamedQuery(name="ActivityReg.findAll", query="SELECT a FROM ActivityReg a")
public class ActivityReg implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="activity_id")
private int activityId;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="ins_date")
private Date insDate;
#Id
#Column(name="member_id")
private int memberId;
}
Activity.class
#Entity
#NamedQuery(name="Activity.findAll", query="SELECT a FROM Activity a")
public class Activity implements Serializable {
// some attributes
}

How to model a one-to-one relationship in JPA when the "parent" table has a composite PK?

While there is plenty of information around on how to model, in JPA (2), a one-to-one relationship OR an entity having a natural key, I haven't been able to find a clear / simple answer to how to model the situation where we have both, i.e. a one-to-one relationship where the parent table has a natural key. It could obviously be that I might have missed such a tutorial; if so, pointing me to one could also be the answer.
And, as many times with JPA and noobs such as I, the moment one needs a bit more than the most basic model, one can quickly hit the wall.
Hence, considering the following DB model:
What would be the corresponding JPA-annotated object model? (I'm sparing you guys of the things I've tried since I don't want to influence the answer...)
Performance recommendations are also welcome (e.g. "a one-to-many could perform faster", etc.)!
Thanks,
The composite identifier is built out of two numerical columns so the mapping looks like this:
#Embeddable
public class EmployeeId implements Serializable {
private Long companyId;
private Long employeeId;
public EmployeeId() {
}
public EmployeeId(Long companyId, Long employeeId) {
this.companyId = companyId;
this.employeeId = employeeId;
}
public Long getCompanyId() {
return companyId;
}
public Long getEmployeeId() {
return employeeId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EmployeeId)) return false;
EmployeeId that = (EmployeeId) o;
return Objects.equals(getCompanyId(), that.getCompanyId()) &&
Objects.equals(getEmployeeId(), that.getEmployeeId());
}
#Override
public int hashCode() {
return Objects.hash(getCompanyId(), getEmployeeId());
}
}
The parent class, looks as follows:
#Entity(name = "Employee")
public static class Employee {
#EmbeddedId
private EmployeeId id;
private String name;
#OneToOne(mappedBy = "employee")
private EmployeeDetails details;
public EmployeeId getId() {
return id;
}
public void setId(EmployeeId id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public EmployeeDetails getDetails() {
return details;
}
public void setDetails(EmployeeDetails details) {
this.details = details;
}
}
And the child like this:
#Entity(name = "EmployeeDetails")
public static class EmployeeDetails {
#EmbeddedId
private EmployeeId id;
#MapsId
#OneToOne
private Employee employee;
private String details;
public EmployeeId getId() {
return id;
}
public void setId(EmployeeId id) {
this.id = id;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
this.id = employee.getId();
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}
And everything works just fine:
doInJPA(entityManager -> {
Employee employee = new Employee();
employee.setId(new EmployeeId(1L, 100L));
employee.setName("Vlad Mihalcea");
entityManager.persist(employee);
});
doInJPA(entityManager -> {
Employee employee = entityManager.find(Employee.class, new EmployeeId(1L, 100L));
EmployeeDetails employeeDetails = new EmployeeDetails();
employeeDetails.setEmployee(employee);
employeeDetails.setDetails("High-Performance Java Persistence");
entityManager.persist(employeeDetails);
});
doInJPA(entityManager -> {
EmployeeDetails employeeDetails = entityManager.find(EmployeeDetails.class, new EmployeeId(1L, 100L));
assertNotNull(employeeDetails);
});
doInJPA(entityManager -> {
Phone phone = entityManager.find(Phone.class, "012-345-6789");
assertNotNull(phone);
assertEquals(new EmployeeId(1L, 100L), phone.getEmployee().getId());
});
Code available on GitHub.

"IllegalArgumentException occurred calling getter of" while running criteria with SINGLE_TABLE Inheritance strategy

I have this error while trying to list objects from database with hibernate Criteria decorated with simple Restrictions
Criteria criteria = session.createCriteria(Licence.class);
criteria.add(Restrictions.eq("gym", gym.getId()));
List<Licence> list = criteria.list();
I have two classes: Licence which has an association to Gym. Those two classes are extending DataModel which is for managing information about data edition - (creation and etition, who and when). What is also important that those two classes have #Inheritance(strategy = InheritanceType.SINGLE_TABLE).
Licence
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Licence extends DataModel implements Serializable {
private Gym gym;
private String licenceType;
private String keyCode;
private Date expireDate;
private ELicenceExpiry expired;
public Licence() {
}
#ManyToOne
#JoinColumn(name="gym_id")
public Gym getGym() {
return gym;
}
public void setGym(Gym gym) {
this.gym = gym;
}
#Column(name = "licence_type")
public String getLicenceType() {
return licenceType;
}
public void setLicenceType(String licenceType) {
this.licenceType = licenceType;
}
#Column(name = "key_code")
public String getKeyCode() {
return keyCode;
}
public void setKeyCode(String keyCode) {
this.keyCode = keyCode;
}
#Column(name = "expire_date")
public Date getExpireDate() {
return expireDate;
}
public void setExpireDate(Date expireDate) {
this.expireDate = expireDate;
}
#Column(name = "expired")
#Enumerated(EnumType.ORDINAL)
public ELicenceExpiry getExpired() {
return expired;
}
public void setExpired(ELicenceExpiry expired) {
this.expired = expired;
}
}
Gym
#Entity
#Inheritance(strategy= InheritanceType.SINGLE_TABLE)
public class Gym extends DataModel implements Serializable{
private String shortName;
private String name;
private String nip;
private String street;
private String postCode;
private String localization;
private String telephone;
public Gym(){};
#Column(name="short_name")
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNip() {
return nip;
}
public void setNip(String nip) {
this.nip = nip;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
#Column(name="post_code")
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public String getLocalization() {
return localization;
}
public void setLocalization(String localization) {
this.localization = localization;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
}
DataModel
#MappedSuperclass
public abstract class DataModel implements Serializable{
protected Long id;
protected String editor;
protected Date editDate;
protected Time editTime;
protected int dataState;
#Id
#GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEditor() {
return editor;
}
public void setEditor(String editor) {
this.editor = editor;
}
#Column(name="edit_date")
public Date getEditDate() {
return editDate;
}
public void setEditDate(Date editDate) {
this.editDate = editDate;
}
#Column(name="edit_time")
public Time getEditTime() {
return editTime;
}
public void setEditTime(Time editTime) {
this.editTime = editTime;
}
#Column(name="data_state")
public int getDataState() {
return dataState;
}
public void setDataState(int dataState) {
this.dataState = dataState;
}
}
MySQL
CREATE TABLE licence(
id INT(5) NOT NULL AUTO_INCREMENT,
gym_id int(3),
licence_type VARCHAR(10),
key_code VARCHAR(10),
expire_date DATE,
expired INT(1),
editor VARCHAR(10),
edit_date DATE,
edit_time TIME,
data_state INT(1) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (gym_id) REFERENCES gym(id) ON DELETE SET NULL
);
CREATE TABLE gym(
id INT(3) NOT NULL AUTO_INCREMENT,
short_name VARCHAR(16) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL,
street VARCHAR(100),
post_code VARCHAR(6),
localization VARCHAR(64),
nip VARCHAR(13),
telephone VARCHAR(15),
editor VARCHAR(10),
edit_date DATE,
edit_time TIME,
data_state INT(1) NOT NULL,
PRIMARY KEY (id)
);
Exception:
org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of pl.fitpartner.model.DataModel.id
at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:192)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:346)
at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:4746)
at org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:4465)
(...)
Caused by: java.lang.IllegalArgumentException: java.lang.ClassCastException#37bd68c3
at sun.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:169)
... 28 more
What I am doing wrong?
I found out what was the problem. Despite that the hibernate exception was not very informative, the answer is realy trivial. In Restriction of a given Criteria I must be more precise, which field I want to refer in a query.
It should look like this:
Criteria criteria = session.createCriteria(Licence.class);
criteria.add(Restrictions.eq("gym.id", gym.getId()));
List<Licence> list = criteria.list();
For more explanation You can see this question:
Hibernate query a foreign key field with ID
Try to use
criteria.add(Restrictions.eq("gym", gym));
i.e. you put gym as second argument of criteria.add instead of gym.getId().

serializing object using gson and getting LazyInitializationException

This is my Controller method, i am trying to read my database by providing zip, cityname and province name.
#RequestMapping(value = "/retrieve", method = RequestMethod.GET)
public #ResponseBody String retrieveObjectThroughAjax(ModelMap model){
//Calling Service Method to read data according to zip,cityName and province provide
PropertyItems propertyItems=getPropertyTypeandAddressService.readAddressFromZip("H2H-
2N3","Montreal","Quebec");
Gson gson = new Gson();
String json = null;
try{
json = gson.toJson(propertyItems); // serializing object
}catch(Exception e){
logger.error(Constants.METHOD_INSIDE_MESSAGE +"getAuthors",e);
}
logger.debug(json);
return json;
}
}
Service Method
#Service
public class GetPropertyTypeandAddressServiceImpl implements GetPropertyTypeandAddressService{
#Autowired
private GetPropertyTypeandAddressDAO getPropertyTypeandAddressDAO;
#Transactional
public PropertyItems readAddressFromZip(String zipCode,String cityName,String provinceName){
PropertyItems propertyItems=getPropertyTypeandAddressDAO.getAddressFromZip(zipCode, cityName, provinceName);
Hibernate.initialize(propertyItems);
return propertyItems;
}
}
DAO Method
#Repository
public class GetPropertyTypeandAddressDAOimp implements GetPropertyTypeandAddressDAO{
#Autowired
private SessionFactory sessionFactory;
#Override
public PropertyItems getAddressFromZip(String zipCode,String cityName,String provinceName) {
PropertyItems propertyitems = new PropertyItems();
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(PropertyItems.class,"propertyItemsClass");
if(zipCode != null){
criteria.createAlias("propertyItemsClass.address","address");
criteria.add(Restrictions.eq("address.zip",zipCode));
List<PropertyItems> propertyitem = criteria.list();
if(propertyitem.size()>0){
propertyitems = propertyitem.get(0);
}
}
else if(cityName != null){
criteria.createAlias("propertyItemsClass.address","address");
criteria.add(Restrictions.eq("address.city","city"));
criteria.add(Restrictions.eq("city.cityname",cityName));
List<PropertyItems> propertyitem = criteria.list();
if(propertyitem.size()>0){
propertyitems = propertyitem.get(0);
}
}
else if(provinceName != null){
criteria.createAlias("propertyItemsClass.address","address");
criteria.add(Restrictions.eq("address.city","city"));
criteria.add(Restrictions.eq("city.provinces","provinces"));
criteria.add(Restrictions.eq("provinces.provinceName",provinceName));
List<PropertyItems> propertyitem = criteria.list();
if(propertyitem.size()>0){
propertyitems = propertyitem.get(0);
}
}
return propertyitems;
}
}
Console Error
09:53:56,988 ERROR HelloController:567 - Inside Method: getAuthors org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.agilemaple.common.entity.Property.propertyType, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
As requested my Property Items Look like this
Entity:
Propert Items
#Entity
#Table(name="web_property_item")
public class PropertyItems {
#Id
#GeneratedValue
private Integer id;
private String name;
#ManyToOne
#JoinColumn(name="property_type_id")
private PropertyType propertyType;
#OneToOne(mappedBy="propertyItems",cascade=CascadeType.ALL)
private Address address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PropertyType getPropertyType() {
return propertyType;
}
public void setPropertyType(PropertyType propertyType) {
this.propertyType = propertyType;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
Entity : Property Type
#Entity
#Table(name="web_property_type")
public class PropertyType {
#Id
#GeneratedValue
private Integer id;
private String name;
#ManyToOne
#JoinColumn(name="property_id")
private Property property;
#OneToMany(fetch = FetchType.LAZY,mappedBy="propertyType", cascade=CascadeType.ALL)
private Set<PropertyItems> propertyItems;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Property getProperty() {
return property;
}
public void setProperty(Property property) {
this.property = property;
}
public Set<PropertyItems> getPropertyItems() {
return propertyItems;
}
public void setPropertyItems(Set<PropertyItems> propertyItems) {
this.propertyItems = propertyItems;
}
}
The problem in hibernate. Your field Set of properties has Lazy fetch method, it means that it will try to get when you call method get of this set. When u calling tojson methods, gson calls all get methods of object but in this moment hibernate session is close and hibernate can't open it in controller. I've faced with the same problem but directly on JSP. In a three weeks i resolved it by one more property for hibernate ( in your case) and I write code to opening session in view interceptor. I'm underground just right now, so I can't show property, but in a hour I will edit this answer and add property.
Added:
I remembered ! property is: hibernate.enable_lazy_load_no_trans = true
If it won't help, I will add code of opensessioninviewinterceptor.
#Override
public void addInterceptors(InterceptorRegistry registry) {
OpenSessionInViewInterceptor sessionInViewInterceptor = new OpenSessionInViewInterceptor();
sessionInViewInterceptor.setSessionFactory(sessionFactory());
}

Categories

Resources