mybat使用注解的方式如@Select寫sql


package com.polymer.app.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import com.polymer.app.entity.BussinessDO;
@Mapper
public interface BussinessMapper {

    BussinessDO selectByPrimaryKey(String paramType);
    
    @Select("select PARAM_TYPE, PARAM_VALUE, DESCR, REMARK from bussiness_param where PARAM_TYPE = #{paramType,jdbcType=VARCHAR}")
    BussinessDO selectByPrimaryKeyNoXml(String paramType);
}
<?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 namespace="com.polymer.app.mapper.BussinessMapper">
  <resultMap id="BaseResultMap" type="com.polymer.app.entity.BussinessDO">
    <id column="PARAM_TYPE" jdbcType="VARCHAR" property="paramType" />
    <result column="PARAM_VALUE" jdbcType="VARCHAR" property="paramValue" />
    <result column="DESCR" jdbcType="VARCHAR" property="descr" />
    <result column="REMARK" jdbcType="VARCHAR" property="remark" />
  </resultMap>
  <sql id="Base_Column_List">
    PARAM_TYPE, PARAM_VALUE, DESCR, REMARK
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from bussiness_param
    where PARAM_TYPE = #{paramType,jdbcType=VARCHAR}
  </select>
</mapper>

 

 

使用注解的方式要注意的地方:使用mybatis操作數據庫有兩種方式xml注入和@注解方式,兩種方式在項目中是可以共存的。

注解方式:使用注解方式默認需要實體類的屬性值和表的列名保持一致,否則無法映射到對應的值;或者使用@Results來手動設置映射關系,優點:看着優雅一點,方便修改,缺點:動態sql語句不好寫,比較麻煩

xml形式:很常用的方式,有各種逆向工程可以生成mapper.xml文件,看着比較亂,各種標簽滿天飛,修改的時候很痛苦。

至於兩者運行效率:不管是xml注入還是@注解注入,都是在程序啟動的時候加載到bean里面的,所以理論上運行效率不會有明顯的區別。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM