JsonView returning empty json objects - json

I am trying to implement a JsonView to selectively serialize fields from an entity but the json that is serialized has empty objects with no fields. Below is my code:
ViewClass:
public class AuditReportView {
public interface Summary {}
}
Entity:
#Entity
#SequenceGenerator(name = "AUDIT_REPORT_SEQUENCE_GENERATOR", sequenceName = "EJB_AUDIT_REPORT_SEQ", initialValue = 1, allocationSize = 1)
#Table(name = "DEVICE_AUDIT_REPORT")
#Data
public class AuditReport implements Serializable {
private static final long serialVersionUID = 1246376778314918671L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AUDIT_REPORT_SEQUENCE_GENERATOR")
#Column(name = "ID", nullable = false)
#JsonView(AuditReportView.Summary.class)
private Long id;
#Column(name = "DEVICE_ID", nullable = false)
#JsonView(AuditReportView.Summary.class)
private String deviceId;
#Column(name = "REPORT_TIMESTAMP", nullable = false)
#JsonView(AuditReportView.Summary.class)
private Calendar reportTimestamp;
#Column(name = "USER_ID", nullable = false)
#JsonView(AuditReportView.Summary.class)
private long userId;
#Column(name = "USERNAME", nullable = false)
#JsonView(AuditReportView.Summary.class)
private String username;
#Column(name = "START_DATE", nullable = false)
#JsonView(AuditReportView.Summary.class)
private Calendar startDate;
#Column(name = "END_DATE", nullable = false)
#JsonView(AuditReportView.Summary.class)
private Calendar endDate;
#OneToMany(mappedBy = "auditReport", fetch = FetchType.LAZY, orphanRemoval = true, cascade={CascadeType.ALL})
private Set<AuditEntry> auditEntries = new HashSet<AuditEntry>();
}
Controller:
#JsonView(AuditReportView.Summary.class)
#RequestMapping(method = RequestMethod.GET, value = "auditReportSummary")
public #ResponseBody ResponseEntity<?> getAuditReportSummary()
{
final List<AuditReport> auditReports = auditDAO.getAuditReportSummary();
return new ResponseEntity<>(auditReports, HttpStatus.OK);
}
Json from Postman:
[
{},
{},
{}
]
The database only has 3 results and when I debug it is definately pulling them out, it is just that no members are being serialized. I'm using Spring 4.3.7 and Jackson 2.8.7. Any ideas of what could be wrong or where to start debugging the issue?
Thanks

You must create getters and setters methods for attributes. I did it and it worked.

I guess the issue is due to the #ResponceBody ResponseEntity<?>
Please try with the following code :
#JsonView(AuditReportView.Summary.class)
#RequestMapping(method = RequestMethod.GET, value = "auditReportSummary" produces = MediaType.APPLICATION_JSON_VALUE)
public List<AuditReport getAuditReportSummary()
{
final List<AuditReport> auditReports = auditDAO.getAuditReportSummary();
return auditReports;
}
I am not much sure about it, but you can try if it works..

Try adding a default constructor - ex:
public AuditReport() {}
The default constructor is generated by the java compiler if no custom constructor is specified in the code. However if a custom constructor is specified, the default constructor is no longer automatically added which can break serialization libraries / spring, etc..
BUT - you haven't specified a constructor - how could this be?
One thing I noticed is that you're using Lombok - due to the Data annotation. Lombok can generate constructors for classes. So its possible one of the annotations or libraries you're using is adding a constructor, making the compiler skip generation of a default constructor, which may be breaking your serialization.
So, I hope adding a default constructor works out for you.

Related

Serializing stored json object gives null pointer hibernate vladmihalcea / hibernate-types

