Skip to content

Commit

Permalink
init project
Browse files Browse the repository at this point in the history
  • Loading branch information
jsenjobs committed Aug 2, 2016
0 parents commit 7ee31a2
Show file tree
Hide file tree
Showing 26 changed files with 883 additions and 0 deletions.
13 changes: 13 additions & 0 deletions JShy.iml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="aredis-1.4 (2)" level="project" />
</component>
</module>
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# JShy
## 一个轻量级关系对象映射框架
简化了mybatis复杂的xmlMapper的编写过程,使用原生sql驱动运行,上手快

支持事务操作,采用与mybatis类似的结构,默认使用dbcp数据库连接池



## Version
V1.0.0
V1.0.1
Binary file added libs/aredis-1.4.jar
Binary file not shown.
Binary file added libs/commons-collections4-4.1.jar
Binary file not shown.
Binary file added libs/commons-dbcp2-2.1.1.jar
Binary file not shown.
Binary file added libs/commons-logging-1.2.jar
Binary file not shown.
Binary file added libs/commons-pool2-2.4.2.jar
Binary file not shown.
Binary file added libs/log4j-api-2.6.2.jar
Binary file not shown.
Binary file added libs/log4j-core-2.6.2.jar
Binary file not shown.
Binary file added libs/mysql-connector-java-5.1.39-bin.jar
Binary file not shown.
122 changes: 122 additions & 0 deletions src/com/chaos/jim/db/template/Configer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package com.chaos.jim.db.template;

import com.chaos.jim.db.template.annotations.AutoBody;
import com.chaos.jim.db.template.annotations.AutoParameter;
import com.chaos.jim.db.template.dbpool.DBPool;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.lang.reflect.Field;
import java.net.URL;

/**
* Created by jsen on 2016/8/1.
* 注入数据库操作
* 注入事务处理
*/
public class Configer {
private static int length;
private static final Logger logger = LogManager.getLogger(Configer.class);

/**
* 注入sql操作
* @param packageRoot 包含要注入对象的包路径,建议使用含有注入对象的类的包,
* 要注入的类必须有AutoBody注解,
* 被注解的参数要有AutoParameter注解,且为static类型
* @param loop 是否递归遍历
*/
public static void register(String packageRoot, boolean loop) {
URL root = Configer.class.getClassLoader().getResource("");
if (root!=null) {
String path = root.getPath();
if (!path.endsWith(File.separator)) {
path+=File.separator;
}
length = path.length();
try {
parserPath(new File(path+packageRoot.replaceAll(".", File.separator)), loop);
} catch (ClassNotFoundException e) {
logger.error(e.getMessage());
logger.error("ClassNotFound when autoWried the dbm handler field.");
}
} else {
logger.error("Init DB proxy error, url root is empty.");
}
}

public static void register(String packageRoot) {
register(packageRoot, true);
}

@Deprecated
public static void register(Object obj) {
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field:fields) {
if (field.getAnnotation(AutoParameter.class)!=null) {
try {
field.set(obj, DPQuery.autoWried(field.getType()));
} catch (IllegalAccessException e) {
logger.error(e.getMessage());
logger.error("some error happened when autoWried the dbm handler field.");
}
}
}
}

/**
* 注册事务处理,建议在有事务注解时才注册事务
* @param obj 要注册事务的实体类,必须继承于接口,必须标注AutoBody注解
* @param <T> 接口类型,事务注解在接口中的方法进行标注
* @return 注入后的对象
*/
public static <T> T registerTransactional(T obj) {
if (obj.getClass().getAnnotation(AutoBody.class)!=null) {
return DPTransactional.autoWried(obj, obj.getClass().getInterfaces());
}
return obj;
}

@Deprecated
public static <T> T registerField(Class<T> clazz) {
return DPQuery.autoWried(clazz);
}




public static void setDBPool(DBPool dbPool) {
PoolManager.setPool(dbPool);
}



private static void parserPath(File dir, boolean loop) throws ClassNotFoundException {
File[] files = dir.listFiles();
for (File file:files) {
if (file.isFile()) {
if (file.getName().endsWith(".class")) {
String abPath = file.getAbsolutePath();
abPath = abPath.substring(length, abPath.length()-6);
abPath = abPath.replaceAll(File.separator, ".");
Class cla = Class.forName(abPath);
if (cla.getAnnotation(AutoBody.class)!=null) {
Field[] fields = cla.getDeclaredFields();
for (Field field:fields) {
if (field.getAnnotation(AutoParameter.class)!=null) {
try {
field.set(null, DPQuery.autoWried(field.getType()));
} catch (IllegalAccessException e) {
logger.error(e.getMessage());
logger.error("some error happened when autoWried the dbm handler.");
}
}
}
}
}
} else if (loop && file.isDirectory()) {
parserPath(file, loop);
}
}
}
}
115 changes: 115 additions & 0 deletions src/com/chaos/jim/db/template/DPQuery.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package com.chaos.jim.db.template;

import com.chaos.jim.db.template.annotations.Column;
import com.chaos.jim.db.template.annotations.Sql;
import com.chaos.jim.db.template.dbpool.DBPool;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* Created by jsen on 2016/8/1.
* sql执行的动态注入
*/
class DPQuery implements InvocationHandler {
static DBPool dbcpProxy = PoolManager.getPool();
private DPQuery() {
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Sql sql = method.getAnnotation(Sql.class);
final Exception[] exceptions = new Exception[1];
switch (sql.action()) {
case SingleModel:
final Object[] result = new Object[1];
dbcpProxy.executeQuery(sql.sql(), args, resultSet -> {
try {
if (resultSet.next()) {
Class returnType = sql.returnType();
result[0] = returnType.newInstance();
Method[] setMethods = returnType.getMethods();
Column column;
for (Method setMethod:setMethods) {
column = setMethod.getAnnotation(Column.class);
if (column !=null) {
Method dataMethod = resultSet.getClass().getMethod("get"+ column.type(), String.class);
try {
Object dv = dataMethod.invoke(resultSet, column.name());
setMethod.invoke(result[0], dv);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
exceptions[0] = e;
}
});
if (exceptions[0]!=null) {
throw exceptions[0];
}
return result[0];
case ModelList:
List<Object> results = new ArrayList<>();
dbcpProxy.executeQuery(sql.sql(), args, resultSet -> {
Object result1;
Class returnType = sql.returnType();
Method[] objMethods = returnType.getMethods();
Column column;
Map<Method, Column> setMethods = new HashMap<>();
for (Method objMethod:objMethods) {
column = objMethod.getAnnotation(Column.class);
if (column !=null) {
setMethods.put(objMethod, column);
}
}
try {
while (resultSet.next()) {
result1 = returnType.newInstance();
for (Map.Entry<Method, Column> entry:setMethods.entrySet()) {
column = entry.getValue();
Method dataMethod = resultSet.getClass().getMethod("get"+ column.type(), String.class);
try {
Object dv = dataMethod.invoke(resultSet, column.name());
entry.getKey().invoke(result1, dv);
} catch (Exception e) {
e.printStackTrace();
}
}
results.add(result1);
}
} catch (Exception e) {
e.printStackTrace();
exceptions[0] = e;
}
});
if (exceptions[0]!=null) {
throw exceptions[0];
}
return results;
case EffectValue:
return dbcpProxy.update(sql.sql(), args);
}
return null;
}

@SuppressWarnings("unchecked")
static <T> T autoWried(Class<T> mapperInterface) {
ClassLoader classLoader = mapperInterface.getClassLoader();
Class<?>[] interfaces = new Class[]{mapperInterface};
DPQuery proxy = new DPQuery();
try {
return (T) Proxy.newProxyInstance(classLoader, interfaces, proxy);
} catch (ClassCastException e) {
e.printStackTrace();
return null;
}
}
}
48 changes: 48 additions & 0 deletions src/com/chaos/jim/db/template/DPTransactional.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package com.chaos.jim.db.template;

import com.chaos.jim.db.template.annotations.Transactional;
import com.chaos.jim.db.template.dbpool.DBPool;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
* Created by jsen on 2016/8/2.
* 数据库事务处理相关的动态注入
*/
class DPTransactional implements InvocationHandler {
static DBPool dbcpProxy = PoolManager.getPool();

private Object proxied;

private DPTransactional(Object proxied) {
this.proxied = proxied;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
if (method.getAnnotation(Transactional.class) != null) {
dbcpProxy.startTransactional();
try {
result = method.invoke(proxied, args);
dbcpProxy.commitTransaction();
return result;
} catch (Exception e) {
e.printStackTrace();
dbcpProxy.rollbackTransaction();
return result;
}
}
result = method.invoke(proxied, args);
dbcpProxy.release();
return result;
}

@SuppressWarnings("unchecked")
static <T> T autoWried(T obj, Class<?>[] clazzes) {
return (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(),
clazzes, new DPTransactional(obj));
}
}
23 changes: 23 additions & 0 deletions src/com/chaos/jim/db/template/PoolManager.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.chaos.jim.db.template;

import com.chaos.jim.db.template.dbpool.DBPool;
import com.chaos.jim.db.template.dbpool.DBPoolDefault;

/**
* Created by jsen on 2016/8/2.
*/
class PoolManager {
private static DBPool pool = null;
static DBPool getPool() {
if (pool == null) {
pool = new DBPoolDefault();
}
return pool;
}

static void setPool(DBPool pool) {
if (pool == null){
PoolManager.pool = pool;
}
}
}
14 changes: 14 additions & 0 deletions src/com/chaos/jim/db/template/annotations/Actions.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.chaos.jim.db.template.annotations;

/**
* Created by jsen on 2016/8/1.
* sql操作类型
*/
public enum Actions {
// 返回单个数据表模型
SingleModel,
// 返回一个数据列表
ModelList,
// 返回操作影响数
EffectValue
}
13 changes: 13 additions & 0 deletions src/com/chaos/jim/db/template/annotations/AutoBody.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.chaos.jim.db.template.annotations;

import java.lang.annotation.*;

/**
* Created by jsen on 2016/8/1.
* 自动注入类标记
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface AutoBody {
}
13 changes: 13 additions & 0 deletions src/com/chaos/jim/db/template/annotations/AutoParameter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.chaos.jim.db.template.annotations;

import java.lang.annotation.*;

/**
* Created by jsen on 2016/8/1.
* 自动注入属性标记
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface AutoParameter {
}
17 changes: 17 additions & 0 deletions src/com/chaos/jim/db/template/annotations/Column.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.chaos.jim.db.template.annotations;

import java.lang.annotation.*;

/**
* Created by jsen on 2016/8/1.
* 用于set方法表示数据库的一个table属性
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface Column {
//属性名 the true name in the database
String name();
//属性类型 the type value will be called in ResultSet.get$value$() method.
String type();
}
Loading

0 comments on commit 7ee31a2

Please sign in to comment.