ï»??xml version="1.0" encoding="utf-8" standalone="yes"?>中文字幕一区日韩精品,午夜精品久久久99热福利,亚洲午夜精品久久http://www.aygfsteel.com/keweibo/category/50241.html一ä¸? Java 多能 Delphi,Powerbuilder ... zh-cnWed, 30 Nov 2011 09:11:14 GMTWed, 30 Nov 2011 09:11:14 GMT60MyBatis insert操作˜q”回主键(è½?http://www.aygfsteel.com/keweibo/articles/365211.htmlKeKeWed, 30 Nov 2011 08:06:00 GMThttp://www.aygfsteel.com/keweibo/articles/365211.htmlhttp://www.aygfsteel.com/keweibo/comments/365211.htmlhttp://www.aygfsteel.com/keweibo/articles/365211.html#Feedback0http://www.aygfsteel.com/keweibo/comments/commentRss/365211.htmlhttp://www.aygfsteel.com/keweibo/services/trackbacks/365211.html原文:http://289972458.iteye.com/blog/1001851

在ä‹É用MyBatis做持久层æ—Óž¼Œinsert语句默认是不˜q”回记录的主键å€û|¼Œè€Œæ˜¯˜q”回插入的记录条敎ͼ›å¦‚果业务层需要得到记录的主键æ—Óž¼Œå¯ä»¥é€šè¿‡é…ç½®çš„æ–¹å¼æ¥å®Œæˆ˜q™ä¸ªåŠŸèƒ½

针对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º†



Ke 2011-11-30 16:06 发表评论
]]>
mybatis3.05 分页收藏http://www.aygfsteel.com/keweibo/articles/355693.htmlKeKeWed, 03 Aug 2011 09:15:00 GMThttp://www.aygfsteel.com/keweibo/articles/355693.htmlhttp://www.aygfsteel.com/keweibo/comments/355693.htmlhttp://www.aygfsteel.com/keweibo/articles/355693.html#Feedback0http://www.aygfsteel.com/keweibo/comments/commentRss/355693.htmlhttp://www.aygfsteel.com/keweibo/services/trackbacks/355693.html以下內容來自:
http://zhaohe162.blog.163.com/blog/static/38216797201131262952990/

1.把hibernate下的dialect包全部拷贝到mybatis包的jdbc目录下,如下图所½Cºï¼š

mybatis下的分页åQŒæ”¯æŒæ‰€æœ‰çš„æ•°æ®åº?- 断尘伤痕 - æ–­å°˜å±? style=
 



2.定义一个ResultSetHandler  Interceptor

package cn.machi.utils;

import java.sql.Statement;
import java.util.Properties;

import org.apache.ibatis.executor.resultset.FastResultSetHandler;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.RowBounds;

@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;

import java.sql.Connection;
import java.util.Properties;

import org.apache.ibatis.executor.statement.PreparedStatementHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.jdbc.dialect.OracleDialect;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.RowBounds;

@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;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import org.apache.log4j.Logger;


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));


==============================================================
按照上面的做äº?但運行時åÀL‹‹å‡ºç¼ºž®?IN OUT參數之類的錯èª?
後來換了Dialect™åžæ–‡ä»¶å°±OKäº?OracleDialect內容參考自:
http://rapid-framework.googlecode.com/svn/trunk/rapid-framework/src/rapid_framework_common/cn/org/rapid_framework/jdbc/dialect/




]]>
Ö÷Õ¾Ö©Öë³ØÄ£°å£º ¾°µÂÕòÊÐ| Ì«°×ÏØ| ¼¯°²ÊÐ| ²ßÀÕÏØ| ÐÂÌïÏØ| ÄϺÍÏØ| Ö麣ÊÐ| ËÕÄáÌØ×óÆì| ÓÚ¶¼ÏØ| ãôË®ÏØ| ÈÕÍÁÏØ| Ì©Ë³ÏØ| Õű±ÏØ| ÒÇÕ÷ÊÐ| ·½ÕýÏØ| ÌìÆø| ÁéÌ¨ÏØ| ¿â¶ûÀÕÊÐ| ¼ªÁÖÊ¡| °¢Í¼Ê²ÊÐ| ÐÂÔ´ÏØ| ÍòÄþÊÐ| ÃÉÒõÏØ| ÈéɽÊÐ| ÑôÔ­ÏØ| ÆÕ¶¨ÏØ| ¼ÃÑôÏØ| À­ÈøÊÐ| ·îÏÍÇø| ¸ï¼ªÏØ| »ôÁÖ¹ùÀÕÊÐ| ÍþÄþ| ÄÂÀâÊÐ| Ïç³ÇÏØ| »ù¡ÊÐ| ÓñÌïÏØ| ¸ß±®µêÊÐ| ÇìÔÆÏØ| ÁúÉ½ÏØ| ÃñÇÚÏØ| Èð°²ÊÐ|