Last active
August 8, 2018 02:50
-
-
Save chanchal-357/739fe9a5eb8a282ac979fd7500ec74a5 to your computer and use it in GitHub Desktop.
JQGrid java Backend
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.test.basic.dao; | |
import com.test.model.BaseDO; | |
import com.test.model.GridRequest; | |
import com.test.model.GridResponse; | |
public interface BasicDAO { | |
public BaseDO get(Class klass, Number id); | |
public Long save(BaseDO baseDO); | |
public BaseDO update(BaseDO baseDO); | |
public BaseDO getLastStudent(Class klass); | |
public BaseDO getLastProspectus(Class klass); | |
@SuppressWarnings("rawtypes") | |
public <T>GridResponse fetch(Class<?> klass, String primaryKey, GridRequest gridRequest); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.test.basic.dao; | |
import java.lang.reflect.InvocationTargetException; | |
import java.lang.reflect.Method; | |
import java.math.BigInteger; | |
import java.text.DateFormat; | |
import java.text.ParseException; | |
import java.text.SimpleDateFormat; | |
import java.util.ArrayList; | |
import java.util.Date; | |
import java.util.HashMap; | |
import java.util.Iterator; | |
import java.util.LinkedHashMap; | |
import java.util.LinkedList; | |
import java.util.List; | |
import java.util.Map; | |
import org.hibernate.Criteria; | |
import org.hibernate.HibernateException; | |
import org.hibernate.Query; | |
import org.hibernate.Session; | |
import org.hibernate.SessionFactory; | |
import org.hibernate.Transaction; | |
import org.hibernate.criterion.CriteriaSpecification; | |
import org.hibernate.criterion.Order; | |
import org.hibernate.criterion.Projections; | |
import org.hibernate.criterion.Restrictions; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.stereotype.Repository; | |
import com.test.basic.util.Util; | |
import com.test.init.CustomException; | |
import com.test.model.Account; | |
import com.test.model.BaseDO; | |
import com.test.model.GridRequest; | |
import com.test.model.GridResponse; | |
import com.test.model.Loan; | |
@Repository | |
public class BasicDAOImpl implements BasicDAO { | |
protected final Logger logger = LoggerFactory.getLogger(this.getClass()); | |
@Autowired | |
private SessionFactory sessionFactory; | |
public SessionFactory getSessionFactory() { | |
return sessionFactory; | |
} | |
public SessionFactory getSessionFactory() { | |
return this.sessionFactory; | |
} | |
@SuppressWarnings("rawtypes") | |
public BaseDO get(Class klass, Number id) { | |
Session session = getSessionFactory().openSession(); | |
try { | |
return (BaseDO) session.get(klass, id); | |
} finally { | |
session.flush(); | |
session.close(); | |
} | |
} | |
public Long save(BaseDO baseDO) { | |
Session session = getSessionFactory().openSession(); | |
try { | |
return (Long) session.save(baseDO); | |
} | |
catch(Throwable t){ | |
t.printStackTrace(); | |
return null; | |
} | |
finally { | |
session.flush(); | |
session.close(); | |
} | |
} | |
public BaseDO update(BaseDO baseDO) { | |
Session session = getSessionFactory().openSession(); | |
try { | |
return (BaseDO) session.merge(baseDO); | |
} finally { | |
session.flush(); | |
session.close(); | |
} | |
} | |
public void updateOnly(BaseDO baseDO) { | |
Session session = getSessionFactory().openSession(); | |
try { | |
session.update(baseDO); | |
} finally { | |
session.flush(); | |
session.close(); | |
} | |
} | |
@SuppressWarnings({ "rawtypes", "unchecked" }) | |
public <T> GridResponse fetch(Class<?> klass, String primaryKey, GridRequest gridRequest) { | |
boolean needJoin = false; | |
GridResponse<T> response = new GridResponse<T>(); | |
Session session = getSessionFactory().openSession(); | |
try { | |
// FIND TOTAL COUNT | |
Criteria criteria = session.createCriteria(klass); | |
if(gridRequest.rows > 0){ | |
if (gridRequest.filterColumns.length > 0) { | |
for (int i = 0; i < gridRequest.filterColumns.length; i++) { | |
if (gridRequest.filterColumns[i] == null) | |
continue; | |
needJoin = gridRequest.filterColumns[i].contains("."); | |
Object value = getConvertedValue(klass, gridRequest.filterColumns[i], gridRequest.filterValues[i]); | |
if (value instanceof String) { | |
criteria.add(Restrictions.like(gridRequest.filterColumns[i], value + "%")); | |
} else { | |
criteria.add(Restrictions.eq(gridRequest.filterColumns[i], value)); | |
} | |
} | |
} | |
addValueInCriteria(criteria, gridRequest, klass); | |
if (needJoin) { | |
addJoinCriteria(klass, criteria); | |
} | |
criteria.setProjection(Projections.count(primaryKey)); | |
List list = criteria.list(); | |
for (Iterator it = list.iterator(); it.hasNext();) { | |
response.setRecords((Long) it.next()); | |
response.setTotal(new Double(Math.ceil(new Long(response.getRecords()).doubleValue() / gridRequest.rows)).intValue()); | |
} | |
} | |
else { | |
//if all records to be fetched. | |
} | |
criteria = session.createCriteria(klass); | |
if (needJoin) { | |
addJoinCriteria(klass, criteria); | |
} | |
criteria.setFirstResult(gridRequest.offset).setMaxResults(gridRequest.rows); | |
if (gridRequest.sord != null) { | |
if ("asc".equals(gridRequest.sord) && !gridRequest.sidx.contains(".")) { | |
criteria.addOrder(Order.asc(gridRequest.sidx)); | |
} else if (!gridRequest.sidx.contains(".")) { | |
criteria.addOrder(Order.desc(gridRequest.sidx)); | |
} | |
} | |
if (gridRequest.filterColumns.length > 0) { | |
for (int i = 0; i < gridRequest.filterColumns.length; i++) { | |
if (gridRequest.filterColumns[i] == null) | |
continue; | |
Object value = getConvertedValue(klass, gridRequest.filterColumns[i], gridRequest.filterValues[i]); | |
if (value instanceof String) { | |
criteria.add(Restrictions.like(gridRequest.filterColumns[i], value + "%")); | |
} else { | |
criteria.add(Restrictions.eq(gridRequest.filterColumns[i], value)); | |
} | |
} | |
} | |
addValueInCriteria(criteria, gridRequest, klass); | |
//ADD selected fields | |
{ | |
if(gridRequest.fields.length>0){ | |
for(String field:gridRequest.fields){ | |
criteria.setProjection(Projections.projectionList() | |
.add(Projections.property(field))); | |
} | |
} | |
} | |
List<T> results = criteria.list(); | |
response.setRows(results); | |
response.setPage(gridRequest.offset / gridRequest.rows + 1); | |
} catch (HibernateException e) { | |
logger.error("Error while getting total record. Error:", e); | |
} finally { | |
session.close(); | |
} | |
return response; | |
} | |
@SuppressWarnings("deprecation") | |
public void addJoinCriteria(Class<?> klass, Criteria criteria) { | |
if (Loan.class == klass) { | |
criteria.createAlias("member", "member", CriteriaSpecification.LEFT_JOIN); | |
criteria.add(Restrictions.eqProperty("member.memberID", "member_id")); | |
} | |
} | |
@SuppressWarnings("rawtypes") | |
private static Map<String, Class> fieldClassMap = new HashMap<>(); | |
static { | |
fieldClassMap.put("test.model.Accountmember.firstName", String.class); | |
fieldClassMap.put("test.model.Loanmember.firstName", String.class); | |
} | |
@SuppressWarnings({ "rawtypes", "unchecked" }) | |
private Object getConvertedValue(Class klass, String fieldName, String value) { | |
Class fieldClass = fieldClassMap.get(klass.getName() + fieldName); | |
if ((fieldName) != null && | |
( fieldName.endsWith("firstName") | |
|| fieldName.endsWith("middleName") | |
|| fieldName.endsWith("lastName") | |
|| fieldName.endsWith("fatherName") | |
|| fieldName.endsWith("employee_Id") | |
)){ | |
return value; | |
} | |
try { | |
if (fieldClass == null) { | |
fieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1); | |
if (fieldName.contains(".")) { | |
fieldClass = Long.class; | |
fieldClassMap.put(klass.getName() + fieldName, Long.class); | |
} else if (!fieldName.contains("PK.")) { | |
String getter = "get" + fieldName; | |
Method method = klass.getMethod(getter, new Class[] {}); | |
fieldClass = method.getReturnType(); | |
fieldClassMap.put(klass.getName() + fieldName, fieldClass); | |
} else { | |
fieldClass = Long.class; | |
fieldClassMap.put(klass.getName() + fieldName, Long.class); | |
} | |
} | |
if (fieldClass.equals(String.class)) { | |
return value; | |
} else if (fieldClass.equals(Long.class)) { | |
return new Long(value); | |
} else if (fieldClass.equals(Integer.class)) { | |
return new Integer(value); | |
} | |
else if (fieldClass.equals(Double.class)) { | |
return new Double(value); | |
} else if (fieldClass.equals(Float.class)) { | |
return new Float(value); | |
} else if (fieldClass.equals(BigInteger.class)) { | |
return new BigInteger(value); | |
} else if (fieldClass.equals(Boolean.class)) { | |
return new Boolean(value); | |
} else if (fieldClass.equals(Date.class)) { | |
return Util.parseUIDate(value); | |
} | |
} catch (NumberFormatException e) { | |
e.printStackTrace(); | |
} catch (NoSuchMethodException e) { | |
e.printStackTrace(); | |
} catch (SecurityException e) { | |
e.printStackTrace(); | |
} | |
return null; | |
} | |
private Criteria addValueInCriteria(Criteria criteria, GridRequest request, Class klass) { | |
if (request.infield != null && request.invalues != null && request.invalues.length() > 0) { | |
List list = new ArrayList<>(); | |
String[] values = request.invalues.split(","); | |
Object obj = null; | |
for (String s : values) { | |
if(obj == null) | |
obj = getConvertedValue(klass, request.infield, s); | |
if(obj instanceof String) | |
list.add(s); | |
else if(obj instanceof Integer) | |
list.add(new Integer(s)); | |
else | |
list.add(new Long(s)); | |
} | |
criteria.add(Restrictions.in(request.infield, list)); | |
} | |
if (request.infield != null && request.notinvalues != null && request.notinvalues.length() > 0) { | |
List list = new ArrayList<>(); | |
String[] values = request.notinvalues.split(","); | |
Object obj = null; | |
for (String s : values) { | |
if(obj == null) | |
obj = getConvertedValue(klass, request.infield, s); | |
if(obj instanceof String) | |
list.add(s); | |
else if(obj instanceof Integer) | |
list.add(new Integer(s)); | |
else | |
list.add(new Long(s)); | |
} | |
criteria.add(Restrictions.not(Restrictions.in(request.infield, list))); | |
} | |
if (request.btwfield != null && request.btwvalues != null && request.btwvalues.length() > 0) { | |
List<Long> list = new ArrayList<>(); | |
String[] values = request.btwvalues.split(","); | |
criteria.add(Restrictions.not(Restrictions.between(request.infield, getConvertedValue(klass, request.infield, values[0]), getConvertedValue(klass, request.infield, values[1])))); | |
} | |
if (request.betweenfield != null && request.betweenvalues != null && request.betweenvalues.length() > 0) { | |
String[] values = request.betweenvalues.split(","); | |
criteria.add((Restrictions.between(request.betweenfield, getConvertedValue(klass, request.betweenfield, values[0]), getConvertedValue(klass, request.betweenfield, values[1])))); | |
} | |
return criteria; | |
} | |
/** | |
* @param Provide At Least 2 Fields | |
*/ | |
@SuppressWarnings("unchecked") | |
protected <T> List<T> query(String query, Class<T> returnType, String... fields) throws CustomException { | |
Session session = getSessionFactory().openSession(); | |
try { | |
Query qry = session.createSQLQuery(query); | |
List<Object[]> list = qry.list(); | |
List<T> returnList = new LinkedList<T>(); | |
for (Object[] obj : list) { | |
T returnObj = returnType.newInstance(); | |
int i = 0; | |
for (String field : fields) { | |
setValueInObject(returnType, field, returnObj, obj[i++]); | |
} | |
returnList.add(returnObj); | |
} | |
return returnList; | |
} catch (Exception e) { | |
e.printStackTrace(); | |
throw new CustomException("Query Failed", e); | |
} | |
finally{ | |
session.close(); | |
} | |
} | |
@SuppressWarnings("unchecked") | |
private void setValueInObject(Class returnType, String field, Object returnObj, Object value) throws NoSuchMethodException, | |
SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { | |
if (value == null) { | |
return; | |
} | |
if (field.contains(".")) { | |
String fstField = field.substring(0, field.indexOf(".")); | |
String getField = "get" + Character.toUpperCase(fstField.charAt(0)) + fstField.substring(1); | |
String setField = "set" + Character.toUpperCase(fstField.charAt(0)) + fstField.substring(1); | |
Method getMethod = returnType.getMethod(getField, new Class[] {}); | |
Object fstObj = getMethod.invoke(returnObj, new Class[] {}); | |
if (fstObj == null) { | |
fstObj = getMethod.getReturnType().newInstance(); | |
returnType.getMethod(setField, fstObj.getClass()).invoke(returnObj, fstObj); | |
} | |
returnType = fstObj.getClass(); | |
field = field.substring(field.indexOf(".") + 1); | |
returnObj = fstObj; | |
} | |
field = "set" + Character.toUpperCase(field.charAt(0)) + field.substring(1); | |
if (value instanceof Number) { | |
try { | |
returnType.getMethod(field, Long.class).invoke(returnObj, ((Number) value).longValue()); | |
return; | |
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | |
| InvocationTargetException e) { | |
try { | |
returnType.getMethod(field, Integer.class).invoke(returnObj, ((Number) value).intValue()); | |
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | |
| InvocationTargetException e1) { | |
try { | |
returnType.getMethod(field, Double.class).invoke(returnObj, ((Number) value).doubleValue()); | |
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | |
| InvocationTargetException e2) { | |
try { | |
returnType.getMethod(field, BigInteger.class).invoke(returnObj, new BigInteger(value.toString())); | |
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | |
| InvocationTargetException e3) { | |
try { | |
returnType.getMethod(field, Boolean.class).invoke(returnObj, new Boolean(value.toString())); | |
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | |
| InvocationTargetException e4) { | |
e3.printStackTrace(); | |
} | |
} | |
} | |
} | |
} | |
return; | |
} | |
try { | |
returnType.getMethod(field, String.class).invoke(returnObj, value.toString()); | |
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e3) { | |
try { | |
returnType.getMethod(field, Date.class).invoke(returnObj, dbDateFormat.parse(value.toString())); | |
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | |
| InvocationTargetException | ParseException e5) { | |
e3.printStackTrace(); | |
} | |
} | |
} | |
private static DateFormat dbDateFormat = new SimpleDateFormat("yyyy-MM-dd"); | |
@SuppressWarnings({ "rawtypes", "unchecked" }) | |
protected List<Map> queryToMapList(String query, String... fields) throws CustomException { | |
List<Map> returnList = new ArrayList<>(); | |
Session session = getSessionFactory().openSession(); | |
try { | |
Query qry = session.createSQLQuery(query); | |
List<Object[]> list = qry.list(); | |
for (Object[] objArr : list) { | |
Map map = new LinkedHashMap<>(); | |
int i = 0; | |
for (String field : fields) { | |
Object obj = objArr[i]; | |
map.put(field, obj); | |
i++; | |
} | |
returnList.add(map); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
throw new CustomException("Query Failed", e); | |
} | |
finally{ | |
session.close(); | |
} | |
return returnList; | |
} | |
public void delete(BaseDO baseDO) { | |
Session session = getSessionFactory().openSession(); | |
try { | |
session.delete(baseDO); | |
} finally { | |
session.flush(); | |
session.close(); | |
} | |
} | |
} | |
/* | |
public GridResponse<T> fetchadvancesalary(GridRequest gridRequest) { | |
return super.<T> fetch(T.class, "id", gridRequest); | |
}*/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.test.model; | |
public class GridRequest { | |
public GridRequest(){ | |
} | |
// total records | |
public int total; | |
public int rows; | |
// page size | |
public int records; | |
public String sidx; | |
public String filterOp; | |
public String[] fields = new String[]{}; | |
public String[] filterColumns = new String[]{}; | |
public String[] filterValues = new String[]{}; | |
public String sord; | |
public int offset; | |
public Class klass; | |
public String primary_key; | |
public String invalues; | |
public String notinvalues; | |
public String infield; | |
public String btwfield; | |
public String btwvalues; | |
public String betweenfield; | |
public String betweenvalues; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.test.model; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class GridResponse<T> { | |
//current page | |
private int page; | |
//total records | |
private int total; | |
//page size | |
private long records; | |
//records for current page | |
private List<T> rows = new ArrayList<>(); | |
public int getPage() { | |
return page; | |
} | |
public void setPage(int page) { | |
this.page = page; | |
} | |
public int getTotal() { | |
return total; | |
} | |
public void setTotal(int total) { | |
this.total = total; | |
} | |
public long getRecords() { | |
return records; | |
} | |
public void setRecords(long records) { | |
this.records = records; | |
} | |
public List<T> getRows() { | |
return rows; | |
} | |
public void setRows(List<T> rows) { | |
this.rows = rows; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment