About Michal Jastak

Michał is a Chief Technology Officer in Java Division of AIS.PL, company developing mostly Web Applications of different kind, usually e-Government related.

JSON – Jackson to the rescue

Sometimes you have to fetch some data from the server in JavaScript, JSON is pretty good choice for this task.

Let’s play with the Employer – Employee – Benefit example from the post JPA Demystified (episode 1) – @OneToMany and @ManyToOne mappings. We will use it inside the web application based on Spring Framework.

Our first controller will return the employees list as the response body, in our case MappingJacksonHttpMessageConverter will be used automagically for converting the value returned by handleGet method to the response send to client.

 

@Controller
@RequestMapping('/employee-list.json')
public class EmployeeListController {
    @Autowired
    private EmployerDAO employerDAO;

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public List<Employee> handleGet(@RequestParam('employerId') Long employerId) {
        return employerDAO.getEmployees(employerId);
    }
}

When we try to fetch the data for the first time, we encounter beautiful exception: JsonMappingException: Infinite recursion (StackOverflowError) – caused by bi-directional references between the Employer – Employee – Benefit.

Looking for the possible solution, I’ve found a note Handle bi-directional references using declarative method(s), and after reading it, I’ve corrected the domain entities in following way:

@Entity
@Table(name = 'EMPLOYERS')
public class Employer implements Serializable {
...
    @JsonManagedReference('employer-employee')
    @OneToMany(mappedBy = 'employer', cascade = CascadeType.PERSIST)
    public List

                       getEmployees() {
        return employees;
    }
...
}

@Entity
@Table(name = 'EMPLOYEES')
public class Employee implements Serializable {
...
    @JsonManagedReference('employee-benefit')
    @OneToMany(mappedBy = 'employee', cascade = CascadeType.PERSIST)
    public List

                        getBenefits() {
        return benefits;
    }

    @JsonBackReference('employer-employee')
    @ManyToOne(optional = false)
    @JoinColumn(name = 'EMPLOYER_ID')
    public Employer getEmployer() {
        return employer;
    }
...
}

@Entity
@Table(name = 'BENEFITS')
public class Benefit implements Serializable {
...
    @JsonBackReference('employee-benefit')
    @ManyToOne(optional = false)
    @JoinColumn(name = 'EMPLOYEE_ID')
    public Employee getEmployee() {
        return employee;
    }
...
}

After performing the above changes, I could finally enjoy the JSON response returned by my code:

[{'id':1, 'benefits':[{'name':'Healthy Employees', 'id':1, 'type':'HEALTH_COVERAGE', 'startDate':1104534000000, 'endDate':null}, {'name':'Gold Autumn','id':2,'type':'RETIREMENT_PLAN','startDate':1104534000000,'endDate':null},{'name':'Always Secured','id':3,'type':'GROUP_TERM_LIFE','startDate':1104534000000,'endDate':null}],'firstName':'John'},{'id':2,'benefits':[],'firstName':'Mary'},{'id':3,'benefits':[],'firstName':'Eugene'}]

And as usual some links for the dessert:

Reference: JSON – Jackson to the rescue from our JCG partner Micha? Ja?tak at the Warlock’s Thoughts blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

One Response to "JSON – Jackson to the rescue"

  1. Blaise Doughan says:

    FYI – EclipseLink JAXB (MOXy) also supports bidirectional relationships in its JSON-binding through our inverse reference mapping. As EclipseLink is also a JPA provider it is a use case we’re very familiar with:

    - MOXy’s @XmlInverseReference is now Truly Bidirectional

Leave a Reply


− five = 1



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books