mybatis使用xml進行增刪改查代碼解析,mybatisxml

來源:互聯網
上載者:User

mybatis使用xml進行增刪改查代碼解析,mybatisxml

MyBatis是支援普通sql查詢、預存程序和進階映射的持久層架構。

MyBatis消除了幾乎所有的JDBC代碼和參數的手工設定以及對結果集的檢索封裝。

MyBatis可以使用 簡單的XML或註解用於配置和原始映射,將介面和Java的POJO(Plain Old Java Objects 普通的Java對象)映射成資料庫中的記錄。

每一個Mybatis應用程式都以一個sqlSessionFactory對象的執行個體為核心。

sqlSessionFactory對象的執行個體可以通過sqlSessionFactoryBuilder對象來獲得。sqlSessionFactoryBuilder對象可以通過xml設定檔,或從以往使用管理中準備好的Configuration類執行個體中來構建sqlSessionFactory對象。

【樣本:使用配置類擷取sqlSessionFactory】
DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();TransactionFactory transactionFactory = new JdbcTransactionFactory();//環境Environment environment = new Environment("development", transactionFactory, dataSource);Configuration configuration = new Configuration(environment);//映射器類configuration.addMapper(BlogMapper.class);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);

注意這種情況下配置是添加映射器類。映射器類是Java類,這些類包含SQL映射語句的註解從而避免了xml檔案的依賴,但是xml映射仍然在 大多數進階映射(比如:嵌套join映射)時需要。

出於這樣的原因,如果存在xml設定檔的話,MyBatis將會自動尋找和載入一個對等的XML檔案(這種情況下,基於類路徑下的BlogMapper.class類的類名,那麼BlogMapper.xml將會被載入–即class 與 XML在同一個檔案目錄下。如果非,則需要手動設定載入xml)。

【1】基本增刪改查xml配置
<?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.web.mapper.userMapper">   <!-- 可以解決model屬性名稱與資料表中column列名不一致問題 jdbcType一定要大寫 -->     <resultMap type="User" id="UserMap">    <id property="id" column="id" javaType="int" jdbcType="INTEGER"/>    <result property="name" column="username" javaType="string" jdbcType="VARCHAR"/>    <result property="age" column="age" javaType="int" jdbcType="INTEGER"/>   </resultMap>   <!--   注意這裡的result,如果column == property 則可以直接返回Java object。   如果屬性名稱與列名不一致,解決方案如下:   1. 使用resultMap;    2.返回hashmap ;    3.查詢語句使用別名   -->   <select id="getUser" parameterType="int" resultMap="UserMap">    select * from t_user where id=#{id}   </select>   <delete id="deleteUser" parameterType="int" >    delete from t_user where id=#{id}   </delete>   <update id="updateUser" parameterType="User" >    update t_user set username=#{name},age=#{age} where id=#{id}   </update>   <insert id="insertUser" parameterType="User" >    insert into t_user(username,age) values(#{name},#{age})   </insert>   <!-- model's attr(name) different from column(username), so the result use UserMap -->   <select id="getUsers" resultMap="UserMap">    select * from t_user   </select></mapper>

註冊到mybatis.xml [當與spring結合時,將不需要這個設定檔]

mybatis的設定檔

<?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>  <properties resource="jdbc.properties"/>  <!-- 配置實體類的別名 -->  <typeAliases>    <!-- <typeAlias type="com.web.model.User" alias="User"/> -->    <package name="com.web.model"/>  </typeAliases><!--   development : 開發模式  work : 工作模式 -->  <environments default="development">    <environment id="development">      <transactionManager type="JDBC" />      <dataSource type="POOLED">        <property name="driver" value="${driver}" />        <property name="url" value="${url}" />        <property name="username" value="${username}" />        <property name="password" value="${password}" />      </dataSource>    </environment>  </environments>  <mappers>    <mapper resource="com/web/mapper/userMapper.xml"/>    <mapper resource="com/web/mapper/orderMapper.xml"/>    <mapper class="com.web.mapperClass.UserMapper"/>  </mappers></configuration>
【2】通過SqlSessionFactory拿到session

這裡使用xml檔案擷取sqlSessionFactory和sqlSession。

