针对Sequence主键而言åQŒåœ¨æ‰§è¡Œinsert sqlå‰å¿…™åÀLŒ‡å®šä¸€ä¸ªä¸»é”®å€¼ç»™è¦æ’入的记录åQŒå¦‚Oracleã€DB2åQŒå¯ä»¥é‡‡ç”¨å¦‚下酾|®æ–¹å¼ï¼š
<insert id="add" parameterType="vo.Category">
<selectKey resultType="java.lang.Short" order="BEFORE" keyProperty="id">
SELECT SEQ_TEST.NEXTVAL FROM DUAL
</selectKey>
insert into category (name_zh, parent_id,
show_order, delete_status, description
)
values (#{nameZh,jdbcType=VARCHAR},
#{parentId,jdbcType=SMALLINT},
#{showOrder,jdbcType=SMALLINT},
#{deleteStatus,jdbcType=BIT},
#{description,jdbcType=VARCHAR}
)
</insert>
针对自增主键的表åQŒåœ¨æ’入时ä¸éœ€è¦ä¸»é”®ï¼Œè€Œæ˜¯åœ¨æ’入过½E‹è‡ªåŠ¨èŽ·å–一个自增的主键åQŒæ¯”如MySQLåQŒå¯ä»¥é‡‡ç”¨å¦‚下两¿Ué…¾|®æ–¹å¼ï¼š
<insert id="add" parameterType="vo.Category" useGeneratedKeys="true" keyProperty="id">
insert into category (name_zh, parent_id,
show_order, delete_status, description
)
values (#{nameZh,jdbcType=VARCHAR},
#{parentId,jdbcType=SMALLINT},
#{showOrder,jdbcType=SMALLINT},
#{deleteStatus,jdbcType=BIT},
#{description,jdbcType=VARCHAR}
)
</insert>
�/span>
<insert id="add" parameterType="vo.Category">
<selectKey resultType="java.lang.Short" order="AFTER" keyProperty="id">
SELECT LAST_INSERT_ID() AS id
</selectKey>
insert into category (name_zh, parent_id,
show_order, delete_status, description
)
values (#{nameZh,jdbcType=VARCHAR},
#{parentId,jdbcType=SMALLINT},
#{showOrder,jdbcType=SMALLINT},
#{deleteStatus,jdbcType=BIT},
#{description,jdbcType=VARCHAR}
)
</insert>
在æ’å…¥æ“作完æˆä¹‹åŽï¼Œå‚æ•°categoryçš„id属性就已ç»è¢«èµ‹å€égº†
1.把hibernate下的dialect包全部拷è´åˆ°mybatis包的jdbc目录下,如下图所½Cºï¼š
2.定义一个ResultSetHandler Interceptor
package cn.machi.utils;
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
@Intercepts( {@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
public class DiclectResultSetHandlerInterceptor implements Interceptor
{
public Object intercept(Invocation invocation) throws Throwable
{
FastResultSetHandler resultSet = (FastResultSetHandler)invocation.getTarget();
RowBounds rowBounds = (RowBounds)ReflectUtil.getFieldValue(resultSet,
"rowBounds");
if (rowBounds.getLimit() > 0
&& rowBounds.getLimit() < RowBounds.NO_ROW_LIMIT)
{
ReflectUtil.setFieldValue(resultSet, "rowBounds", new RowBounds());
}
return invocation.proceed();
}
public Object plugin(Object target)
{
return Plugin.wrap(target, this);
}
public void setProperties(Properties properties)
{
}
}
3.定义一个StatementHandler的Interceptor
package cn.machi.utils;
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
@Intercepts( {@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})})
public class DiclectStatementHandlerInterceptor implements Interceptor
{
private static final String DIALECT = "org.apache.ibatis.jdbc.dialect.OracleDialect";
public Object intercept(Invocation invocation) throws Throwable
{
RoutingStatementHandler statement = (RoutingStatementHandler)invocation.getTarget();
PreparedStatementHandler handler = (PreparedStatementHandler)ReflectUtil.getFieldValue(statement,
"delegate");
RowBounds rowBounds = (RowBounds)ReflectUtil.getFieldValue(handler,
"rowBounds");
if (rowBounds.getLimit() > 0
&& rowBounds.getLimit() < RowBounds.NO_ROW_LIMIT)
{
BoundSql boundSql = statement.getBoundSql();
String sql = boundSql.getSql();
OracleDialect dialect = (OracleDialect)Class.forName(DIALECT)
.newInstance();
sql = dialect.getLimitString(sql,
rowBounds.getOffset(),
rowBounds.getLimit());
ReflectUtil.setFieldValue(boundSql, "sql", sql);
}
return invocation.proceed();
}
public Object plugin(Object target)
{
return Plugin.wrap(target, this);
}
public void setProperties(Properties properties)
{
}
}
4.定义工具¾c»ReflectUtil
package cn.machi.utils;
imp
imp
imp
imp
imp
public class ReflectUtil
{
private static Logger log = Logger.getLogger(ReflectUtil.class);
private static Object operate(Object obj, String fieldName,
Object fieldVal, String type)
{
Object ret = null;
try
{
// 获得对象¾cÕdž‹
Class<? extends Object> classType = obj.getClass();
// 获得对象的所有属�nbsp;
Field fields[] = classType.getDeclaredFields();
for (int i = 0; i < fields.length; i++)
{
Field field = fields[i];
if (field.getName().equals(fieldName))
{
String firstLetter = fieldName.substring(0, 1)
.toUpperCase(); // 获得和属性对应的getXXX()æ–ÒŽ³•çš„åå?nbsp;
if ("set".equals(type))
{
String setMethodName = "set" + firstLetter
+ fieldName.substring(1); // 获得和属性对应的getXXX()æ–ÒŽ³•
Method setMethod = classType.getMethod(setMethodName,
new Class[] {field.getType()}); // 调用原对象的getXXX()æ–ÒŽ³•
ret = setMethod.invoke(obj, new Object[] {fieldVal});
}
if ("get".equals(type))
{
String getMethodName = "get" + firstLetter
+ fieldName.substring(1); // 获得和属性对应的setXXX()æ–ÒŽ³•çš„åå?nbsp;
Method getMethod = classType.getMethod(getMethodName,
new Class[] {});
ret = getMethod.invoke(obj, new Object[] {});
}
return ret;
}
}
}
catch (Exception e)
{
log.warn("reflect error:" + fieldName, e);
}
return ret;
}
public static Object getVal(Object obj, String fieldName)
{
return operate(obj, fieldName, null, "get");
}
public static void setVal(Object obj, String fieldName, Object fieldVal)
{
operate(obj, fieldName, fieldVal, "set");
}
private static Method getDeclaredMethod(Object object, String methodName,
Class<?>[] parameterTypes)
{
for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass())
{
try
{
//superClass.getMethod(methodName, parameterTypes);
return superClass.getDeclaredMethod(methodName, parameterTypes);
}
catch (NoSuchMethodException e)
{
//Method ä¸åœ¨å½“剾cÕd®šä¹? ¾l§ç®‹å‘上转型
}
}
return null;
}
private static void makeAccessible(Field field)
{
if (!Modifier.isPublic(field.getModifiers()))
{
field.setAccessible(true);
}
}
private static Field getDeclaredField(Object object, String filedName)
{
for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass())
{
try
{
return superClass.getDeclaredField(filedName);
}
catch (NoSuchFieldException e)
{
//Field ä¸åœ¨å½“剾cÕd®šä¹? ¾l§ç®‹å‘上转型
}
}
return null;
}
public static Object invokeMethod(Object object, String methodName,
Class<?>[] parameterTypes, Object[] parameters)
throws InvocationTargetException
{
Method method = getDeclaredMethod(object, methodName, parameterTypes);
if (method == null)
{
throw new IllegalArgumentException("Could not find method ["
+ methodName + "] on target [" + object + "]");
}
method.setAccessible(true);
try
{
return method.invoke(object, parameters);
}
catch (IllegalAccessException e)
{
}
return null;
}
public static void setFieldValue(Object object, String fieldName,
Object value)
{
Field field = getDeclaredField(object, fieldName);
if (field == null)
throw new IllegalArgumentException("Could not find field ["
+ fieldName + "] on target [" + object + "]");
makeAccessible(field);
try
{
field.set(object, value);
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
public static Object getFieldValue(Object object, String fieldName)
{
Field field = getDeclaredField(object, fieldName);
if (field == null)
throw new IllegalArgumentException("Could not find field ["
+ fieldName + "] on target [" + object + "]");
makeAccessible(field);
Object result = null;
try
{
result = field.get(object);
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
return result;
}
}
5.æ›´æ–°mapper configurationæ–‡äšgåQŒæ·»åŠ å¦‚ä¸‹å‡ æ¡ï¼Œæ³¨æ„plugins在整个configurationæ–‡äšgä¸çš„™åºåº
<plugins>
<plugin interceptor="functionPoint.db.DiclectStatementHandlerInterceptor"/>
<plugin interceptor="functionPoint.db.DiclectResultSetHandlerInterceptor"/>
</plugins>
6.使用æ–ÒŽ³•åŒmybatis逻辑分页åQŒæ‹¦æˆªå™¨ä¼šè‡ªåŠ¨æ‹¦æˆªæ‰§è¡ŒSQLçš„åœ°æ–¹ï¼ŒåŠ ä¸Šåˆ†é¡µä»£ç åQ?/strong>
getSqlSession().selectList(mapId, queryKey,new RowBounds(pageId, pageSize));