ExtJS, Spring MVC 3 and Hibernate 3.5: CRUD DataGrid Example
Join the DZone community and get the full member experience.
Join For Freethis tutorial will walk through how to implement a crud (create, read, update, delete) datagrid using extjs, spring mvc 3 and hibernate 3.5.
what do we usually want to do with data?
- create (insert)
- read / retrieve (select)
- update (update)
- delete / destroy (delete)
until extjs 3.0 we only could read data using a datagrid. if you wanted to update, insert or delete, you had to do some code to make these actions work. now extjs 3.0 (and newest versions) introduces the ext.data.writer, and you do not need all that work to have a crud grid.
so… what do i need to add in my code to make all these things working together?
in this example, i’m going to use json as data format exchange between the browser and the server.
extjs code
first, you need an ext.data.jsonwriter:
// the new datawriter component.
var writer = new ext.data.jsonwriter({
encode: true,
writeallfields: true
});
where writeallfields identifies that we want to write all the fields from the record to the database. if you have a fancy orm then maybe you can set this to false. in this example, i’m using hibernate, and we have saveorupate method – in this case, we need all fields to updated the object in database, so we have to ser writeallfields to true. this is my record type declaration:
var contact = ext.data.record.create([
{name: 'id'},
{
name: 'name',
type: 'string'
}, {
name: 'phone',
type: 'string'
}, {
name: 'email',
type: 'string'
}]);
now you need to setup a proxy like this one:
var proxy = new ext.data.httpproxy({
api: {
read : 'contact/view.action',
create : 'contact/create.action',
update: 'contact/update.action',
destroy: 'contact/delete.action'
}
});
fyi, this is how my reader looks like:
var reader = new ext.data.jsonreader({
totalproperty: 'total',
successproperty: 'success',
idproperty: 'id',
root: 'data',
messageproperty: 'message' // <-- new "messageproperty" meta-data
},
contact);
the writer and the proxy (and the reader) can be hooked to the store like this:
// typical store collecting the proxy, reader and writer together.
var store = new ext.data.store({
id: 'user',
proxy: proxy,
reader: reader,
writer: writer, // <-- plug a datawriter into the store just as you would a reader
autosave: false // <-- false would delay executing create, update,
//destroy requests until specifically told to do so with some [save] buton.
});
where autosave identifies if you want the data in automatically saving mode (you do not need a save button, the app will send the actions automatically to the server). in this case, i implemented a save button, so every record with new or updated value will have a red mark on the cell left up corner). when the user alters a value in the grid, then a “save” event occurs (if autosave is true). upon the “save” event the grid determines which cells has been altered. when we have an altered cell, then the corresponding record is sent to the server with the ‘root’ from the reader around it. e.g if we read with root “data”, then we send back with root “data”. we can have several records being sent at once. when updating to the server (e.g multiple edits). and to make you life even easier, let’s use the roweditor plugin, so you can easily edit or add new records. all you have to do is to add the css and js files in your page:
<!-- row editor plugin css -->
<link rel="stylesheet" type="text/css" href="/extjs-crud-grid/ext-3.1.1/examples/ux/css/roweditorcustom.css" />
<link rel="stylesheet" type="text/css" href="/extjs-crud-grid/ext-3.1.1/examples/shared/examples.css" />
<link rel="stylesheet" type="text/css" href="/extjs-crud-grid/ext-3.1.1/examples/ux/css/roweditor.css" />
<!-- row editor plugin js -->
<script src="/extjs-crud-grid/ext-3.1.1/examples/ux/roweditor.js"></script>
add the plugin on you grid declaration:
var editor = new ext.ux.grid.roweditor({
savetext: 'update'
});
// create grid
var grid = new ext.grid.gridpanel({
store: store,
columns: [
{header: "name",
width: 170,
sortable: true,
dataindex: 'name',
editor: {
xtype: 'textfield',
allowblank: false
}},
{header: "phone #",
width: 150,
sortable: true,
dataindex: 'phone',
editor: {
xtype: 'textfield',
allowblank: false
}},
{header: "email",
width: 150,
sortable: true,
dataindex: 'email',
editor: {
xtype: 'textfield',
allowblank: false
}})}
],
plugins: [editor],
title: 'my contacts',
height: 300,
width:610,
frame:true,
tbar: [{
iconcls: 'icon-user-add',
text: 'add contact',
handler: function(){
var e = new contact({
name: 'new guy',
phone: '(000) 000-0000',
email: 'new@loianetest.com'
});
editor.stopediting();
store.insert(0, e);
grid.getview().refresh();
grid.getselectionmodel().selectrow(0);
editor.startediting(0);
}
},{
iconcls: 'icon-user-delete',
text: 'remove contact',
handler: function(){
editor.stopediting();
var s = grid.getselectionmodel().getselections();
for(var i = 0, r; r = s[i]; i++){
store.remove(r);
}
}
},{
iconcls: 'icon-user-save',
text: 'save all modifications',
handler: function(){
store.save();
}
}]
});
java code
finally, you need some server side code.
controller:
package com.loiane.web;
@controller
public class contactcontroller {
private contactservice contactservice;
@requestmapping(value="/contact/view.action")
public @responsebody map<string,? extends object> view() throws exception {
try{
list<contact> contacts = contactservice.getcontactlist();
return getmap(contacts);
} catch (exception e) {
return getmodelmaperror("error retrieving contacts from database.");
}
}
@requestmapping(value="/contact/create.action")
public @responsebody map<string,? extends object> create(@requestparam object data) throws exception {
try{
list<contact> contacts = contactservice.create(data);
return getmap(contacts);
} catch (exception e) {
return getmodelmaperror("error trying to create contact.");
}
}
@requestmapping(value="/contact/update.action")
public @responsebody map<string,? extends object> update(@requestparam object data) throws exception {
try{
list<contact> contacts = contactservice.update(data);
return getmap(contacts);
} catch (exception e) {
return getmodelmaperror("error trying to update contact.");
}
}
@requestmapping(value="/contact/delete.action")
public @responsebody map<string,? extends object> delete(@requestparam object data) throws exception {
try{
contactservice.delete(data);
map<string,object> modelmap = new hashmap<string,object>(3);
modelmap.put("success", true);
return modelmap;
} catch (exception e) {
return getmodelmaperror("error trying to delete contact.");
}
}
private map<string,object> getmap(list<contact> contacts){
map<string,object> modelmap = new hashmap<string,object>(3);
modelmap.put("total", contacts.size());
modelmap.put("data", contacts);
modelmap.put("success", true);
return modelmap;
}
private map<string,object> getmodelmaperror(string msg){
map<string,object> modelmap = new hashmap<string,object>(2);
modelmap.put("message", msg);
modelmap.put("success", false);
return modelmap;
}
@autowired
public void setcontactservice(contactservice contactservice) {
this.contactservice = contactservice;
}
}
some observations:
in spring 3, we can get the objects from requests directly in the method parameters using @requestparam. i don’t know why, but it did not work with extjs. i had to leave as an object and to the json-object parser myself. that is why i’m using a util class – to parser the object from request into my pojo class. if you know how i can replace object parameter from controller methods, please, leave a comment, because i’d really like to know that!
service class:
package com.loiane.service;
@service
public class contactservice {
private contactdao contactdao;
private util util;
@transactional(readonly=true)
public list<contact> getcontactlist(){
return contactdao.getcontacts();
}
@transactional
public list<contact> create(object data){
list<contact> newcontacts = new arraylist<contact>();
list<contact> list = util.getcontactsfromrequest(data);
for (contact contact : list){
newcontacts.add(contactdao.savecontact(contact));
}
return newcontacts;
}
@transactional
public list<contact> update(object data){
list<contact> returncontacts = new arraylist<contact>();
list<contact> updatedcontacts = util.getcontactsfromrequest(data);
for (contact contact : updatedcontacts){
returncontacts.add(contactdao.savecontact(contact));
}
return returncontacts;
}
@transactional
public void delete(object data){
//it is an array - have to cast to array object
if (data.tostring().indexof('[') > -1){
list<integer> deletecontacts = util.getlistidfromjson(data);
for (integer id : deletecontacts){
contactdao.deletecontact(id);
}
} else { //it is only one object - cast to object/bean
integer id = integer.parseint(data.tostring());
contactdao.deletecontact(id);
}
}
@autowired
public void setcontactdao(contactdao contactdao) {
this.contactdao = contactdao;
}
@autowired
public void setutil(util util) {
this.util = util;
}
}
contact class – pojo:
package com.loiane.model;
@jsonautodetect
@entity
@table(name="contact")
public class contact {
private int id;
private string name;
private string phone;
private string email;
@id
@generatedvalue
@column(name="contact_id")
public int getid() {
return id;
}
public void setid(int id) {
this.id = id;
}
@column(name="contact_name", nullable=false)
public string getname() {
return name;
}
public void setname(string name) {
this.name = name;
}
@column(name="contact_phone", nullable=false)
public string getphone() {
return phone;
}
public void setphone(string phone) {
this.phone = phone;
}
@column(name="contact_email", nullable=false)
public string getemail() {
return email;
}
public void setemail(string email) {
this.email = email;
}
}
dao class:
package com.loiane.dao;
@repository
public class contactdao implements icontactdao{
private hibernatetemplate hibernatetemplate;
@autowired
public void setsessionfactory(sessionfactory sessionfactory) {
hibernatetemplate = new hibernatetemplate(sessionfactory);
}
@suppresswarnings("unchecked")
@override
public list<contact> getcontacts() {
return hibernatetemplate.find("from contact");
}
@override
public void deletecontact(int id){
object record = hibernatetemplate.load(contact.class, id);
hibernatetemplate.delete(record);
}
@override
public contact savecontact(contact contact){
hibernatetemplate.saveorupdate(contact);
return contact;
}
}
util class:
package com.loiane.util;
@component
public class util {
public list<contact> getcontactsfromrequest(object data){
list<contact> list;
//it is an array - have to cast to array object
if (data.tostring().indexof('[') > -1){
list = getlistcontactsfromjson(data);
} else { //it is only one object - cast to object/bean
contact contact = getcontactfromjson(data);
list = new arraylist<contact>();
list.add(contact);
}
return list;
}
private contact getcontactfromjson(object data){
jsonobject jsonobject = jsonobject.fromobject(data);
contact newcontact = (contact) jsonobject.tobean(jsonobject, contact.class);
return newcontact;
}
)
private list<contact> getlistcontactsfromjson(object data){
jsonarray jsonarray = jsonarray.fromobject(data);
list<contact> newcontacts = (list<contact>) jsonarray.tocollection(jsonarray,contact.class);
return newcontacts;
}
public list<integer> getlistidfromjson(object data){
jsonarray jsonarray = jsonarray.fromobject(data);
list<integer> idcontacts = (list<integer>) jsonarray.tocollection(jsonarray,integer.class);
return idcontacts;
}
}
if you want to see all the code (complete project will all the necessary files to run this app), download it from my github repository: http://github.com/loiane/extjs-crud-grid-spring-hibernate
this was a requested post. i’ve got a lot of comments from my previous crud grid example and some emails. i made some adjustments to current code, but the idea is still the same. i hope i was able answer all the questions.
happy coding!
from http://loianegroner.com/2010/09/extjs-spring-mvc-3-and-hibernate-3-5-crud-datagrid-example/
Opinions expressed by DZone contributors are their own.
Comments