Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
com.enterprisemath.dao.relational.MyBatisEntityDao Maven / Gradle / Ivy
package com.enterprisemath.dao.relational;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.enterprisemath.dao.filter.Criterium;
import com.enterprisemath.dao.filter.Filter;
import com.enterprisemath.dao.filter.Order;
import com.enterprisemath.utils.Dates;
import com.enterprisemath.utils.DomainUtils;
import com.enterprisemath.utils.Month;
import com.enterprisemath.utils.ValidationUtils;
import java.util.Collection;
/**
* Implementation of entity dao which is using my batis framework.
*
* @author radek.hecl
*
*/
public class MyBatisEntityDao implements EntityDao {
/**
* Factory for sql sessions.
*/
private SqlSessionFactory sqlSessionFactory;
/**
* Creates new instance.
*/
private MyBatisEntityDao() {
}
/**
* Guards this object to be consistent. Throws exception if this is not the case.
*/
private void guardInvariants() {
ValidationUtils.guardNotNull(sqlSessionFactory, "sqlSessionFactory cannot be null");
}
@Override
public void insertEntity(Entity entity) {
SqlSession session = sqlSessionFactory.openSession();
try {
MyBatisEntityMapper mapper = session.getMapper(MyBatisEntityMapper.class);
mapper.insertEntityCore(entity.getCode(), entity.getName(), entity.getCreatedTimestamp(), entity.getParentCode(), entity.getType());
if (!entity.getJoins().isEmpty()) {
Map> sortedJoins = getTaleJoins(entity.getJoins());
for (String table : sortedJoins.keySet()) {
mapper.insertEntityJoins(entity.getCode(), table, sortedJoins.get(table));
}
}
} finally {
session.close();
}
}
@Override
public void deleteEntity(String code) {
SqlSession session = sqlSessionFactory.openSession();
try {
MyBatisEntityMapper mapper = session.getMapper(MyBatisEntityMapper.class);
mapper.deleteEntity(code);
} finally {
session.close();
}
}
@Override
public List selectEntities(Set joinsData, Filter filter) {
SqlSession session = sqlSessionFactory.openSession();
try {
MyBatisEntityMapper mapper = session.getMapper(MyBatisEntityMapper.class);
// fetch data
List> cores = mapper.selectEntities(transformJoinLabels(joinsData), transformFilter(filter));
if (cores == null || cores.isEmpty()) {
return Collections.emptyList();
}
// map data
List res = new ArrayList();
for (Map core : cores) {
core = convertKeysToLowerKeys(core);
Entity.Builder builder = new Entity.Builder().
setCode((String) core.get("code")).
setName((String) core.get("name")).
setParentCode((String) core.get("parent_code")).
setType((String) core.get("type")).
setCreatedTimestamp((Date) core.get("created_timestamp"));
for (String label : joinsData) {
Object obj = core.get(label.replaceFirst("\\.", "_"));
if (obj != null && obj instanceof java.sql.Timestamp) {
obj = DomainUtils.copyDate((Date) obj);
}
builder.addJoin(label, obj);
}
res.add(builder.build());
}
return res;
} finally {
session.close();
}
}
@Override
public long countEntities(Set joinsData, List> criteria) {
SqlSession session = sqlSessionFactory.openSession();
try {
// extract tables from join data
Set tables = new HashSet();
for (String join : joinsData) {
tables.add(join.split("\\.")[0]);
}
// transform criteria
Set> transformedCriteria = new HashSet>();
for (Criterium crit : criteria) {
transformedCriteria.add(Criterium.create(transformColumnLabel(crit.getColumn()), crit.getOperator(), crit.getValue()));
}
//
MyBatisEntityMapper mapper = session.getMapper(MyBatisEntityMapper.class);
return mapper.countEntities(tables, transformedCriteria);
} finally {
session.close();
}
}
@Override
public void updateEntityName(String code, String name) {
SqlSession session = sqlSessionFactory.openSession();
try {
MyBatisEntityMapper mapper = session.getMapper(MyBatisEntityMapper.class);
mapper.updateEntityName(code, name);
} finally {
session.close();
}
}
@Override
public void insertEntityJoins(String code, String table, Map values) {
SqlSession session = sqlSessionFactory.openSession();
try {
MyBatisEntityMapper mapper = session.getMapper(MyBatisEntityMapper.class);
mapper.insertEntityJoins(code, table, values);
} finally {
session.close();
}
}
@Override
public void updateEntityJoin(String code, String join, Object value) {
SqlSession session = sqlSessionFactory.openSession();
try {
// create entity object to validate new join object
new Entity.Builder().
setCode("VE").
setName("Vaildation entity").
setType("DOES_NOT_MATTER").
setCreatedTimestamp(Dates.createDate(2000, Month.JANUARY, 1)).
addJoin(join, value).
build();
String[] parts = join.split("\\.", 2);
MyBatisEntityMapper mapper = session.getMapper(MyBatisEntityMapper.class);
mapper.updateEntityJoin(code, parts[0], parts[1], value);
} finally {
session.close();
}
}
@Override
public void deleteEntityJoins(String code, String table) {
SqlSession session = sqlSessionFactory.openSession();
try {
MyBatisEntityMapper mapper = session.getMapper(MyBatisEntityMapper.class);
mapper.deleteEntityJoins(code, table);
} finally {
session.close();
}
}
@Override
public void insertProfiles(Collection entityProfiles) {
SqlSession session = sqlSessionFactory.openSession();
try {
MyBatisEntityMapper mapper = session.getMapper(MyBatisEntityMapper.class);
for (EntityProfile profile : entityProfiles) {
mapper.insertProfile(profile.getCode(), profile.getEntityCode(), profile.getProfileKey(), profile.getProfileValue());
}
} finally {
session.close();
}
}
@Override
public void deleteProfiles(List> criteria) {
SqlSession session = sqlSessionFactory.openSession();
try {
MyBatisEntityMapper mapper = session.getMapper(MyBatisEntityMapper.class);
mapper.deleteProfiles(criteria);
} finally {
session.close();
}
}
@Override
public List selectProfiles(Filter filter) {
SqlSession session = sqlSessionFactory.openSession();
try {
MyBatisEntityMapper mapper = session.getMapper(MyBatisEntityMapper.class);
// fetch data
List> profs = mapper.selectProfiles(filter);
if (profs == null || profs.isEmpty()) {
return Collections.emptyList();
}
// map data
List res = new ArrayList();
for (Map prof : profs) {
prof = convertKeysToLowerKeys(prof);
res.add(EntityProfile.create(prof.get("code"), prof.get("entity_code"), prof.get("profile_key"), prof.get("profile_value")));
}
return res;
} finally {
session.close();
}
}
/**
* Transform join labels into the table columns format.
* Key of the map is table name. Values of the set are joins.
*
* @param joins join labels to be transformed
* @return transformed joins
*/
private Map> transformJoinLabels(Set joins) {
Map> res = new HashMap>();
for (String join : joins) {
String[] parts = join.split("\\.", 2);
if (!res.containsKey(parts[0])) {
res.put(parts[0], new HashSet());
}
res.get(parts[0]).add(parts[1]);
}
return res;
}
/**
* Transforms filter into table columns format.
*
* @param filter filter to be transformed
* @return column filter format
*/
private Filter transformFilter(Filter filter) {
Filter.Builder res = new Filter.Builder();
res.setFrom(filter.getFrom());
res.setLimit(filter.getLimit());
for (Criterium crit : filter.getCriteria()) {
res.addCriterium(Criterium.create(transformColumnLabel(crit.getColumn()), crit.getOperator(), crit.getValue()));
}
for (Order ord : filter.getOrders()) {
res.addOrder(Order.create(transformColumnLabel(ord.getColumn()), ord.getDirection()));
}
return res.build();
}
/**
* Transforms column label to the filter format.
*
* @param source source label
* @return output label
*/
private String transformColumnLabel(String source) {
if (!source.contains(".")) {
return "a." + source;
}
return source;
}
/**
* Returns entity joins sorted to the tables.
*
* @param joins original entity joins
* @return joins sorted to table
*/
private Map> getTaleJoins(Map joins) {
Map> res = new HashMap>();
for (Map.Entry entry : joins.entrySet()) {
String[] parts = entry.getKey().split("\\.", 2);
if (!res.containsKey(parts[0])) {
res.put(parts[0], new HashMap());
}
res.get(parts[0]).put(parts[1], entry.getValue());
}
return res;
}
/**
* Converts keys in the one map to the lower case.
*
* @param value type
* @param source source map
* @return map with lower case keys
*/
private Map convertKeysToLowerKeys(Map source) {
Map res = new HashMap(source.size());
for (String key : source.keySet()) {
res.put(key.toLowerCase(), source.get(key));
}
return res;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
/**
* Creates new instance.
*
* @param sqlSessionFactory factory for sql sessions
* @return created instance
*/
public static MyBatisEntityDao create(SqlSessionFactory sqlSessionFactory) {
MyBatisEntityDao res = new MyBatisEntityDao();
res.sqlSessionFactory = sqlSessionFactory;
res.guardInvariants();
return res;
}
}