關於mybatis的xml配置方式的個人理解

來源:互聯網
上載者:User

學習心得:

   學習的時候忌諱墨守陳規,從頭學的想法是錯誤的

   學習到了就要先鞏固下來

   不懂的一定要弄懂,一知半解危害大


1 主設定檔 裡面解析

   

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><properties resource="db.properties"><property name="username" value="root"/><property name="password" value="root"/></properties><typeAliases><typeAlias type="User" alias="user"/></typeAliases><environments default="development"><!-- 配置多個資料庫連接環境這裡和 db.properties對應 --><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="UserMapper.xml"/> --><mapper class="UserMapper"/></mappers></configuration>
  有幾個要點

  a: properties載入的話可以直接定義,也可以從properties檔案讀取,也可以混合,都是可以的。下面要用到

  b:typeAliases,就是別名的意思,本來可以不用寫,但是後面會經常用到,所以寫個別名減少了字串的書寫

  c:environments 配置了 jdbc資料庫連接情況,必填

  d:mappers:這個有兩種,用resource 就代表用註解的方式了

                              用class代表用設定檔xml的方式(用了類,類對應xml,xml中定義了明明空間為map類)

2 映射類

  

public interface UserMapper {public User findUser(User user);public User findUserById(String id);public User findUserByIdForInt(int id);}
   簡單的定義了一個介面,在測試類別裡會用一個奇特的方式來調用

3 類User 是最最簡單的pojo類,不做描述

4 映射設定檔

   

<?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="UserMapper" ><resultMap type="user" id="baseUserMap" ><id column="l_id" property="id" jdbcType="INTEGER" /> <result column="l_sex" property="sex" jdbcType="VARCHAR" /><result column="l_name" property="name" jdbcType="VARCHAR" /> <result column="l_greade" property="grade" jdbcType="VARCHAR" /> </resultMap>    <sql id="searchUser"> <where>   <if test="id!=null">   l_id = #{id}   </if>  <if test="id == null">  l_id is null  </if> </where> </sql>  <select id="findUser" parameterType="user" resultMap="baseUserMap"> select * from tb_user <include refid="searchUser"/> order by l_grade </select>  <select id="findUserById" parameterType="string" resultMap="baseUserMap"> select * from tb_user where l_id = #{id} order by l_grade </select>   <select id="findUserByIdForInt" parameterType="int" resultMap="baseUserMap"> select * from tb_user where l_id = #{id} order by l_grade </select></mapper>
  a:這裡用了三種方式來測試查詢語句,根據主類,根據String類型id,根據int類型id

  b:雖然id類本身為int類型,但是用string類型也是可以的,不報錯

  c:如果用了簡單類型例如string、int就不能讓引用include帶變數了,因為會找不到,報錯,實驗下就知道了

  d :resultMap 定義了User類的屬性和表列名一一對應關係,起了一個id名,和對應的 User類的別名,在主設定檔定義過了

  e:命名空間要用類名,這個是用來找類名的,具體mybatis怎麼處理是架構處理的,只需記得加上別名即可

  f: 定義子句

     

 <sql id="searchUser"> <where>   <if test="id!=null">   l_id = #{id}   </if>  <if test="id == null">  l_id is null  </if> </where> </sql>
 調用方法

<include refid="searchUser"/>
5 測試語句

import java.io.IOException;import java.io.InputStream;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class SelectTest {public static void main(String[] args) {InputStream inputStream;try {inputStream = Resources.getResourceAsStream("mybiatis-config.xml");SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession session = factory.openSession();UserMapper mapper = session.getMapper(UserMapper.class);User user2 = new User();user2.setId(1);User user = mapper.findUser(user2);System.out.println(user);System.out.println(mapper.findUserById(String.valueOf(1)));System.out.println(mapper.findUserByIdForInt(1));session.close();} catch (IOException e) {e.printStackTrace();}}}

a: 擷取位元組流

b:擷取sessionfactory

c:擷取session

d:後去XXMap

e:調用map方法

