Mybatis實戰-各種乾貨分享

工作以來有感於現在企業的持久層框架基本上會選擇mybatis來進行數據庫操作,因此在這裏總結下mybatis的常用的方法,下面的這篇文章將會就開發中常用的mybaits操作數據庫的相關技巧性知識進行總結,不說總結的百分之百吧,基本上開發過程涉及到mybaits操作數據庫方面的知識應該都會總結到,對於簡單的基本上不會講解過多,希望能幫助到有需要的人。

Mybatis的常用的配置

通常呢,絕大部分的其他框架集成Mybatis都會涉及到一下的兩個配置文件,一個配置文件通常命名爲sqlMapConfig.xml,一個命名爲mybatis-config.xml

sqlMapConfig.xml的內容如下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
	<settings>
		<setting name="cacheEnabled" value="true" />
		<setting name="lazyLoadingEnabled" value="true" />
		<setting name="multipleResultSetsEnabled" value="true" />
		<setting name="useColumnLabel" value="true" />
		<setting name="useGeneratedKeys" value="false" />
		<setting name="autoMappingBehavior" value="PARTIAL" />
		<setting name="defaultExecutorType" value="SIMPLE" />
		<setting name="defaultStatementTimeout" value="25000" />
		<setting name="safeRowBoundsEnabled" value="false" />
		<setting name="mapUnderscoreToCamelCase" value="false" />
		<setting name="localCacheScope" value="SESSION" />
		<setting name="jdbcTypeForNull" value="NULL" />
		<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString" />
	</settings>

	<typeHandlers>
		<typeHandler
			handler="xxx.orm.mybatis.SerializableTypeHandler" />
	</typeHandlers>

	<plugins>
		<plugin
			interceptor="xxx.interceptor.mybatis.StatementHandlerInterceptor">
			<property name="prop1" value="prop1" />
			<property name="prop2" value="prop2" />
		</plugin>
		<plugin
			interceptor="xxx.interceptor.mybatis.ResultSetHandlerInterceptor">
			<property name="prop1" value="prop1" />
			<property name="prop2" value="prop2" />
		</plugin>
	</plugins>
</configuration>

mybatis-config.xml的內容如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"
	   default-lazy-init="true">

	<description>Spring jdbc 配置</description>

	<!-- MyBatis配置 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- 自動掃描entity目錄, 省掉Configuration.xml裏的手工配置 -->
		<property name="typeAliasesPackage" value="xxx.domain" />
		<property name="configLocation" value="classpath:/spring-mybatis/sqlMapConfig.xml" />
		<!-- 顯式指定Mapper文件位置 -->
		<property name="mapperLocations" value="classpath:/sql-mapper/*Mapper.xml" />
	</bean>

	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.**.dao" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
	</bean>
</beans>
  • mybatis準備知識
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<!--mapper標籤的作用是將xml文件中操作數據庫中的方法同namespace中定義的接口的方法對應起來-->
<mapper namespace="xxx.dao.yyyDAO" >

<!--這裏resultMap的作用是將實體勒種定義的屬性同數據庫定義的字段一一對應起來,column爲數據庫中定義的字段,property爲實體類型的屬性-->
 <resultMap id="BaseResultMap" type="xxx.domain.yyyPOJO" >
    <result column="groupId" property="groupid" jdbcType="INTEGER" />
    <result column="groupName" property="groupname" jdbcType="VARCHAR" />
    <result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
  </resultMap>

<!--定義的sql片段,可以用來進行復用-->
 <sql id="Base_Column_List">	
     res_id,basic_information,self_assessment,professional_skill
 </sql>  

查詢相關的操作總結

輸入參數爲普通類型的
 ResStandardResume selectByPrimaryKey(Integer resId);

<!--resultMap指定查詢結果對應類型,parameterType指定輸入參數類型,一般爲實體類型-->
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer">
        select
        <include refid="Base_Column_List"/>
        from res_standard_resume
        where res_id = #{resId,jdbcType=INTEGER}
</select>

輸入參數爲實體類型的
ResResume selectByResumeNetID(ResResume resResume);

<select id="selectByResume"resultMap="BaseResultMap"parameterType="xxx.domain.ResResume">
        SELECT
         xxx
        FROM
        res_resume 
        WHERE 1=1
        <if test="resumenetid != null">
            AND resumenetid = #{resumenetid}
        </if>
        <if test="resumeType != null">
            AND resume_type = #{resumeType}
        </if>
 </select>

模糊查詢
 <if test="entity.workbranch != null">
      and a.workbranch LIKE CONCAT(CONCAT('%', #{entity.workbranch}), '%')
 </if>

時間類型
<if test="entity.workyears != null">
            <![CDATA[ and a.workyears >= #{entity.workyears} ]]>
</if>

<if test="entity.beginTime != null">
    <![CDATA[ and a.arrive_time >= #{entity.beginTime} ]]>
</if>
<if test="entity.endTime != null">
    <![CDATA[ and a.arrive_time <= #{entity.endTime} ]]>
</if>

集合的遍歷
<if test="entity.groupIds != null">
    and (
    a.u_group_id IN
    <foreach item="item" index="index" collection="entity.groupIds" open="(" close=")" separator=",">
        #{item}
    </foreach>
    )
</if>

刪除相關

int deleteByPrimaryKey(Integer resId);
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from res_resume
    where res_id = #{resId,jdbcType=INTEGER}
</delete>

插入相關

 int insert(ResResume record);
<insert id="insert" parameterType="xxx.domain.ResResume" useGeneratedKeys="true" keyProperty="resId">
    insert into res_resume (res_id, name, 
    identity_documents, gander
    values (#{resId,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, 
    #{identityDocuments,jdbcType=VARCHAR}, #{gander,jdbcType=VARCHAR}
</insert>

int insertSelective(ResResume record);
<insert id="insertSelective" parameterType="xxx.domain.ResResume" useGeneratedKeys="true" keyProperty="resId">
    insert into res_resume
    <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="resId != null">
            res_id,
        </if>
        <if test="name != null">
            name,
        </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
        <if test="resId != null">
            #{resId,jdbcType=INTEGER},
        </if>
        <if test="name != null">
            #{name,jdbcType=VARCHAR},
        </if>
    </trim>
</insert>

更新相關

int releaseResume(@Param("resId")Integer resId);
<update id="releaseResume" parameterType="java.lang.Integer">
    update res_resume
    <set>
        is_lock = 0,
        u_group_id = null,
        u_group_area = null
    </set>
    where res_id = #{resId,jdbcType=INTEGER}
</update>

int updateByPrimaryKeySelective(ResResume record);
<update id="updateByPrimaryKeySelective" parameterType=xxx.domain.ResResume">
    update res_resume
        <set>
            <if test="name != null and name != ''">
                name = #{name,jdbcType=VARCHAR},
            </if>
            <if test="identityDocuments != null and identityDocuments != ''">
                identity_documents = #{identityDocuments,jdbcType=VARCHAR},
            </if>
        </set>
    where res_id = #{resId,jdbcType=INTEGER}
</update>

int updateByPrimaryKey(ResResume record);
<update id="updateByPrimaryKey" parameterType="xxx.domain.ResResume">
    update res_resume
    set name = #{name,jdbcType=VARCHAR},
    identity_documents = #{identityDocuments,jdbcType=VARCHAR},
    gander = #{gander,jdbcType=VARCHAR},
    where res_id = #{resId,jdbcType=INTEGER}
</update>

未完待續…

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章