Translate

Wednesday, April 18, 2012

MyBatis Generator - Generic Example Class

One of the things that I like about the mapper files created by MyBatis Generator is the ability to set up some basic query filter using the "Example" class that application creates. You can read more about them here. What I don't like about the "Example" classes is that they are specific to the class file that is created to map to the table. So if you have a large project like I do with around 25 main tables you would have 25 different "Example" classes. To get around this I created the following generic "Example" class. Use it in place of the "Example" classes created by the generator.

BaseExample class:

package com.interbase.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Basic database example class
 * @author Richard Golebiowski
 *
 */
public class BaseExample {
    protected List oredCriteria;    
    protected boolean distinct;
    protected String orderByClause;
    protected String table;//table name
    protected String field;//field name
    protected String queryName;//name of the query
    protected BaseCriteria baseCriteria = new BaseCriteria();
    
    public BaseExample() {
        this.oredCriteria = new ArrayList();
    }
    
    /**
     * Used to clear out current criteria
     */
    public void reset(){
        oredCriteria = new ArrayList();
        this.distinct = false;
        this.orderByClause = null;
        this.baseCriteria = new BaseCriteria();       
    }

    public void resetBase() {
        this.baseCriteria = new BaseCriteria();       
    }
    
    public void orCriteria() {
        oredCriteria.add(this.baseCriteria);
    }

    public void andCriterion(String condition, Object value) {
        baseCriteria.addCriterion(condition, value, condition);    
    }
    
    public void andCommonCriterion(String fieldName, String condition, Object value) {
        if(condition.equals("begins with")) {
            condition = "like";
            value = value + "%";
        }
        else if(condition.equals("contains")){
            condition = "like";
            value = "%" + value + "%";     
        }
        else if(condition.equals("ends with")){
            condition = "like";
            value = "%" + value;
        }
        else if(condition.equals("equals")){
             condition = "=";    
        } 
        condition = fieldName + " " + condition;
        baseCriteria.addCriterion(condition, value, condition);    
    }
    
    public void andCriterion(DataViewCriteria dataViewCriteria) {
        if(dataViewCriteria.getValue1() == null) {
            baseCriteria.addCriterion(dataViewCriteria.getFieldName() + " " + dataViewCriteria.getCondition());
        }
        else if(dataViewCriteria.getValue2() == null){
            baseCriteria.addCriterion(dataViewCriteria.getFieldName() + " " + dataViewCriteria.getCondition(), dataViewCriteria.getValue1(), dataViewCriteria.getFieldName());
        }
        else{
            baseCriteria.addCriterion(dataViewCriteria.getFieldName() + " " + dataViewCriteria.getCondition(), dataViewCriteria.getValue1(), dataViewCriteria.getValue2(), dataViewCriteria.getFieldName());        
        }
    }
    
    public void addCriterion(DataViewCriteria dataViewCriteria) {
        this.baseCriteria = new BaseCriteria();
        if(dataViewCriteria.getValue1() == null) {
            baseCriteria.addCriterion(dataViewCriteria.getFieldName() + " " + dataViewCriteria.getCondition());
            oredCriteria.add(baseCriteria);
        }
        else if(dataViewCriteria.getValue2() == null){
            baseCriteria.addCriterion(dataViewCriteria.getFieldName() + " " + dataViewCriteria.getCondition(), dataViewCriteria.getValue1(), dataViewCriteria.getFieldName());
            oredCriteria.add(baseCriteria);
        }
        else{
            baseCriteria.addCriterion(dataViewCriteria.getFieldName() + " " + dataViewCriteria.getCondition(), dataViewCriteria.getValue1(), dataViewCriteria.getValue2(), dataViewCriteria.getFieldName());
            oredCriteria.add(baseCriteria);
        }
    }

    public void addCriterion(String condition, Object value) {
        this.baseCriteria = new BaseCriteria();
        baseCriteria.addCriterion(condition, value, condition);
        oredCriteria.add(baseCriteria);
    }
    
    public void addCriterion(String condition) {
        if (condition == null) {
            throw new RuntimeException("Value for condition cannot be null");
        }
        this.baseCriteria = new BaseCriteria();
        baseCriteria.addCriterion(condition);
    }

