Search code examples
javamodel-view-controllerbackbone.jspojoutility

How to create a Backbone model from a POJO or a JavaBean?


I have a POJO named Person.java, is there any bash or utility that allows me to create a Backbone model named person.js from Person.java so I don't have to re-type all the fields again?

Thank you.


Solution

  • If you're using the Jackson JSON Processor http://jackson.codehaus.org/ to translate your POJO model code to JSON, you should not have to recreate any of the properties on your Backbone model. A simple example:

    public String getPerson(){
        Person personPOJOInstance = new Person();
        ObjectMapper mapper = new ObjectMapper();
        StringWriter sw = new StringWriter();
    
        try{
            mapper.writeValue(sw, personPOJOInstance);
            pojoJSON = sw.getBuffer().toString();
        }
        catch(IOException exc){
    
        }
        return pojoJSON;
    }
    

    You don't even have to worry about doing this if you're using a Spring MVC controller and mark your controller method with the following @RequestMapping annotation, like so:

    @RequestMapping(method= RequestMethod.GET, produces = "application/json", value="/path/to/controller/method")
    public @ResponseBody getPerson(){
        return new Person();
    }
    

    Finally, your backbone model is as simple as:

    var Person = Backbone.Model.extend({
        url: '/path/to/controller/method'
    });
    

    You're not required to specify any default attributes on your Backbone model, although it may be a good idea to do so.

    Now when you fetch the model, you can access any of the properties that came from the original POJO on the Backbone model like this:

    //instantiate and fetch your model.
    var person = new Person();
    person.fetch();
    ...
    //access properties on your model.
    var name = person.get('name');