Mybatis入門——語法詳解:基礎使用、增刪改查、起別名、解決問題、注釋、動態查詢,從入門到進階

文章目錄

  • 1.基礎使用
    • 1.添加依賴
    • 2.在resouces文件下新建xml文件db.properties
    • 3.在resouces文件下新建xml文件mybatis-config-xml
    • 4.創建一個MybatisUtils工具類
    • 5.創建xml文件XxxMapper.xml映射dao層接口
    • 6.添加日志
    • 5.測試
  • 2.增刪改查
    • 1.select
    • 2.delete
    • 3.update
    • 4.insert
    • 5.模糊查詢
    • 6.分頁查詢
  • 3.起別名
    • 3.1具體的某個文件
    • 3.2給包名起別名
    • 3.3用注解起別名
  • 4.解決實體屬性名與數據庫列名不一致問題
    • 1.建一個resultMap標簽
    • 2.引用
  • 5.使用注解
    • 5.1在接口上寫注解
    • 5.2進行綁定
  • 6.association和collection
    • 6.1一對多
    • 6.2多對一
  • 7.動態查詢
    • 7.1模糊查詢if標簽
    • 7.2更新數據set標簽
    • 7.3Forech
  • 8.二級緩存
    • 8.1在mybatis-config.xml中開啟全局緩存
    • 8.1添加局部緩存,在xxMapper.xml中添加

1.基礎使用

1.添加依賴

<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.18</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.6</version></dependency>
<build>
<resources><resource><directory>src/main/resources</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource><resource><directory>src/main/java</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource>
</resources>
</build>

2.在resouces文件下新建xml文件db.properties

寫配置文件

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai&useSSL=true&useUnicode=true&characterEncoding=utf-8
username=root
password=DRsXT5ZJ6Oi55LPQ

3.在resouces文件下新建xml文件mybatis-config-xml

<?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"/><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/tuzhi/dao/UserMapper.xml"/></mappers>
</configuration>

4.創建一個MybatisUtils工具類

public class MybatisUtils {private static SqlSessionFactory sqlSessionFactory;static {String resource = "org/mybatis/example/mybatis-config.xml";InputStream inputStream = null;try {inputStream = Resources.getResourceAsStream(resource);} catch (IOException e) {e.printStackTrace();}sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);}public SqlSession getSqlSession() {return sqlSessionFactory.openSession();}
}

5.創建xml文件XxxMapper.xml映射dao層接口

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--映射dao層接口-->
<mapper namespace="com.tuzhi.dao.UserDao">
<!--    映射接口里面的方法--><select id="getUserList" resultType="com.tuzhi.pojo.User">select * from user</select>
</mapper>

6.添加日志

<settings><setting name="logImpl" value="LOG4J"/><!--    是否開啟駝峰命名自動映射,即從經典數據庫列名 A_COLUMN 映射到經典 Java 屬性名 aColumn。--><setting name="mapUnderscoreToCamelCase" value="true"/><!--        開啟全局緩存--><setting name="cacheEnabled" value="true"/></settings>

5.測試

@Testpublic void test() {SqlSession sqlSession = MybatisUtils.getSqlSession();UserDao userDao = sqlSession.getMapper(UserDao.class);List<User> userList = userDao.getUserList();for (User user : userList) {System.out.println(user);}sqlSession.close();}

2.增刪改查

1.select

<select id="getUserById" resultType="com.tuzhi.pojo.User" parameterType="int">select * from user where id = #{id}</select>

2.delete

<delete id="deleteUser" parameterType="com.tuzhi.pojo.User">deletefrom USERwhere id = #{id};</delete>

3.update

<update id="updateUser" parameterType="com.tuzhi.pojo.User">update USERset name = #{name},pwd = #{pwd}where id = #{id};</update>

4.insert