    public void addCriterion(String condition, Object value, String property) {
        if (value == null) {
            throw new RuntimeException("Value for " + property + " cannot be null");
        }
        this.baseCriteria = new BaseCriteria();
        baseCriteria.addCriterion(condition, value, property);
    }

    public void addCriterion(String condition, Object value1, Object value2, String property) {
        if (value1 == null || value2 == null) {
            throw new RuntimeException("Between values for " + property + " cannot be null");
        }
        this.baseCriteria = new BaseCriteria();
        baseCriteria.addCriterion(condition, value1, value2,property);
    }

    public void addCriterionForJDBCDate(String condition, Date value, String property) {
        if (value == null) {
            throw new RuntimeException("Value for " + property + " cannot be null");
        }
        addCriterion(condition, new java.sql.Date(value.getTime()), property);
    }

    public void addCriterionForJDBCDate(String condition, List values, String property) {
        if (values == null || values.size() == 0) {
            throw new RuntimeException("Value list for " + property + " cannot be null or empty");
        }
        List dateList = new ArrayList();
        Iterator iter = values.iterator();
        while (iter.hasNext()) {
            dateList.add(new java.sql.Date(iter.next().getTime()));
        }
        addCriterion(condition, dateList, property);
    }

    public void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) {
        if (value1 == null || value2 == null) {
            throw new RuntimeException("Between values for " + property + " cannot be null");
        }
        addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property);
    }    
    

    public List getOredCriteria() {
        return oredCriteria;
    }

    public void setOredCriteria(List oredCriteria) {
        this.oredCriteria = oredCriteria;
    }
    
    public void setDistinct(boolean distinct) {
        this.distinct = distinct;
    }
    
    public boolean isDistinct() {
        return distinct;
    }
    
    public void setOrderByClause(String orderByClause) {
        this.orderByClause = orderByClause;
    }

    public String getOrderByClause() {
        return orderByClause;
    }

    public String getTable() {
        return table;
    }

    public void setTable(String table) {
        this.table = table;
    }

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public String getQueryName() {
        return queryName;
    }

    public void setQueryName(String queryName) {
        this.queryName = queryName;
    }

    public BaseCriteria getBaseCriteria() {
        return baseCriteria;
    }

    public void setBaseCriteria(BaseCriteria baseCriteria) {
        this.baseCriteria = baseCriteria;
    }    
}


BaseCriteria class:

package com.interbase.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
/**
 * Basic criteria class
 * @author Richard Golebiowski
 *
 */
public class BaseCriteria {
 protected List criteria;
 
    public BaseCriteria() {
        this.criteria = new ArrayList();
    } 
    public boolean isValid() {
        return criteria.size() > 0;
    }

    public List getAllCriteria() {
        return criteria;
    }

    public List getCriteria() {
        return criteria;
    }

    public void addCriterion(String condition) {
        if (condition == null) {
            throw new RuntimeException("Value for condition cannot be null");
        }
        criteria.add(new Criterion(condition));
    }

    public void addCriterion(String condition, Object value, String property) {
        if (value == null) {
            throw new RuntimeException("Value for " + property + " cannot be null");
        }
        criteria.add(new Criterion(condition, value));
    }

    public void addCriterion(String condition, Object value1, Object value2, String property) {
        if (value1 == null || value2 == null) {
            throw new RuntimeException("Between values for " + property + " cannot be null");
        }
        criteria.add(new Criterion(condition, value1, value2));
    }

    public void addCriterionForJDBCDate(String condition, Date value, String property) {
        if (value == null) {
            throw new RuntimeException("Value for " + property + " cannot be null");
        }
        addCriterion(condition, new java.sql.Date(value.getTime()), property);
    }

    public void addCriterionForJDBCDate(String condition, List values, String property) {
        if (values == null || values.size() == 0) {
            throw new RuntimeException("Value list for " + property + " cannot be null or empty");
        }
        List dateList = new ArrayList();
        Iterator iter = values.iterator();
        while (iter.hasNext()) {
            dateList.add(new java.sql.Date(iter.next().getTime()));
        }
        addCriterion(condition, dateList, property);
    }

    public void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) {
        if (value1 == null || value2 == null) {
            throw new RuntimeException("Between values for " + property + " cannot be null");
        }
        addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property);
    }    
}



Example usage:

