diff options
author | Jérémy Zurcher <jeremy@asynk.ch> | 2017-03-23 17:10:39 +0100 |
---|---|---|
committer | Jérémy Zurcher <jeremy@asynk.ch> | 2017-03-23 17:10:39 +0100 |
commit | 724efad67fe61d2c02c41af24ebc352eb79ff2f8 (patch) | |
tree | 777e62835ca2f6901d8d2542e328fcea403f9680 /java/MyMyBatis/src/AbstractDAO.java | |
parent | bb1caf716a18b65fa42d7bed2369b66a0837d977 (diff) | |
download | share-724efad67fe61d2c02c41af24ebc352eb79ff2f8.zip share-724efad67fe61d2c02c41af24ebc352eb79ff2f8.tar.gz |
java : add MyMyBatis
Diffstat (limited to 'java/MyMyBatis/src/AbstractDAO.java')
-rw-r--r-- | java/MyMyBatis/src/AbstractDAO.java | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/java/MyMyBatis/src/AbstractDAO.java b/java/MyMyBatis/src/AbstractDAO.java new file mode 100644 index 0000000..916d511 --- /dev/null +++ b/java/MyMyBatis/src/AbstractDAO.java @@ -0,0 +1,75 @@ +package ch.asynk; + +import java.util.List; + +import org.apache.ibatis.session.SqlSession; +import org.apache.ibatis.exceptions.PersistenceException; + +public abstract class AbstractDAO<TObject, TMapper> +{ + public final int DAO_ERROR = -1; + protected Class<TMapper> mapperClass = null; + + public static boolean logErrors = true; + private static SqlConnection conn = null; + + static { + conn = new SqlConnection(); + MapperRegistration.registerMappers(conn); + } + + static public SqlConnection getSqlConnection() { return conn; } + + protected abstract class CallBack<TRet, TMapper> + { + public abstract TRet call(TMapper m); + } + + protected int execInt(boolean commit, CallBack<Integer, TMapper> cb) + { + int status = DAO_ERROR; + SqlSession session = conn.openSqlSession(); + try { + status = cb.call(session.getMapper(mapperClass)); + if (commit) session.commit(); + } + catch(PersistenceException e) { + if (commit) session.rollback(); + if (logErrors) conn.error(e); + } + finally { session.close(); } + return status; + } + + protected TObject execObject(boolean commit, CallBack<TObject, TMapper> cb) + { + TObject obj = null; + SqlSession session = conn.openSqlSession(); + try { + obj = cb.call(session.getMapper(mapperClass)); + if (commit) session.commit(); + } + catch(PersistenceException e) { + if (commit) session.rollback(); + if (logErrors) conn.error(e); + } + finally { session.close(); } + return obj; + } + + protected List<TObject> execObjects(boolean commit, CallBack<List<TObject>, TMapper> cb) + { + List<TObject> list = null; + SqlSession session = conn.openSqlSession(); + try { + list = cb.call(session.getMapper(mapperClass)); + if (commit) session.commit(); + } + catch(PersistenceException e) { + if (commit) session.rollback(); + if (logErrors) conn.error(e); + } + finally { session.close(); } + return list; + } +} |