public static SqlSessionFactory getFactory(){/* flow the src dir*/String resource = "mybatis.xml";/*MybatisUtils.class.getResourceAsStream(resource)----- it's wrong !!!!     * please distinguish the two up and down      * */InputStream inputStream = MybatisUtils.class.getClassLoader().getResourceAsStream(resource);SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);return factory;}SqlSession session = factory.openSession(true);//預設手動提交;/*  兩種解決方式:  1.factory.opensession(true);  2.session.commit();  */
【3】增刪改查後台測試代碼
/*use sql xml not annotation*/@Test  public void testAdd(){SqlSession session = MybatisUtils.getFactory().openSession();String statement = "com.web.mapper.userMapper.insertUser";/*return the effect rows*/int insert= session.insert(statement, new User("tom5", 15));/*default is not auto commit*/session.commit(true);session.close();System.out.println("effect rows.."+insert);}@Test  public void testSelect(){/*set auto commit ,which equals to the above*/SqlSession session = MybatisUtils.getFactory().openSession(true);String statement = "com.web.mapper.userMapper.getUser";/*return the effect rows*/User user = session.selectOne(statement, 3);System.out.println("effect rows.."+user);}@Test  public void testUpdate(){SqlSession session = MybatisUtils.getFactory().openSession(true);String statement = "com.web.mapper.userMapper.updateUser";/*return the effect rows*/int update= session.update(statement, new User(3,"tom4", 13));System.out.println("effect rows.."+update);}@Test  public void testDelete(){SqlSession session = MybatisUtils.getFactory().openSession();String statement = "com.web.mapper.userMapper.deleteUser";/*return the effect rows*/int delete= session.delete(statement, 6);/* commit by yourself*/session.commit();System.out.println("effect rows.."+delete);session.close();}@Test  public void testGetUsers(){SqlSession session = MybatisUtils.getFactory().openSession();String statement = "com.web.mapper.userMapper.getUsers";/*return the List<User>*/List<User> users= session.selectList(statement);session.commit();System.out.println("effect rows.."+users);session.close();}
Tips :

parameterType 和 resultType 為 hashmap :

  • mapper.xml :
<select id="getUserForMap" parameterType="hashmap" resultType="hashmap">    select * from c_user where id=#{id};  </select>
  • test code :
@Test  public void getUserForMap(){SqlSession session = MybatisUtils.getFactory().openSession();String statement = "com.web.mapper.userMapper.getUserForMap";HashMap<String, Object> map = new HashMap<String, Object>();map.put("id", 1);/*return the effect rows*/Object selectOne = session.selectOne(statement, map);/*default is not auto commit*/session.commit(true);session.close();System.out.println("effect rows.."+selectOne+" ,class :"+selectOne.getClass());}
  • result as follows :
effect rows..{id=1, age=12, name=luli} ,class :class java.util.HashMap

綜上可知:mybatis 會根據參數類型和結果類型,自動進行解析封裝。

【擴充 基本方法】【1】分頁列表
 <select id="getListPage" parameterType="hashmap" resultMap="siteExtendDaoMap">    select id,site_id,site_name,site_number,province,city,area,address,internal_number,longitude,latitude    from tb_site    --使用動態sql    <trim prefix="where" prefixOverrides="AND |OR ">       <if test="checkState!= null and checkState!=''">        and check_state = #{checkState,jdbcType=INTEGER}      </if>      <if test="siteId!= null and siteId!=''">        and site_id like concat('%',#{siteId},'%')      </if>      <if test="siteName!= null and siteName!=''">        and site_name like concat('%',#{siteName},'%')      </if>      <if test="siteNumber!= null and siteNumber!=''">        and site_number like concat('%', #{siteNumber},'%')      </if>      <if test="province!= null and province!=''">        and province = #{province}      </if>      <if test="city!= null and city!=''">        and city = #{city}      </if>      <if test="area!= null and area!=''">        and area = #{area}      </if>    </trim>     --添加排序    <if test="sortname!= null and sortname!='' and sortorder!= null and sortorder!=''">      order by ${sortname} ${sortorder}    </if>    --添加分頁    limit ${(page-1)*pagesize},${pagesize} </select>
【2】刪除方法–根據對象或者Id

如果參數為pojo,mybatis會自動從對象裡面擷取id ;

  <delete id="delete" parameterType="User">    delete from tb_user    where    id = #{id}   </delete>  <delete id="deleteById" parameterType="long">    delete from tb_user    where    id = #{id}   </delete>
【3】根據 id list 刪除資料
  <delete id="deleteByIds">    delete from tb_user    where id in    --使用foreach    <foreach collection="list" item="id" open="(" separator=","close=")"> #{id}     </foreach>  </delete>
【4】getRows

通常與getListPage聯合使用。

<select id="getRows" parameterType="hashmap" resultType="long">    select count(*) from tb_sys_role    <if test="keySysRole!= null">      <trim prefix="WHERE" prefixOverrides="AND |OR ">        <if test="keySysRole.id!= null">        and id = #{keySysRole.id}        </if>        <if test="keySysRole.name!= null and keySysRole.name!=''">        and name = #{keySysRole.name}        </if>        <if test="keySysRole.available!= null and keySysRole.available!=''">        and available = #{keySysRole.available}        </if>      </trim>    </if>  </select>
總結

以上就是本文關於mybatis使用xml進行增刪改查代碼解析的全部內容,希望對大家有所協助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.