mybatis-mysql小优化

原文:http://blog.csdn.net/jinzhencs/article/details/51656548

1.查询某条记录是否存在

<!-- 查询s是否被创建过:Uuid,name,deleteFlag -->
    <select id="isCreated" parameterType="XXEntity" resultType="Integer">
        select 1 from table 
        where uuid = #{uuid} 
        and   name = #{name} 
        and   delete_flag = #{deleteFlag} 
        limit 1
    </select>

第一个是select 1,第二个是limit 1,即找到一条符合的记录就返回 而不用全表查询. 
注意此处必须返回Integer,因为当记录为空会返回null,则报空指针异常。 
使用Integer然后对它进行判断:

if(result!=null && result==1){
    Syso("记录存在");
}

2.mybatis配置自动扫描别名TypeAliases

<bean id="sqlSessionFactory"
        class="com.wlqq.cloud.core.mybaties.PackagesSqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />

        <!-- 此处利用spring扫描 然后自动映射成别名,可以使用更复杂的配置 -->
        <property name="typeAliasesPackage" value="com.wlqq.cloud.**.entity" />

        <property name="plugins">
            <list>
                <ref bean="myBatisPageIntercept" />
                <ref bean="myBatisJsonIntercept" />
            </list>
        </property>
    </bean>

即需要在sqlsession配置一个property:typeAliasesPackage 
然后指定扫描位置为实体包.那么之后使用别名就直接可以用类名了; 
比如 com.mylearn.test.entity.User.Java 
那么配置之后直接paramType=’User’即可。需要注意多个Entity包下类取名不要相同.

原文地址:https://www.cnblogs.com/shihaiming/p/6100878.html