Wednesday, 2 December 2015

ServerSide pagination in java using ajax


index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link href="lib/jquery.dataTables.min.css" rel="stylesheet">
<script src="lib/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="lib/jquery.dataTables.min.js" type="text/javascript"></script>
<script type="text/javascript"> 
 
 $(document).ready(function(){ 
       $('#firmtable').dataTable({
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "data.json",
            "type": "GET"
        },

        "columns": [
            {"mData": "id"},
            {"mData": "lineNumber"},
            {"mData": "status"},
            {"mData": "findingType"}
        ]
    });
   
});
</script>
</head>
<body>
    <table id="firmtable" class="display" border="1" >
        <thead>
            <tr>
                <th>id</th>
                <th>lineNumber</th>
                <th>status</th>
                <th>findingType</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</body>
</html>
  

data.json

{ 
 "draw":0,
 "iTotalDisplayRecords":35,
 "iTotalRecords":100,
 "aaData":[  
  {"id":224,"lineNumber":"NA","status":"Assigned","findingType":"Infrastructure"},
  {"id":225,"lineNumber":"NA","status":"Assigned","findingType":"Infrastructure"},
  {"id":226,"lineNumber":"NA","status":"Assigned","findingType":"Infrastructure"},
  {"id":227,"lineNumber":"NA","status":"Assigned","findingType":"Infrastructure"},
  {"id":232,"lineNumber":"NA","status":"Assigned","findingType":"Infrastructure"} 
         ]
}
 
  
Serverside pagination in Hibernate 
 
var oTable =
 $('#productionIssuesTable').dataTable({
   "bRetrieve": true,"processing": true,"serverSide": true,"aaSorting": [],
   "ajax": {
 "url": 'rest/production/getBatchIssueProduction',
 "type": "GET",
 },
 "fnRowCallback": function( nRow, aData, iDisplayIndex ) {  
//first column is checkbox 
      $('td:eq(0)', nRow).html('
<input type="checkbox" class="issues" id="'+nRow.firstChild.textContent+'">');
//second column is anchor tag  
 $('td:eq(1)', nRow).html(' 
<a onclick="updateIssue('+nRow.firstChild.nextSibling.textContent+')">
+nRow.firstChild.nextSibling.textContent+ '</a>');
//last column is action button
 $('td:eq(14)', nRow).html(' 
<button class=" btn btn-success custom waves-effect" 
onclick="assignIssues('+nRow.firstChild.nextSibling.textContent+')" >Assign</button>');
    return nRow;
   
     },
     "bSearchable": true,
     "aoColumnDefs": [
                      { 'bSortable': false, 'aTargets': [ 0,1,2,3,4,5,6,7,8,9,10,11,12] }
                      ],
     "columns" : [{
      "mData" : "check",
     },{
      "mData" : "id",
     }, {
      "mData" : "project"
     }, {
      "mData" : "activityType"
     }, {
      "mData" : "findingType"
     }, {
      "mData" : "sourceCodeFile"
     },{
      "mData" : "lineNumber"
     }, {
      "mData" : "testingInstance"
     },{
      "mData" : "dateRaised"
     }, {
      "mData" : "etdClosure"
     },{
      "mData" : "status.statusCode"
     }, {
      "mData" : "risk"
     },{
      "mData" : "batchId"
     },{
      "mData" : "batchDescription"
     },{
      "mData" : "assign"
     }],

    }); 
 <div class="container-fluid">
     <table class="display table" id="productionIssuesTable">
        <thead>
           <tr><th><input type="checkbox" id="checkall" /></th><td><b>Id</b></td> 
          <td><b>Project</b></td><td><b>Activity Type</b></td><td><b>Finding Type</b></td> 
          <td><b>Source Code Files</b></td><td><b>Line Number</b></td>
          <td><b>Testing Instance</b></td><td><b>Date Raised</b></td>
          <td><b>Expected Date To Close</b></td><td><b>Status</b></td>
          <td><b>Risk</b></td><td><b>Batch Id</b></td><td><b>Batch Description</b></td> 
          <td><b>Assign</b></td></tr> 
        </thead>
        <tbody >
        </tbody>
     </table>
</div> 
 
Create modal 
public class DatatableView {
 private int  iTotalRecords;
 private int  iTotalDisplayRecords;
 private List aaData;
//generate setters and getters
} 
 
JAVA SIDE
 
@Controller
@RequestMapping("production")
public class ProductionController { 

@RequestMapping(value = "/getBatchIssueProduction", method = RequestMethod.GET)
public @ResponseBody DatatableView getBatchIssueProduction(
  @RequestParam(value = "length") String displayReocrds,
  @RequestParam(value = "start") String pageNum,
  @RequestParam(value = "search[value]") String search) {
     try {
 DatatableView view= productionDao
            .getBatchIssueProduction(pageNum,displayReocrds,search);
 return new DatatableView(view.getiTotalRecords(), view.getiTotalDisplayRecords(), view.getAaData());
 } catch (Exception e) {
 return new DatatableView();
  }
 } 
}
 
@Service
@Transactional
public class ProductionDao { 
@SuppressWarnings("unchecked")
public DatatableView getBatchIssueProduction(
  String pageNumber,
  String displayReocrds,
  String search){
  List<BatchIssueProductionsView> batchIssueProductionViews = null;
  List<BatchIssueProductionViewModel> issuesProductionModels= 
         new ArrayList<BatchIssueProductionViewModel>();
  Integer firstValue=Integer.parseInt(pageNumber) ;
  Integer pageSize=Integer.parseInt(displayReocrds);
  Integer noOfRows;Query query;
  try {
     Session session = sessionFactory.getCurrentSession(); 
  if(search==""){
    query = session.createQuery("from BatchIssueProductionsView where status= :status ")
                   .setParameter("status", Constants.OPEN);
  }else{
    query = session.createQuery("from BatchIssueProductionsView where status= :status 
              and (batchDescription like :search or batchId like :search or risk like :search
              or etdClosure like :search  or dateRaised like :search or 
              testingInstance like :search  or lineNumber like :search  or 
              sourceCodeFile like :search or findingType like :search or 
              activityType like :search or project like :search or id like :search) ")
              .setParameter("status", Constants.OPEN).setParameter("search", "%"+search+"%");
  }
  batchIssueProductionViews = query.list();
  noOfRows=batchIssueProductionViews.size();
  query = query.setFirstResult(firstValue);
  query.setMaxResults(pageSize);
  List<BatchIssueProductionsView> batchIssueProductionViews1  = query.list();
  for (BatchIssueProductionsView batchIssueProductionView : batchIssueProductionViews1) {
    issuesProductionModels.add(entityToModelBatchIssueProducction(batchIssueProductionView));       
  }
  DatatableView datatableView = new DatatableView();
  datatableView.setAaData(issuesProductionModels);
  datatableView.setiTotalDisplayRecords(noOfRows);
  datatableView.setiTotalRecords(noOfRows);
  return datatableView;
 } catch (HibernateException e) {
  // TODO Auto-generated catch block
   e.printStackTrace();
   return new DatatableView();
 }
  }
}