I'm saving a java object as json in my db. For this implementation when I save it, it works fine and I can find the new row in my db. However whenever I try to fetch the same object I stored, I get this error:
java.lang.NullPointerException: null
at java.lang.Class.isAssignableFrom(Native Method)
at com.vladmihalcea.hibernate.type.json.internal.JsonTypeDescriptor.fromString(JsonTypeDescriptor.java:104)
at com.vladmihalcea.hibernate.type.json.internal.JsonTypeDescriptor.wrap(JsonTypeDescriptor.java:165)
at com.vladmihalcea.hibernate.type.json.internal.AbstractJsonSqlTypeDescriptor$1.doExtract(AbstractJsonSqlTypeDescriptor.java:34)
at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47)...
My hibernate versions are:
Hibernate Core {5.3.7.Final}
Hibernate Commons Annotations {5.0.4.Final}
And I'm using this library to serialize my java class to json.
com.vladmihalcea:hibernate-types-52:2.17.3
What is weird is that I can save entities to the database (can deserialize) but it cannot build the object back when I try to get it.
#Getter
#Setter
#TypeDefs({
#TypeDef(name = "json", typeClass = JsonType.class)
})
public class NotificationMessage implements Serializable {
private Long id;
private String name = "";
private String type;
}
#Entity
#Table(name = "notification")
#Getter
#Setter
#EntityListeners(AuditingEntityListener.class)
public class Notification {
#Id
#Column(name = "notification_id")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_notification_sequence")
#SequenceGenerator(name = "id_notification_sequence", sequenceName = "id_notification_sequence", allocationSize = 1)
private Long id;
#Column(name = "type", nullable = false)
#Enumerated(EnumType.STRING)
#NotNull
private NotificationType type;
#NotNull
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_uuid", referencedColumnName = "user_uuid")
private User user;
#Type(type = "json")
#Column(name = "message", columnDefinition = "json")
#NotNull
private NotificationMessage message;
#Column(name = "acknowledged")
private boolean acknowledged = false;
#Column(name = "created_date", nullable = false, updatable = false)
#CreatedDate
private LocalDateTime createdDate;
#Column(name = "modified_date")
#LastModifiedDate
private LocalDateTime modifiedDate;
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Notification that = (Notification) o;
return id.equals(that.id);
}
#Override
public int hashCode() {
return Objects.hash(id);
}
}
This is the query I'm running to get the notification back:
#Repository
public interface NotificationRepository extends JpaRepository<Notification, Long>, JpaSpecificationExecutor<Notification> {
#Query("SELECT n FROM Notification n WHERE n.type = :type AND n.acknowledged = false")
List<Notification> findAllByTypeAndAcknowledgedIsFalse(#Param("type") NotificationType type);
}
You must also declare the Hibernate Type to the entity class using the #TypeDef annotation like this:
#Entity
#Table(name = "notification")
#Getter
#Setter
#EntityListeners(AuditingEntityListener.class)
#TypeDef(name = "json", typeClass = JsonType.class)
public class Notification {
I had the same issue as you, and was stuck on it full day, really frustrating. But now I have fixed it. My fixes are:
Match the versions. I was using Hibernate 5.1 and hypersistence-utils-hibernate-55. However, according to the README in the repo, I should use io.hypersistence: hypersistence-utils-hibernate-5: 3.0.1 with Hibernate 5.1. However, in your case, I would try to unify the Hibernate versions first, and then choose the matching version for hypersistence-utils.
Use the correct annotation. In my Entity, I was annotating the field #Type(type = "jsonb"). After changing it to #Type(type = "json"). It started to work.
Hopefully, this can help you.

How to GET data in the JSON format form the DB Repository

I have this JPA Class, where I have 3 columns id, name and date. The Database is already filled with data, where each entry has an id.
#Data
#Entity
#Table(name = "TEST", schema = "TESTSCHEMA")
public class TestDataJpaRecord implements Serializable {
private static final long serialVersionUID = 1L;
TestDataJpaRecord(){
// default constructor
}
public TestDataJpaRecord(
String name,
Date date,
){
this.name = name;
this.date = date;
}
#Id
#Column(name = "ID", nullable = false)
#GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "TEST_SEQUENCE")
#SequenceGenerator(
sequenceName = "TEST_SEQUENCE", allocationSize = 1,
name = "TEST_SEQUENCEx")
private Long id;
#Column(name = "NAME")
private String name;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "DATE")
private Date date;
}
I created a JPA repository for all the data.
public interface TestDataJpaRecordRepository extends JpaRepository<TestDataJpaRecord, Long> {
}
I want to get the data from the DB in a JSON format.
Here is my Rest GET Api. Here I return the data as a string just, but I want to return them as JSON.
#GetMapping(value = "data/{id}")
private ResponseEntity<?> getDataFromTheDB(#PathVariable("id") Long id) {
// get one entry form the DB
TestDataJpaRecord testDataJpaRecord =testDataJpaRecordRepository.findOne(id);
// Here I want to return a JSON instead of a String
return new ResponseEntity<>(testDataJpaRecord.toString(), HttpStatus.OK);
}
Any idea on how I could return the data as JSON and not as a string from the DB?
I would very very much appreciate any suggestion.
If you have Jackson on the classpath which you should if you have used the spring-boot-starter-web then simply:
#GetMapping(value = "data/{id}")
private ResponseEntity<TestDataJpaRecord> getDataFromTheDB(#PathVariable("id") Long id) {
TestDataJpaRecord testDataJpaRecord =testDataJpaRecordRepository.findOne(id);
return new ResponseEntity.ok(testDataJpaRecord);
}
This assumes you have annoted your controller with #RestController rather than #Controller. If not then you can either do that or, annotate your controller method with #ResponseBody.
With Spring Data's web support enabled (which it should be by default with Spring Boot) then you can also simplify as below:
#GetMapping(value = "data/{id}")
private ResponseEntity<TestDataJpaRecord>
getDataFromTheDB(#PathVariable("id") TestDataJpaRecord record) {
return new ResponseEntity.ok(record);
}
See:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#core.web.basic.domain-class-converter