6 擷取結果:

User [id=1, name=112, grade=null, sex=333]User [id=1, name=112, grade=null, sex=333]User [id=1, name=112, grade=null, sex=333]


7 關於使用關聯的問題,例如

import java.util.List;public class XianUser {private int id;private String location;private List<User> users;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getLocation() {return location;}public void setLocation(String location) {this.location = location;}public List<User> getUsers() {return users;}public void setUsers(List<User> users) {this.users = users;}@Overridepublic String toString() {return "XianUser [id=" + id + ", location=" + location + ", users="+ users + "]";}}

這裡面多了一個 集合List<user>,所以這裡在配置時要使用遞迴。因為XianUser和User存在了關聯,所以我放在了同一個UserMapper.java和UserMapper.xml下面

但是還沒確認分開是否可以,應該是可以的理論上

這裡處理需要添加集合

<resultMap type="xianUser" id="xaUser"><id column="l_id" property="id" jdbcType="INTEGER"/><result column="l_location" property="location" jdbcType="VARCHAR"/> <collection property="users" ofType="user" column="l_p_id" select="findChildUserById" javaType="java.util.ArrayList"></collection><!--<collection property="sysDictVOList" ofType="sysDictVO" column="sd_id"  select="findSysDictTreeByCOde" javaType="java.util.ArrayList"           ></collection> --></resultMap><select id="findAllUserById" resultMap="xaUser" parameterType="int">select * from tb_xianuser where l_id = #{id}</select><select id="findChildUserById" resultMap="baseUserMap" parameterType="int">select * from tb_user where l_p_id = #{id}</select> 

注意查看集合的使用方式

8 在返回裡面有可能是多個值所以

返回最好都用list的值表示

import java.util.List;public interface UserMapper {public User findUser(User user);public User findUserById(String id);public User findUserByIdForInt(int id);public List<XianUser> findAllUserById(int id);public List<User> findChildUserById(int id);}

除非你確定了的確只有一個傳回值存在


9 mybatis在insert時的操作

 <insert id="insertUser" parameterType="User"> insert into tb_user(l_name,l_sex,l_grade) values(#{name},#{sex},#{grade}); </insert>

10 調用時要提交

mapper.insertUser(user);session.commit();


11 更新時操作

<update id="updateUser" parameterType="user"> update tb_user <set> <if test="name!=null"> l_name = #{name} </if> </set> <where> l_id = #{id} </where> </update>


user.setId(2);user.setName("ok");mapper.updateUser(user);session.commit();

12  刪除樣本

  <delete id="deleteUserById" parameterType="int" >
  delete from tb_user where l_id = #{id}
  </delete>


  13 有的項目配置的時候加上了這個,有時可以不用

 <settings><!-- 全域對應器啟用緩衝 --><setting name="cacheEnabled" value="true" /><!-- 查詢時,關閉關聯對象即時載入以提高效能 --><setting name="lazyLoadingEnabled" value="true" /><!-- 設定關聯對象載入的形態,此處為按需載入欄位(載入欄位由SQL指 定),不會載入關聯表的所有欄位,以提高效能 --><setting name="aggressiveLazyLoading" value="false" /><!-- 對於未知的SQL查詢,允許返回不同的結果集以達到通用的效果 --><setting name="multipleResultSetsEnabled" value="true" /><!-- 允許使用欄標籤代替列名 --><setting name="useColumnLabel" value="true" /><!-- 允許使用自訂的主索引值(比如由程式產生的UUID 32位編碼作為索引值),資料表的PK建置原則將被覆蓋 --><setting name="useGeneratedKeys" value="true" /><!-- 給予被嵌套的resultMap以欄位-屬性的映射支援 --><setting name="autoMappingBehavior" value="FULL" /><!-- 對於批次更新操作緩衝SQL以提高效能 --><setting name="defaultExecutorType" value="BATCH" /><!-- 資料庫超過25000秒仍未響應則逾時 --><setting name="defaultStatementTimeout" value="25000" /></settings>



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.