一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語(yǔ)言|JavaScript|易語(yǔ)言|vb.net|

服務(wù)器之家 - 編程語(yǔ)言 - Java教程 - mybatis使用xml進(jìn)行增刪改查代碼解析

mybatis使用xml進(jìn)行增刪改查代碼解析

2021-04-01 14:28流煙默 Java教程

這篇文章主要介紹了mybatis使用xml進(jìn)行增刪改查代碼解析,分享了相關(guān)配置和代碼示例,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下

MyBatis是支持普通sql查詢、存儲(chǔ)過(guò)程和高級(jí)映射的持久層框架。

MyBatis消除了幾乎所有的JDBC代碼和參數(shù)的手工設(shè)置以及對(duì)結(jié)果集的檢索封裝。

MyBatis可以使用 簡(jiǎn)單的XML或注解用于配置和原始映射,將接口和Java的POJO(Plain Old Java Objects 普通的Java對(duì)象)映射成數(shù)據(jù)庫(kù)中的記錄。

每一個(gè)Mybatis應(yīng)用程序都以一個(gè)sqlSessionFactory對(duì)象的實(shí)例為核心。

sqlSessionFactory對(duì)象的實(shí)例可以通過(guò)sqlSessionFactoryBuilder對(duì)象來(lái)獲得。sqlSessionFactoryBuilder對(duì)象可以通過(guò)xml配置文件,或從以往使用管理中準(zhǔn)備好的Configuration類實(shí)例中來(lái)構(gòu)建sqlSessionFactory對(duì)象。

 

【示例:使用配置類獲取sqlSessionFactory】

 

?
1
2
3
4
5
6
7
8
DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
//環(huán)境
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
//映射器類
configuration.addMapper(BlogMapper.class);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);

注意這種情況下配置是添加映射器類。映射器類是Java類,這些類包含SQL映射語(yǔ)句的注解從而避免了xml文件的依賴,但是xml映射仍然在 大多數(shù)高級(jí)映射(比如:嵌套join映射)時(shí)需要。

出于這樣的原因,如果存在xml配置文件的話,MyBatis將會(huì)自動(dòng)查找和加載一個(gè)對(duì)等的XML文件(這種情況下,基于類路徑下的BlogMapper.class類的類名,那么BlogMapper.xml將會(huì)被加載–即class 與 XML在同一個(gè)文件目錄下。如果非,則需要手動(dòng)配置加載xml)。

 

【1】基本增刪改查xml配置

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?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屬性名與數(shù)據(jù)表中column列名不一致問(wèn)題 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.查詢語(yǔ)句使用別名
   -->
   <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>

注冊(cè)到mybatis.xml [當(dāng)與spring結(jié)合時(shí),將不需要這個(gè)配置文件]

mybatis的配置文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?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"/>
 
  <!-- 配置實(shí)體類的別名 -->
  <typeAliases>
    <!-- <typeAlias type="com.web.model.User" alias="User"/> -->
    <package name="com.web.model"/>
  </typeAliases>
<!--
  development : 開(kāi)發(fā)模式
  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】通過(guò)SqlSessionFactory拿到session

 

這里使用xml文件獲取sqlSessionFactory和sqlSession。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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);
//默認(rèn)手動(dòng)提交;
/*
  兩種解決方式:
  1.factory.opensession(true);
  2.session.commit();
  */

 

【3】增刪改查后臺(tái)測(cè)試代碼

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*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 :
?
1
2
3
<select id="getUserForMap" parameterType="hashmap" resultType="hashmap">
    select * from c_user where id=#{id};
  </select>
  • test code :
?
1
2
3
4
5
6
7
8
9
10
11
12
13
@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 :
?
1
effect rows..{id=1, age=12, name=luli} ,class :class java.util.HashMap

綜上可知:mybatis 會(huì)根據(jù)參數(shù)類型和結(jié)果類型,自動(dòng)進(jìn)行解析封裝。

 

【擴(kuò)展 基本方法】

 

 

【1】分頁(yè)列表

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<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
   --使用動(dòng)態(tài)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>
   --添加分頁(yè)
   limit ${(page-1)*pagesize},${pagesize}
</select>

 

【2】刪除方法–根據(jù)對(duì)象或者Id

如果參數(shù)為pojo,mybatis會(huì)自動(dòng)從對(duì)象里面獲取id ;

?
1
2
3
4
5
6
7
8
9
10
11
<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】根據(jù) id list 刪除數(shù)據(jù)

?
1
2
3
4
5
6
7
<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聯(lián)合使用。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<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>

 

總結(jié)

 

以上就是本文關(guān)于mybatis使用xml進(jìn)行增刪改查代碼解析的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!

原文鏈接:http://blog.csdn.net/J080624/article/details/53374067

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 日本五级床片全都免费播放 | 手机在线免费观看高清 | 丝瓜视频在线观看污 | 全彩孕交漫画福利啪啪吧 | 俄罗斯大逼 | 日本高清在线看 | 日韩精品免费一区二区三区 | 艹出白浆 | 免费看又黄又爽又猛的视频软件- | 日韩在线中文字幕 | 国产成人成人一区二区 | 男人插曲女人下面 | 国产精品理论片在线观看 | 女人把私密部位张开让男人桶 | 9420高清完整版在线观看国语 | 国产欧美日韩视频在线观看一区二区 | 毛片网站免费观看 | 99热久久这里只有精品23 | 国产精亚洲视频 | futa文| 欧美精品成人a多人在线观看 | 国产精品香蕉一区二区三区 | 亚洲卡一卡2卡三卡4卡无卡三 | 国产91精品久久久久久 | 四虎国产一区 | 色色色资源站 | 日韩毛片免费在线观看 | 国产精品第1页在线播放 | 四虎成人网 | 99久久www免费 | 欧美午夜精品久久久久久黑人 | 国产a不卡片精品免费观看 国产aaa伦理片 | 亚洲天堂2013 | 青青草精品在线观看 | 97社区| 欧美一卡二卡科技有限公司 | 五月最新商场女厕所高跟嘘嘘 | 国产欧美日韩在线观看精品 | 无码国产成人777爽死在线观看 | 亚欧美综合 | 啊皇上你好大要知画 |