How to solve the MismatchedInputException: Cannot construct instance of `java.util.HashSet` exception

In my program I tried to update the user's email. But it gave me an exception saying
nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
construct instance of java.util.HashSet
But when I update a user with adding skills and email it didn't gave me this exception.
I tried to create a default constructor but it didn't work. I also tried to use Json creator.It also didn't worked for me.I can see that the problem is when I pass the skill set empty this exception is rising.But I don't have a clear idea, how to over come this situation.
This is my Employee entity
#Entity
#Table(name = "Employee")
public class Employee implements Serializable{
private static final long serialVersionUID = -3009157732242241606L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long emp_id;
#Column(name = "emp_fname")
private String emp_fname;
#Column(name = "emp_lname")
private String emp_lname;
#Column(name = "emp_email")
private String emp_email;
#Column(name = "emp_dob")
private Date emp_dob;
#ManyToMany(cascade = CascadeType.MERGE)
#JoinTable(name = "emp_skills",
joinColumns = #JoinColumn(name = "emp_id", referencedColumnName = "emp_id"),
inverseJoinColumns = #JoinColumn(name = "s_id",referencedColumnName = "s_id"))
private Set<Skills> skills;
protected Employee(){
}
public Employee(String emp_fname,String emp_lname,String emp_email,Date emp_dob){
this.emp_fname = emp_fname;
this.emp_lname = emp_lname;
this.emp_email = emp_email;
this.emp_dob = emp_dob;
}
public Employee(Long emp_id,String emp_fname,String emp_lname,String emp_email,Date emp_dob,Set<Skills> skills){
this.emp_id = emp_id;
this.emp_fname = emp_fname;
this.emp_lname = emp_lname;
this.emp_email = emp_email;
this.emp_dob = emp_dob;
this.skills = skills;
}
//all the getters and setter
This is my Skills entity
#Entity
#Table(name = "Skills")
public class Skills implements Serializable {
private static final long serialVersionUID = -3009157732242241606L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long s_id;
#Column(name = "s_name")
private String s_name;
#ManyToMany(mappedBy = "skills",cascade = CascadeType.ALL)
#JsonIgnore
private Set<Employee> employees;
protected Skills(){
}
public Skills(String s_name){
this.s_name = s_name;
}
//all the getters and setter
This is my controller class method to update user
#Autowired
EmployeeRepository repository;
#RequestMapping("/updateEmployee")
#PostMapping("/updateEmployee")
#CrossOrigin
public void updateEmployee(#RequestBody Employee employee, BindingResult bindingResult){
Employee empToBeUpdated = null;
for (Employee emp : repository.findAll()){
if (emp.getEmp_id()==employee.getEmp_id()){
empToBeUpdated = emp;
}
}
if (!employee.getEmp_fname().equals("")&&employee.getEmp_fname()!=null){
empToBeUpdated.setEmp_fname(employee.getEmp_fname());
}
if (!employee.getEmp_lname().equals("")&&employee.getEmp_lname()!=null){
empToBeUpdated.setEmp_lname(employee.getEmp_lname());
}
if (!employee.getEmp_email().equals("")&&employee.getEmp_email()!=null){
empToBeUpdated.setEmp_email(employee.getEmp_email());
}
if (employee.getEmp_dob()!=null){
empToBeUpdated.setEmp_dob(employee.getEmp_dob());
}
if (employee.getSkills()!= null){
empToBeUpdated.setSkills(employee.getSkills());
}
repository.save(empToBeUpdated);
}
Here is the error I'm getting
Resolved
[org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Cannot construct instance of java.util.HashSet
(although at least one Creator exists): no String-argument
constructor/factory method to deserialize from String value ('');
nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
construct instance of java.util.HashSet (although at least one
Creator exists): no String-argument constructor/factory method to
deserialize from String value ('') at [Source: (PushbackInputStream);
line: 1, column: 94] (through reference chain:
com.ems.assignment1.model.Employee["skills"])]
The problem I faced was, the back end expect a skill set but if when the user didn't pick any skills from the skill list the front end passing an empty string.
I resolved this issue by sending an empty array from angular front end if the user didn't select any skills from the skill list.
constructor(private apiService: ApiService) {
this.nullSkills = [];
}
if (this.form.controls.skillsSet.value == null || this.form.controls.skillsSet.value === '') {
this.employee.skills = this.nullSkills;
} else {
this.employee.skills = this.form.controls.skillsSet.value;
}

Jackson JSON infinite recursion without omiting anything from the serialization

I want to serialize and eventually deserialize an object to perform an export/import operation. I use Jackson library because of the extend annotation provided. I do break the infinite recursion by using the latest tags #JsonManagedReference, #JsonBackReference. But the problem here #JsonBackReference does omit the annotated part from the json file so I am not able to set the relationship while importing.
The relationship btwn entities can be shown:
public class A{
#Id
#Column(name = "ID", unique = true, precision = 20)
#SequenceGenerator(name = "a_generator", sequenceName =
"SEQ_A", initialValue = 1, allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator =
"a_generator")
private Long id;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "metricDefinition",
fetch = FetchType.LAZY, orphanRemoval = true)
#Fetch(FetchMode.SELECT)
#NotAudited
#JsonManagedReference
private Set<B> bSet= new HashSet<B>();
}
public class B{
#Id
#Column(name = "id", unique = true, precision = 20)
#SequenceGenerator(name = "b_generator", sequenceName = "seq_b", initialValue = 1, allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "b_generator")
private Long id;
#ManyToOne(cascade = {CascadeType.REFRESH})
#JoinColumn(name = "a_id")
#Fetch(FetchMode.SELECT)
#JsonBackReference(value = "a-b")
private A a;
#ManyToOne(cascade = {CascadeType.REFRESH})
#JoinColumn(name = "ref_a_id")
#Fetch(FetchMode.SELECT)
#JsonBackReference(value = "a-ref")
private A refA;
#Column(name = "is_optional")
#Fetch(FetchMode.SELECT)
private boolean isOptional;
#Column(name = "name")
#Fetch(FetchMode.SELECT)
private String name;
When I serialize any A object, it does serialize the B's included but the referenced A and refA are omitted. So, when I import A object of course the B's are also imported but I do want to the relationship between the objects to be set.
Is there any idea how can I break the infinite recursion without omitting the one side of the reference?
Thanks in advance
I did also try to use statement below according to answers given similar questions but it did not work so I asked the question above.
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
property = "#id")
it does not sufficient to break the circle. You should also add below annotation to the id property of your class.
#JsonProperty("id")
We can try to break the loop either at the Parent end or at the Child end by following 3 ways
Use #JsonManagedReference and #JsonBackReference
Use #JsonIdentityInfo
Use #JsonIgnore
Use #JsonIdentityInfo
#Entity
#Table(name = "nodes")
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class Node {
...
}
#Entity
#Table(name = "relations")
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class Relation {
...
}
Refer more in detail here with the working demo at the end.