<insert id="addUser" parameterType="com.tuzhi.pojo.User">insert into USER (id,name ,pwd)values (#{id},#{name},#{pwd});</insert>

5.模糊查詢

<select id="getUserListLike" resultType="com.tuzhi.pojo.User">select * from user where name like concat('%',#{name},'%')</select>

6.分頁查詢

<!--    分頁查詢--><select id="getUserLimit" parameterType="map" resultMap="userResultMap">select * from user limit #{startIndex},#{pageSize}</select>

3.起別名

3.1具體的某個文件

<typeAliases><typeAlias alias="Author" type="domain.blog.Author"/><typeAlias alias="Blog" type="domain.blog.Blog"/><typeAlias alias="Comment" type="domain.blog.Comment"/><typeAlias alias="Post" type="domain.blog.Post"/><typeAlias alias="Section" type="domain.blog.Section"/><typeAlias alias="Tag" type="domain.blog.Tag"/>
</typeAliases>

3.2給包名起別名

<typeAliases><package name="domain.blog"/>
</typeAliases>

注,用別名的時候直接用文件名,全小寫

3.3用注解起別名

@Alias("author")

注,直接在類上注解

4.解決實體屬性名與數據庫列名不一致問題

1.建一個resultMap標簽

<resultMap id="userResultMap" type="User">//property實體類里的,column數據庫里的<id property="id" column="user_id" /><result property="username" column="user_name"/><result property="password" column="hashed_password"/>
</resultMap>

2.引用

然后在引用它的語句中設置 resultMap 屬性就行了(注意我們去掉了 resultType 屬性)。比如:

<select id="selectUsers" resultMap="userResultMap">select user_id, user_name, hashed_passwordfrom some_tablewhere id = #{id}
</select>

5.使用注解

5.1在接口上寫注解

public interface UserMapper {//    使用注解@Select("select * from user")List<User> getUserListAnnotate();
}

5.2進行綁定

<mappers><mapper class="com.tuzhi.dao.UserMapper"/>
</mappers>

6.association和collection

association用于對象,關聯

collection用于集合

6.1一對多

  • 實體類

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Student {private int id;private String name;private Teacher teacher;
    }
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Teacher {private int id;private String name;
    }
    
  • 第一種查詢

    <!--    第一種多對一查詢-->
    <select id="getUserList1" resultMap="studentTeacher1">select * from student
    </select>
    <resultMap id="studentTeacher1" type="Student"><association property="teacher" column="tid" select="getTeacherListById"/>
    </resultMap>
    <select id="getTeacherListById" resultType="Teacher">select * from teacher where id = #{tid}
    </select>
    
  • 第二種查詢

    <!--    第二種多對一查詢-->
    <select id="getUserList2" resultMap="studentTeacher2">select s.id sid,s.name sname,t.id tid,t.name tnamefrom student s,teacher twhere s.tid = t.id
    </select>
    <resultMap id="studentTeacher2" type="Student"><result property="id" column="sid"/><result property="name" column="sname"/><association property="teacher" javaType="Teacher"><result property="id" column="tid"/><result property="name" column="tname"/></association>
    </resultMap>
    

6.2多對一

  • 實體類

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Student {private int id;private String name;
    }
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Teacher {private int id;private String name;private List<Student> student;
    }
  • 第一種查詢

    <!--    第一種查詢--><select id="getTeacherListById1" resultMap="teacherStudent1">select t.id id,t.name tname,s.id sid,s.name sname,s.tid tidfrom teacher t,student swhere t.id=s.tid</select><resultMap id="teacherStudent1" type="Teacher"><result property="id" column="id"/><result property="name" column="tname"/><collection property="student" ofType="Student"><result property="id" column="sid"/><result property="name" column="sname"/></collection></resultMap>
    
  • 第二種查詢

    <!--    第二種查詢--><select id="getTeacherListById2" resultMap="teacherStudent2">select * from teacher where id = #{id}</select><resultMap id="teacherStudent2" type="Teacher"><collection property="student" javaType="Arraylist" ofType="Student" column="id" select="getStudentList"/></resultMap><select id="getStudentList" resultType="Student">select * from student where tid = #{id}</select>
    

7.動態查詢

7.1模糊查詢if標簽

  • 接口
//查詢
List<Blog> getBlogIf(Map map);
  • if
<!--    動態sql模糊查詢-->
<select id="getBlogIf" parameterType="map" resultType="blog">select * from blog<where><if test="title != null">and title like concat('%',#{title},'%')</if><if test="author != null">and author like concat('%',#{author}.'%')</if></where></select>

7.2更新數據set標簽

  • 接口

  • set標簽

    <!--    動態更新數據-->
    <update id="updateBlog" parameterType="Blog">update blog<set><if test="title != null">title = #{title},</if><if test="author != null">author = #{author},</if><if test="views != null">views = #{views},</if></set>where id = #{id}
    </update>
    

7.3Forech

  • forech

    <select id="queryForeach" parameterType="map" resultType="Blog">select * from blog<where><foreach collection="ids" item="id" open="and (" separator="or" close=")">id = #{id}</foreach></where>
    </select>
    
  • 測試

    @Test
    public void queryForech() {SqlSession sqlSession = MybatisUtils.getSqlSession();BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);ArrayList arrayList = new ArrayList();arrayList.add(1);arrayList.add(2);HashMap hashMap = new HashMap();hashMap.put("ids",arrayList);mapper.queryForeach(hashMap);sqlSession.close();
    }
    

8.二級緩存

8.1在mybatis-config.xml中開啟全局緩存

<setting name="cacheEnabled" value="true"/>

8.1添加局部緩存,在xxMapper.xml中添加

<cacheeviction="FIFO"flushInterval="60000"size="512"readOnly="true"/>

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/37020.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/37020.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/37020.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

同心創建 共踐食安 | 趙夢澈榮獲食品安全大使

“民族要復興&#xff0c;鄉村必振興”&#xff0c;為深入貫徹落實國家鄉村振興戰略&#xff0c;推進鄉村全面振興不斷取得新成效&#xff0c;助力全國優質食品農產品的宣傳推廣、市場營銷、品牌創建工作&#xff0c;由中國食品安全報社主辦&#xff0c;商業發展中心、健康中國…

python數據分析與可視化一

公共部分 # 引入數據分析工具 Pandas import pandas as pd # 引入數據可視化工具 Matplotlib import matplotlib.pyplot as plt # 引入數據可視化工具 Seaborn (基于matplotlib) import seaborn as sns # 解決輸出時的列名對齊問題 pd.set_option(display.unicode.east_…

Python多線程編程詳解

Python多線程編程詳解 大家好&#xff0c;我是免費搭建查券返利機器人省錢賺傭金就用微賺淘客系統3.0的小編&#xff0c;也是冬天不穿秋褲&#xff0c;天冷也要風度的程序猿&#xff01; 多線程編程是利用計算機多核心和多線程處理器的優勢&#xff0c;提高程序并發性能的重要…

如何申請免費SSL證書以消除訪問網站顯示連接不安全提醒

在當今互聯網時代&#xff0c;網絡安全已成為一個不可忽視的問題。當用戶瀏覽一些網站時&#xff0c;有時會看到瀏覽器地址欄出現“不安全”的提示&#xff0c;這意味著該網站沒有安裝SSL證書&#xff0c;數據傳輸可能存在風險。那么&#xff0c;如何消除這種不安全提醒&#x…

2024年6月,Altair被Gartner魔力象限評為數據科學與機器學習平臺領導者

Altair 因其愿景完整性和執行能力被評為領導者 2024 年 6 月 20 日&#xff0c;Altair&#xff08;納斯達克股票代碼&#xff1a;ALTR&#xff09;宣布&#xff0c;Altair RapidMiner 被 Gartner Magic Quadrant?&#xff08;魔力象限&#xff09;評為數據科學與機器學習平臺領…

SpringBoot配置參數獲取

1、使用Value注解 import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component;Component public class MyBean {Value("${myapp.name}") private String appName;public void printAppName() {System.out.print…

冪等生產者和事務生產者

Kafka消息交付 Kafka消息交付可靠性保障以及精確處理一次語義的實現。 所謂的消息交付可靠性保障&#xff0c;是指Kafka對Producer和Consumer要處理的消息提供什么樣的承諾。常見的承諾有以下三種&#xff1a; 最多一次&#xff08;atmost once&#xff09;&#xff1a;消息…

SpringBoot:SpringBoot 調用第三方接口的幾種方式

一、前言 在項目中調用第三方接口時&#xff0c;確實需要根據項目的技術棧、架構規范以及具體的業務需求來選擇最適合的調用方式。比如&#xff1a;RESTful API調用、Feign聲明式HTTP客戶端、Apache HttpClient等調用方式&#xff0c;每種方式都有其適用場景和優勢。下面我們就…

倉庫管理系統16--入庫管理

原創不易&#xff0c;打字不易&#xff0c;截圖不易&#xff0c;多多點贊&#xff0c;送人玫瑰&#xff0c;留有余香&#xff0c;財務自由明日實現。 1、創建物資入庫用戶控件 <UserControl x:Class"West.StoreMgr.View.InStoreView"xmlns"http://schema…

CAS自旋解析

CAS全稱CompareAndSwap(比較并交換)&#xff0c;是cpu的指令&#xff0c;調用時不涉及上下文的切換。Java中屬于樂觀鎖的一種&#xff0c;具體流程如下圖&#xff1a; 具體的實現使用的是Unsafe類去調用native修飾的compareAndSwap方法&#xff0c;4個字段分別是對象實例&#…

PTA—C語言期末復習(判斷題)

1. C語言程序是從源文件的第一條語句開始執行的 &#xff08;F&#xff09; 在 C 語言中&#xff0c;程序是從 main 函數開始執行的&#xff0c;而不是從源文件的第一條語句開始執行 2. 若變量定義為double x;&#xff0c;則x % 2是符合C語言語法的表達式 &#xff08;F&#…

通過nginx去除 api url前綴 并保持后面剩余的url不變向后臺請求

如 我前臺瀏覽器向后臺請求的接口是 http://127.0.0.1:5099/api/sample/sample/getbuttonlist 實際的請求接口傳向 http://192.168.3.71:5099/sample/sample/getbuttonlist 方法是向config中加入下面這樣一個server server {listen 5099;location /api/ {rewrite ^/a…

HTML流星雨

目錄 寫在前面 完整代碼 代碼分析 系列文章 寫在最后 寫在前面 歲月如梭&#xff0c;光陰似箭&#xff0c;不知不覺暑假就要來嘍&#xff0c;本期小編用HTML給大家手搓了一個炫酷的流星雨動畫&#xff0c;一起來看看吧。 完整代碼 <!DOCTYPE html> <html lang…

項目風險管理系統有哪些?分享11款主流項目管理系統

本文將分享11款主流項目管理系統&#xff1a;PingCode、Worktile、StandardFusion、MasterControl、ClickUp、SAI360、Netwrix Auditor、MetricStream、Wrike、Celoxis、Zoho Projects。 在項目管理中&#xff0c;風險管理不僅是一個挑戰&#xff0c;也是保證項目順利進行的關鍵…

探索Vim的文本處理能力:精通查找與替換

探索Vim的文本處理能力&#xff1a;精通查找與替換 Vim&#xff0c;作為Linux終端下的王牌文本編輯器&#xff0c;以其強大的功能和靈活性深受開發者和系統管理員的喜愛。在Vim中進行查找和替換是文本編輯中的一項基礎且重要的操作。本文將詳細解釋如何在Vim中執行查找和替換文…

Linux Redis 服務設置開機自啟動

文章目錄 前言一、準備工作二、操作步驟2.1 修改redis.conf文件2.2 創建啟動腳本2.3 設置redis 腳本權限2.4 設置開機啟動2.5 驗證 總結 前言 請各大網友尊重本人原創知識分享&#xff0c;謹記本人博客&#xff1a;南國以南i、 提示&#xff1a;以下是本篇文章正文內容&#x…

編程的難點在哪?是邏輯、算法,還是模塊、框架的掌握?

&#x1f446;點擊關注 回復『新人禮』獲取學習禮包&#x1f446; 很多新手程序員在一開始都是滿懷熱情地投入到編程的學習&#xff0c;但卻在學習過程中處處碰壁&#xff0c;導致放棄。 編程的難點在于邏輯、數學、算法&#xff0c;還是模塊、框架、接口的掌握&#xff1f;但…

idea Error running ‘Application‘

1、Error running ‘Application’ Error running ApplicationError running Application. Command line is too long.Shorten the command line via JAR manifest or via a classpath file and rerun.找到 .idea/libraies/workspace.xml 中的 PropertiesComponent 屬性&#…

Android InputDispatcher分發輸入事件

派發循環是指 InputDispatcher 不斷地派發隊列取出事件&#xff0c;尋找合適的窗口并進行發送的過程&#xff0c;是 InputDispatcher 線程的主要工作 事件發送循環是 InputDispatcher 通過 Connection 對象將事件發送給窗口&#xff0c;并接受其反饋的過程 InputDispatcher —…

Spring Boot跨域請求關鍵處理技術解析

Spring Boot跨域請求關鍵處理技術解析 在Web開發中&#xff0c;跨域請求是一個常見問題&#xff0c;尤其在微服務架構和前后端分離的開發模式中更為突出。Spring Boot作為一種流行的Java Web框架&#xff0c;提供了多種解決跨域請求的方法。本文將詳細解析Spring Boot中跨域請…