GenericDataService genService = new GenericDataService("DataViewCriteriaMapper");
BaseExample baseExample = new BaseExample();
baseExample.addCriterion("DataViewID =", this.viewID);
//get the criteria for the view
this.lstDataViewCriteria = (List) genService.getListByExample(baseExample);

GenericDataService Class:

package com.dataSpace.service;

public class GenericDataService extends DataService {
 
 public GenericDataService(String dataMapper){
  this.dataMapper = dataMapper;
 }
 
 public GenericDataService() {

 }

 public void switchDataMapper(String dataMapper){
  this.dataMapper = dataMapper;
 }
 

}
DataService Class:

package com.dataSpace.service;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;

import com.interbase.mapper.MyBatisConnectionFactory_INform;
import com.interbase.model.BaseExample;
import  com.utilSpace.util.ExtKeyValuePair;
import  com.utilSpace.util.KeyValuePair;

public abstract class DataService {
 private static final Logger logger = Logger.getLogger(DataService.class);
 protected SqlSessionFactory sqlSessionFactoryINform = MyBatisConnectionFactory_INform.getSqlSessionFactory();
 protected String dataMapper;
 protected boolean errorFlag;
 protected String errorMsg;
 
 public List<Object> getAll(){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")
   List<Object> list = session.selectList(this.dataMapper + ".selectAll");
   return list;
  } finally {
   session.close();
  }    
 }
 
 public List<KeyValuePair> getByMethod(String method){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")
   List<KeyValuePair> list = session.selectList(this.dataMapper + "." + method);
   return list;
  } finally {
   session.close();
  }    
 }
 
 public List<ExtKeyValuePair> getExtByMethod(String method){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")
   List<ExtKeyValuePair> list = session.selectList(this.dataMapper + "." + method);
   return list;
  } finally {
   session.close();
  }    
 }
 
 public List<?> getListByExample(BaseExample baseExample){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")
   List<Object> list = session.selectList(this.dataMapper + ".selectByExample", baseExample);
   return list;
  }catch(Exception e){
   System.out.println(e.getMessage());
   this.errorFlag = true;
   this.errorMsg = e.getMessage();
   return null;
  } finally {
   session.close();
  }    
 }
 
 public List<?> getListFromTableByExample(BaseExample baseExample){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")
   List<Object> list = session.selectList(this.dataMapper + ".selectFromTableByExample", baseExample);
   return list;
  }catch(Exception e){
   System.out.println(e.getMessage());
   return null;
  } finally {
   session.close();
  }    
 }
 
 public List<?> getListByMethodAndExample(String method, BaseExample baseExample){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")
   List<Object> list = session.selectList(this.dataMapper + "." + method, baseExample);
   return list;
  }catch(Exception e){
   System.out.println(e.getMessage());
   return null;
  } finally {
   session.close();
  }    
 }  
 
 public Object getRecordByMethodAndExample(String method, BaseExample baseExample){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")
   Object obj = session.selectOne(this.dataMapper + "." + method, baseExample);
   return obj;
  }catch(Exception e){
   System.out.println(e.getMessage());
   return null;
  } finally {
   session.close();
  }    
 }
 
 public Object getByMethodWithID(String method, Integer id){
  SqlSession session = sqlSessionFactoryINform.openSession();
  try {
   Object obj = session.selectOne(this.dataMapper + "." + method, id);
   return obj;
  }catch(Exception e){
   System.out.println(e.getMessage());
   return null;
  } finally {
   session.close();
  }   
 }
  
 public Object getRecordByExample(BaseExample baseExample){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   this.errorFlag = false;
   Object obj = session.selectOne(this.dataMapper + ".selectByExample", baseExample);
   return obj;
  }catch(Exception e){
   this.errorFlag = true;
   return null;
  } finally {
   session.close();
  }    
 } 
 
 public Object getRecordByQueryExample(BaseExample baseExample){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   Object obj = session.selectOne(this.dataMapper + "." + baseExample.getQueryName(), baseExample);
   return obj;
  } finally {
   session.close();
  }    
 } 
 
 public Object getByID(Integer id){
  SqlSession session = sqlSessionFactoryINform.openSession();
  try {
   Object obj = session.selectOne(this.dataMapper + ".selectByPrimaryKey", id);
   return obj;
  }catch(Exception e){
   System.out.println(e.getMessage());
   return null;
  } finally {
   session.close();
  }   
 }
 
 public void updateByID(Object obj){
  SqlSession session = sqlSessionFactoryINform.openSession();
  try {
   session.update(this.dataMapper + ".updateByPrimaryKey", obj);
   session.commit();
  }catch(Exception e){
   System.out.println(e.getMessage());
  } finally {
   session.close();
  } 
 }
 
 public Object insert(Object obj){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   session.insert(this.dataMapper + ".insert", obj);
   session.commit();
  } catch(Exception e){
   System.out.println(e.getMessage());
  }finally {
   session.close();
  } 
  return obj;  
 }
 
 public void deleteByID(Integer id){
  SqlSession session = sqlSessionFactoryINform.openSession();
  try {
   this.errorFlag = false;
   session.delete(this.dataMapper + ".deleteByPrimaryKey", id);
   session.commit();
  }catch(Exception e){
   this.errorFlag = true;
   logger.error(e.getMessage());
  } finally {
   session.close();
  } 
 } 
 
 public void deleteByExample(BaseExample baseExample){
  SqlSession session = sqlSessionFactoryINform.openSession();
  try {
   this.errorFlag = false;
   session.delete(this.dataMapper + ".deleteByExample", baseExample);
   session.commit();
  }catch(Exception e){
   this.errorFlag = true;
   logger.error(e.getMessage());
  } finally {
   session.close();
  } 
 } 
 
 public List<ExtKeyValuePair> selectAllKeyValue(String source){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")
   List<ExtKeyValuePair> list = session.selectList(this.dataMapper + ".selectAllKeyValue", source);
   return list;
  }catch(Exception e){
   System.out.println(e.getMessage());
   return null;   
  } finally {
   session.close();
  }
 }
 
 public List<ExtKeyValuePair> getFRomTableByMethod(String source, String method){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")
   List<ExtKeyValuePair> list = session.selectList(this.dataMapper + "." + method, source);
   return list;
  } finally {
   session.close();
  }    
 }
 
 /**
  * Select records from the database with the field specified by the "field" property returned as "Value"
  * @param baseExample
  * @return
  */
 public ExtKeyValuePair loadFieldAsValue(BaseExample baseExample){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   Object kvp = session.selectOne(this.dataMapper + ".loadFieldAsValue", baseExample);
   return (ExtKeyValuePair) kvp;
  }catch(Exception e){
   System.out.println(e.getMessage());
   return null;   
  } finally {
   session.close();
  }
 }
 
 /**
  * Select records from the database with the field specified by the "field" property returned as "Value"
  * @param baseExample
  * @return
  */
 public  List<ExtKeyValuePair> getFieldAsValue(BaseExample baseExample){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")   
   List<ExtKeyValuePair> list = session.selectList(this.dataMapper + ".loadFieldAsValue", baseExample);
   return list;
  }catch(Exception e){
   System.out.println(e.getMessage());
   return null;   
  } finally {
   session.close();
  }
 }
 /**
  * Select records from the database with the field specified by the "field" property returned as "Value"
  * @param baseExample
  * @return
  */
 public  List<ExtKeyValuePair> getFieldAsDescValue(BaseExample baseExample){
  SqlSession session = this.sqlSessionFactoryINform.openSession();
  try {
   @SuppressWarnings("unchecked")   
   List<ExtKeyValuePair> list = session.selectList(this.dataMapper + ".loadFieldAsDescValue", baseExample);
   return list;
  }catch(Exception e){
   System.out.println(e.getMessage());
   return null;   
  } finally {
   session.close();
  }
 }

 public boolean isErrorFlag() {
  return errorFlag;
 }

 public void setErrorFlag(boolean errorFlag) {
  this.errorFlag = errorFlag;
 }

 public String getErrorMsg() {
  return errorMsg;
 }

 public void setErrorMsg(String errorMsg) {
  this.errorMsg = errorMsg;
 }
 
}

3 comments:

  1. very nice! just what I needed

    ReplyDelete
  2. Nice example! I am new to mybatis. Could you please post the code for GenericDataService.java and DataViewCriteria.java?

    ReplyDelete
  3. this is so nice post . i really enjoy this .

    ReplyDelete

Thank you for commenting!