Could not write content: failed to lazily initialize a collection of role

I have One-To-Many relationship, here is my code
#Entity
#Table(name = "catalog")
public class Catalog {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "catalog_id")
private int catalog_id;
#NotEmpty
#Size(min = 3, max = 255)
#Column(name = "name", nullable = false)
private String name;
#OneToMany(mappedBy="mycatalogorder")
private List<Order> orders;
#OneToMany(mappedBy="mycatalog")
private List<CatalogItem> items;
// setters and getters
}
#Entity
#Table(name = "catalogitem")
public class CatalogItem {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "catalogitem_id")
private int catalogitem_id;
#NotEmpty
#Size(min = 3, max = 255)
#Column(name = "name", nullable = false)
private String name;
#NotEmpty
#Column(name = "price", nullable = false)
private Double price;
#OneToOne(mappedBy="ordercatalogitem", cascade=CascadeType.ALL)
private OrderItem morderitem;
#ManyToOne
#JoinColumn(name="catalog_id", nullable=false)
private Catalog mycatalog;
// setters and getters
}
#Entity
#Table(name = "orders")
public class Order {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "order_id")
private int order_id;
#NotEmpty
#Size(min = 3, max = 255)
#Column(name = "name", nullable = false)
private String name;
#NotEmpty
#Size(min = 3, max = 1024)
#Column(name = "note", nullable = false)
private String note;
#Temporal(TemporalType.TIMESTAMP)
#DateTimeFormat(pattern = "ddmmYYYY HH:mm:ss")
#Column(name = "created", nullable = false)
private Date created;
#OneToMany(mappedBy="myorder")
private Set<OrderItem> orderItems;
#ManyToOne
#JoinColumn(name="catalog_id", nullable=false)
private Catalog mycatalogorder;
#PrePersist
protected void onCreate() {
created = new Date();
}
// setters and getters
}
#Entity
#Table(name = "orderitem")
public class OrderItem {
#Id
#Column(name="catalogitem_id", unique=true, nullable=false)
#GeneratedValue(generator="gen")
#GenericGenerator(name="gen", strategy="foreign", parameters=#Parameter(name="property", value="catalogitem"))
private int catalogitem_id;
#Column(name = "quantity")
private int quantity;
#OneToOne
#PrimaryKeyJoinColumn
private CatalogItem ordercatalogitem;
#ManyToOne
#JoinColumn(name="order_id", nullable=false)
private Order myorder;
// setters and getters
}
And I am getting the exception:
org.springframework.http.converter.HttpMessageNotWritableException:
Could not write content: failed to lazily initialize a collection of
role: com.example.helios.model.Catalog.items, could not initialize
proxy - no Session; nested exception is
com.fasterxml.jackson.databind.JsonMappingException: failed to lazily
initialize a collection of role:
com.example.helios.model.Catalog.items, could not initialize proxy -
no Session
org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:271)
org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:100)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:222)
org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:183)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:80)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:126)
My versions is:
SpringFramework 4.2.4.RELEASE
Hibernate 4.3.11.Final
Jackson 2.7.4
Jacksontype 2.7.1
This is the normal Hibernate behaviour
In one to many relations, hibernate loads the father entity (Catalog in your case) but it will load the children entities List (List items and List orders in your case) in a LAZY mode
This means you can't access to these objects because they are just proxies and not real objects
This is usefull in order to avoid to load the full DB when you execute a query
You have 2 solution:
Load children entities in EAGER mode (I strongly suggest to you to not do it because you can load the full DB.... but it is something related to your scenario
You don't serialize in your JSON the children entities by using the com.fasterxml.jackson.annotation.JsonIgnore property
Angelo
A third option which can be useful if you don't want to use EAGER mode and load up everything is to use Hibernate::initialize and only load what you need.
Session session = sessionFactory.openSession();
Catalog catalog = (Catalog) session.load(Catalog.class, catalogId);
Hibernate.initialize(shelf);
More information
I had the same problem but a fixed by:
#OneToMany
#JoinColumn(name = "assigned_ingredient", referencedColumnName = "ingredient_id")
#Fetch(FetchMode.JOIN) // Changing the fetch profile you can solve the problem
#Where(clause = "active_ind = 'Y'")
#OrderBy(clause = "meal_id ASC")
private List<Well> ingredients;
you can have more information here: https://vladmihalcea.com/the-best-way-to-handle-the-lazyinitializationexception/
It's caused by an infinite loop when parsing datas to JSON.
You can solve this by using #JsonManagedReference and #JsonBackReference annotations.
Definitions from API :
JsonManagedReference (https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonManagedReference.html) :
Annotation used to indicate that annotated property is part of two-way
linkage between fields; and that its role is "parent" (or "forward")
link. Value type (class) of property must have a single compatible
property annotated with JsonBackReference. Linkage is handled such
that the property annotated with this annotation is handled normally
(serialized normally, no special handling for deserialization); it is
the matching back reference that requires special handling
JsonBackReference: (https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonBackReference.html):
Annotation used to indicate that associated property is part of
two-way linkage between fields; and that its role is "child" (or
"back") link. Value type of the property must be a bean: it can not be
a Collection, Map, Array or enumeration. Linkage is handled such that
the property annotated with this annotation is not serialized; and
during deserialization, its value is set to instance that has the
"managed" (forward) link.
Example:
Owner.java:
#JsonManagedReference
#OneToMany(mappedBy = "owner", fetch = FetchType.EAGER)
Set<Car> cars;
Car.java:
#JsonBackReference
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "owner_id")
private Owner owner;
Another solution is to use #JsonIgnore which will just set null to the field.
Here is my solution for this task with Hibernate. I marked hibernate releation with #JsonIgnore and use custom field for jackson, in which I check if the field is loaded. If you need serialize collection to json then you should manualy call collection getter during hibernate transaciton.
#JsonIgnore
#OneToMany(mappedBy = "myorder")
private List<OrderItem> orderItems = new ArrayList<>();
#JsonProperty(value = "order_items", access = JsonProperty.Access.READ_ONLY)
private List<OrderItem> getOrderItemsList() {
if(Hibernate.isInitialized(this.relatedDictionary)){
return this.relatedDictionary;
} else{
return new ArrayList<>();
}
}
#JsonProperty(value = "order_items", access = JsonProperty.Access.WRITE_ONLY)
private void setOrderItemsList(List<OrderItem> orderItems) {
this.orderItems = orderItems;
}
I know this is an old post but this might still help someone facing a similar issue. To solve the problem, iterate through the list of items and set the lazy-loadable collection to null. Then set your mapper to include NON-NULL
for (Catalog c : allCatalogs) {
c.setItems(null);
}
objectMapper.setSerializationInclusion(Include.NON_NULL)
Using FetchType.LAZY , if still getting the error "Could not write content: failed to lazily initialize a collection of role" , that may be probably caused by somewhere in the logic (perhaps in a controller) , Catalog is being tried to be deserialized that contains list of catalog items which is a proxy but the transaction has already ended to get that.
So create a new model ('CatalogResource' similar to catalog but without the list of items).
Then create a catalogResource object out of the Catalog (which is returned from the query)
public class CatalogResource {
private int catalog_id;
private String name;
private List<Order> orders;
}
I think the best solution to your problem (which also is the simplest) is to set your FetchType to LAZY and simply annotate the oneToMany collection fields using #transient.
Setting FetchType to EAGER isn't a good idea most times.
Best of luck.
"You don't serialize in your JSON the children entities by using the com.fasterxml.jackson.annotation.JsonIgnore property"
Add #JsonIgnore for hibernate lazy loading properties eg. #ManyToOne. That should work