【Mybatis】快速入門 基本使用 第一期

文章目錄

  • Mybatis是什么?
  • 一、快速入門(基于Mybatis3方式)
  • 二、MyBatis基本使用
  • 2.1 向SQL語句傳參
    • 2.1.1 mybatis日志輸出配置
    • 2.1.2 #{}形式
    • 2.1.3 ${}形式
  • 2.2 數據輸入
    • 2.2.1 Mybatis總體機制概括
    • 2.2.2 概念說明
    • 2.2.3 單個簡單類型參數
    • 2.2.4 實體類類型參數
    • 2.2.5 多個簡單類型數據
    • 2.2.6 Map類型參數
  • 2.3 數據輸出
    • 2.3.1 返回單個簡單類型
    • 2.3.2 返回實體類對象
    • 2.3.3 返回Map類型
    • 2.3.4 返回List類型
    • 2.3.5 返回主鍵值
    • 2.3.6 實體類屬性和數據庫字段對應關系
  • 2.4 CRUD強化練習
  • 2.5 mapperXML標簽總結
  • 總結


Mybatis是什么?

官網 文檔
MyBatis 是一款優秀的持久層框架,MyBatis 可以通過簡單的 XML 或注解來配置和映射原始類型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 對象)為數據庫中的記錄。

開發效率:Hibernate>Mybatis>JDBC

運行效率:JDBC>Mybatis>Hibernate


一、快速入門(基于Mybatis3方式)

  1. 數據庫
CREATE DATABASE `mybatis-example`;USE `mybatis-example`;CREATE TABLE `t_emp`(emp_id INT AUTO_INCREMENT,emp_name CHAR(100),emp_salary DOUBLE(10,5),PRIMARY KEY(emp_id)
);INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("tom",200.33);
INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("jerry",666.66);
INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("andy",777.77);
  1. 項目的搭建 準備
  • 項目搭建
    1
  • 依賴導入
<dependencies><!-- mybatis依賴 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.11</version></dependency><!-- MySQL驅動 mybatis底層依賴jdbc驅動實現,本次不需要導入連接池,mybatis自帶! --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.25</version></dependency><!--junit5測試--><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><version>5.3.1</version></dependency>
</dependencies>
  • 實體類
public class Employee {private Integer empId;private String empName;private Double empSalary;......set/get
  1. Mapper接口與MapperXML文件
    1
  • 定義Mapper接口
/*** @Description: dao層接口*/
public interface EmployeeMapper {/*** 根據ID查找員工信息* @param id* @return*/Employee queryById(Integer id);/*** 根據ID刪除對應員工* @param id* @return*/int deleteById(Integer id);
}
  • 定義Mapper xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace等于mapper接口類的全限定名,這樣實現對應 -->
<mapper namespace="com.wake.mapper.EmployeeMapper"><!-- 查詢使用 select標簽id = 方法名resultType = 返回值類型標簽內編寫SQL語句--><select id="queryById" resultType="com.wake.pojo.Employee"><!-- #{id}代表動態傳入的參數,并且進行賦值!... -->select emp_id empId,emp_name empName, emp_salary empSalary fromt_emp where emp_id = #{id}</select><delete id="deleteById">delete from t_emp where emp_id = #{id}</delete>
</mapper>
  1. 準備Mybatis配置文件
<?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><!-- environments表示配置Mybatis的開發環境,可以配置多個環境,在眾多具體環境中,使用default屬性指定實際運行時使用的環境。default屬性的取值是environment標簽的id屬性的值。 --><environments default="development"><!-- environment表示配置Mybatis的一個具體的環境 --><environment id="development"><!-- Mybatis的內置的事務管理器 --><transactionManager type="JDBC"/><!-- 配置數據源 --><dataSource type="POOLED"><!-- 建立數據庫連接的具體信息 --><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/mybatis-example"/><property name="username" value="root"/><property name="password" value="root"/></dataSource></environment></environments><mappers><!-- Mapper注冊:指定Mybatis映射文件的具體位置 --><!-- mapper標簽:配置一個具體的Mapper映射文件 --><!-- resource屬性:指定Mapper映射文件的實際存儲位置,這里需要使用一個以類路徑根目錄為基準的相對路徑 --><!--    對Maven工程的目錄結構來說,resources目錄下的內容會直接放入類路徑,所以這里我們可以以resources目錄為基準 --><mapper resource="mappers/EmployeeMapper.xml"/></mappers></configuration>
  1. 運行 測試
public class MybatisTest {@Testpublic void test_01() throws IOException {// 1. 讀取外部配置文件(mybatis-config.xml)InputStream ips = Resources.getResourceAsStream("mybatis-config.xml");// 2. 創建 SqlSessionFactorySqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(ips);// 3. 根據sqlSessionFactory 創建 sqlSession (每次業務創建一個,用完就釋放SqlSession session = sessionFactory.openSession();// 4. 獲取接口的代理對象(代理技術) 調用代理對象的方法,就會查找Mapper接口的方法//jdk動態代理技術生成的mapper代理對象EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);// 內部拼接接口的全限定符號.方法名 去查找sql語句標簽// 拼接 類的全限定符號.方法名 整合參數 -> ibatis對應的方法傳入參數// mybatis底層依賴調用ibatis只不過有固定的模式!Employee employee = mapper.queryById(1);System.out.println(employee);// 4.提交事務(非DQL)和釋放資源session.commit(); //提交事務 [DQL不需要,其他需要]session.close(); //關閉會話}
}

1
說明:

  • SqlSession:代表Java程序和數據庫之間的會話。
    • (HttpSession是Java程序和瀏覽器之間的會話)
  • SqlSessionFactory:是“生產”SqlSession的“工廠”。
    • 工廠模式:如果創建某一個對象,使用的過程基本固定,那么我們就可以把創建這個對象的相關代碼封裝到一個“工廠類”中,以后都使用這個工廠類來“生產”我們需要的對象。

SqlSession和HttpSession區別:

  • HttpSession:工作在Web服務器上,屬于表述層。
    • 代表瀏覽器和Web服務器之間的會話。
  • SqlSession:不依賴Web服務器,屬于持久化層。
    • 代表Java程序和數據庫之間的會話。

1

二、MyBatis基本使用

1

2.1 向SQL語句傳參

2.1.1 mybatis日志輸出配置

Mybatis 3 配置
1
我們可以在mybatis的配置文件使用settings標簽設置,輸出運過程SQL日志!

通過查看日志,我們可以判定#{} 和 ${}的輸出效果!

settings設置項:

logImpl指定 MyBatis 所用日志的具體實現,未指定時將自動查找。SLF4J | LOG4J(3.5.9 起廢棄) | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING未設置

日志配置:

    <settings><setting name="logImpl" value="STDOUT_LOGGING"/></settings>

開啟日志后 測試:
1

2.1.2 #{}形式

Mybatis會將SQL語句中的#{}轉換為問號占位符。

1

使用這個防止【注入式攻擊】

2.1.3 ${}形式

${}形式傳參,底層Mybatis做的是字符串拼接操作。
1

結論:實際開發中,能用#{}實現的,肯定不用${}。

特殊情況: 動態的不是值,是列名或者關鍵字,需要使用${}拼接

//注解方式傳入參數!!
@Select("select * from user where ${column} = #{value}")
User findByColumn(@Param("column") String column, @Param("value") String value);

一個特定的適用場景是:通過Java程序動態生成數據庫表,表名部分需要Java程序通過參數傳入;而JDBC對于表名部分是不能使用問號占位符的,此時只能使用

2.2 數據輸入

1
Mapper接口中 允許 重載方法

2.2.1 Mybatis總體機制概括

2.2.2 概念說明

這里數據輸入具體是指上層方法(例如Service方法)調用Mapper接口時,數據傳入的形式。

  • 簡單類型:只包含一個值的數據類型
    • 基本數據類型:int、byte、short、double、……
    • 基本數據類型的包裝類型:Integer、Character、Double、……
    • 字符串類型:String
  • 復雜類型:包含多個值的數據類型
    • 實體類類型:Employee、Department、……
    • 集合類型:List、Set、Map、……
    • 數組類型:int[]、String[]、……
    • 復合類型:List<Employee>、實體類中包含集合……

2.2.3 單個簡單類型參數

1
Mapper接口中抽象方法的聲明:

    /*** 根據ID 查詢對應員工信息* @param id* @return*/Employee selectEmpById(Integer id);/*** 根據薪資查找員工信息* @param salary* @return*/List<Employee> selectEmpBySalary(Double salary);/*** 根據ID 刪除員工對象* @param id* @return*/int deleteEmpById(Integer id);

SQL語句:

    <select id="selectEmpById" resultType="com.wake.pojo.Employee">select emp_id empId , emp_name empName , emp_Salary empSalary fromt_emp where emp_id = #{id};</select><select id="selectEmpBySalary" resultType="com.wake.pojo.Employee">select emp_id empId , emp_name empName , emp_Salary empSalary fromt_emp where emp_salary = #{salary};</select><!--  傳入簡單類型 key值 隨便寫 因為只有一個,一般情況寫參數名  --><delete id="deleteEmpById">delete from t_emp where emp_id = #{id};</delete>

2.2.4 實體類類型參數

Mapper接口中抽象方法的聲明:

    /*** 插入一條員工信息* @param employee* @return*/int insertEmp(Employee employee);

SQL語句:

    <!-- 傳入實體類 key 等于 屬性名  --><insert id="insertEmp">insert into t_emp (emp_name,emp_salary) values(#{empName},#{empSalary})</insert>

2.2.5 多個簡單類型數據

Mapper接口中抽象方法的聲明:

    /*** 根據名字與薪資 查找員工* @param name* @param salary* @return*/Employee selectEmpByNameAndSalary(@Param("empName") String name, @Param("salary") Double salary);/*** 根據ID 修改名字* @param id* @return*/int updateNameById(String name,Integer id);

SQL語句:

    <!-- 多個簡單參數接口中使用注解@Paramormapper.xml中  用[arg1, arg0, param1, param2]指代 (arg要查找的值 , param是要修改的值)--><select id="selectEmpByNameAndSalary" resultType="com.wake.pojo.Employee">select emp_id empId , emp_name empName , emp_Salary empSalary fromt_emp where emp_name = #{empName} and emp_salary = #{salary};</select><update id="updateNameById">update t_emp set emp_name = #{param1} where emp_id = #{arg1};</update>

2.2.6 Map類型參數

Mapper接口中抽象方法的聲明:

    /*** 傳入map員工對象數據* @param data* @return*/int insertEmpMap(Map data);

SQL語句:

    <!-- 傳入map的數據 使用的是map的key值 key = map key   --><insert id="insertEmpMap">insert into t_emp (emp_name,emp_salary) values(#{name},#{salary})</insert>

2.3 數據輸出

數據輸出總體上有兩種形式:

  • 增刪改操作返回的受影響行數:直接使用 int 或 long 類型接收即可
  • 查詢操作的查詢結果

2.3.1 返回單個簡單類型

返回單個簡單類型如何指定 : resultType的寫法,用返回值類型。

resultType的語法:

    1. 類的全限定符號
    • 1
    1. 別名簡稱
    • 指定查詢的輸出數據類型即可!并且插入場景下,實現主鍵數據回顯示!
    • 類型別名(typeAliases)
    • 1
    1. 自定義類型名字
    • 在 mybatis-config.xml 中全局設置:
    <!-- 單個類單獨定義別名 , 之后resultType 使用“自己設置的名字”   --><typeAliases><typeAlias type="com.wake.pojo.Employee" alias="自己設置名字"/></typeAliases><!-- 批量修改   --><typeAliases><!--  批量將包下的類 設置別名都為首字母小寫      --><package name="com.wake.pojo"/></typeAliases><!-- 批量后 想單獨設置單個類 使用注解單個類   --><!-- @Alias("666")   -->

2.3.2 返回實體類對象

resultType: 返回值類型

    <select id="queryEmpById" resultType="employee">select *from t_empwhere emp_Id = #{empId};</select>

要求:
查詢,返回單個實體類型,要求 列名 和 屬性名 要一致 !
這樣才可以進行實體類的屬性映射。

mybatis 可以開啟屬性列名的自動映射:
在 mybatis-config.xml中設置:

<!--   true開啟駝峰命名自動映射,即從經典數據庫列名 A_COLUMN 映射到經典 Java 屬性名 aColumn。--><setting name="mapUnderscoreToCamelCase" value="true"/>

1

2.3.3 返回Map類型

  • 接口:
Map<String,Object> selectEmpNameAndMaxSalary();
  • sql xml
<!-- Map<String,Object> selectEmpNameAndMaxSalary(); -->
<!-- 返回工資最高的員工的姓名和他的工資 -->
<select id="selectEmpNameAndMaxSalary" resultType="map">SELECTemp_name 員工姓名,emp_salary 員工工資,(SELECT AVG(emp_salary) FROM t_emp) 部門平均工資FROM t_emp WHERE emp_salary=(SELECT MAX(emp_salary) FROM t_emp)
</select>
  • junit測試
@Testpublic void mybatisTest01() throws IOException {// 1.讀取配置文件InputStream ips = Resources.getResourceAsStream("Mybatis-Config.xml");// 2. 創建sqlSession 數據庫連接工廠SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);// 3. 開啟sqlSession 數據庫連接SqlSession sqlSession = sqlSessionFactory.openSession();// 4. 確定mapper對象EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);// 5. 執行mapper方法Map<String, Object> stringObjectMap =employeeMapper.selectEmpNameAndMaxSalary();Set<Map.Entry<String, Object>> entries =stringObjectMap.entrySet();for (Map.Entry<String, Object> entry : entries) {String key = entry.getKey();Object value = entry.getValue();System.out.println(key + "---" + value);}sqlSession.close();}

1

2.3.4 返回List類型

返回值是集合,resultType不需要指定集合類型,只需要指定泛型即可。
因為
mybatis -> ibatis -> selectOne 單個 | selectList 集合 -> selectOne 調用[selectList]

  • 接口
    /*** 查詢全部員工對象* @return*/List<Employee> selectAll();
  • mapper.xml
    <!-- List<Employee> selectAll(); --><select id="selectAll" resultType="employee">select emp_id empId,emp_name empName,emp_salary empSalaryfrom t_emp</select>
  • 測試
    @Testpublic void mybatisTest01() throws IOException {// 1.讀取配置文件InputStream ips = Resources.getResourceAsStream("Mybatis-Config.xml");// 2. 創建sqlSession 數據庫連接工廠SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);// 3. 開啟sqlSession 數據庫連接SqlSession sqlSession = sqlSessionFactory.openSession();// 4. 確定mapper對象EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);// 5. 執行mapper方法List<Employee> employees = employeeMapper.selectAll();for (Employee employee : employees) {System.out.println(employee);}sqlSession.close();}

1

2.3.5 返回主鍵值

1. 自增長類型主鍵

  • 接口
    /*** 插入一條員工信息* @param employee* @return*/int insertEmp(Employee employee);
  • xml
    <insert id="insertEmp">insert into t_emp(emp_Name,emp_salary)values(#{empName},#{empSalary});</insert>
  • 測試
    @Testpublic void mybatisTest01() throws IOException {// 1.讀取配置文件InputStream ips = Resources.getResourceAsStream("Mybatis-Config.xml");// 2. 創建sqlSession 數據庫連接工廠SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);// 3. 開啟sqlSession 數據庫連接【自動開啟JDBC】// 自動開啟事務SqlSession sqlSession = sqlSessionFactory.openSession();// 4. 執行代理對象EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);// 5. 執行mapper方法Employee e1 = new Employee();e1.setEmpName("亞倫");e1.setEmpSalary(147.6);int i = employeeMapper.insertEmp(e1);System.out.println(i);// 6. 釋放資源 和 提交事務sqlSession.commit();sqlSession.close();}

1
1

主鍵回顯:

  • xml
<!--useGeneratedKeys="true"  : 開啟獲取數據庫主鍵值keyColumn="emp_id"       : 主鍵列的值keyProperty="empId"      : 接收主鍵列值的屬性--><insert id="insertEmp" useGeneratedKeys="true" keyColumn="emp_id" keyProperty="empId">insert into t_emp(emp_Name,emp_salary)values(#{empName},#{empSalary});</insert>
  • 測試:
    @Testpublic void mybatisTest01() throws IOException {// 1.讀取配置文件InputStream ips = Resources.getResourceAsStream("Mybatis-Config.xml");// 2. 創建sqlSession 數據庫連接工廠SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);// 3. 開啟sqlSession 數據庫連接【自動開啟JDBC】// 自動開啟事務SqlSession sqlSession = sqlSessionFactory.openSession(true);// 4. 執行代理對象EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);// 5. 執行mapper方法Employee e1 = new Employee();e1.setEmpName("內爾");e1.setEmpSalary(258.9);// 提交前 主鍵值System.out.println("前:"+e1.getEmpId());System.out.println("=============================");int i = employeeMapper.insertEmp(e1);System.out.println(i);// 提交后 主鍵值System.out.println("后:"+e1.getEmpId());// 6. 釋放資源 和 提交事務//sqlSession.commit();sqlSession.close();}

1
1


2. 非自增長類型主鍵

新創建一個 表(不添加自動更新索引)
手動添加UUID

create TABLE teacher(t_id VARCHAR(64) PRIMARY KEY,t_name VARCHAR(20) 
)
  • mapper接口
int insertTeacher(Teacher teacher);
  • xml
<mapper namespace="com.wake.mapper.TeacherMapper"><insert id="insertTeacher"><!--order="BEFORE|AFTER"  確定是在插入語句執行前還是后執行resultType=""          返回值類型keyProperty=""         查詢結果是給哪個屬性--><selectKey order="BEFORE" resultType="string" keyProperty="tId">select replace(UUID(),"-","");</selectKey>insert into teacher(t_id,t_name) values(#{tId},#{tName});</insert>
</mapper>
  • 測試
    @Testpublic void mybatisTest02() throws IOException {// 1.讀取配置文件InputStream ips = Resources.getResourceAsStream("Mybatis-Config.xml");// 2. 創建sqlSession 數據庫連接工廠SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);// 3. 開啟sqlSession 數據庫連接【自動開啟JDBC】// 自動開啟事務SqlSession sqlSession = sqlSessionFactory.openSession(true);// 4. 執行代理對象TeacherMapper teacherMapper = sqlSession.getMapper(TeacherMapper.class);// 5. 執行mapper方法Teacher teacher = new Teacher();teacher.setTName("維克");// 使用mybatis 在xml中定義uuid//String uuid = UUID.randomUUID().toString().replace("-", "");//teacher.setTId(uuid);System.out.println("UUID BEFORE:"+teacher.getTId());int i = teacherMapper.insertTeacher(teacher);System.out.println("UUID AFTER:"+teacher.getTId());System.out.println(i);// 6. 釋放資源 和 提交事務//sqlSession.commit();sqlSession.close();}
  • 結果:
    1
    1

2.3.6 實體類屬性和數據庫字段對應關系

  1. 別名對應
    將字段的別名設置成和實體類屬性一致。
<!-- 編寫具體的SQL語句,使用id屬性唯一的標記一條SQL語句 -->
<!-- resultType屬性:指定封裝查詢結果的Java實體類的全類名 -->
<select id="selectEmployee" resultType="com.doug.mybatis.entity.Employee"><!-- Mybatis負責把SQL語句中的#{}部分替換成“?”占位符 --><!-- 給每一個字段設置一個別名,讓別名和Java實體類中屬性名一致 -->select emp_id empId,emp_name empName,emp_salary empSalary from t_emp where emp_id=#{maomi}</select>
  1. 全局配置自動識別駝峰式命名規則
    在Mybatis全局配置文件加入如下配置:
<!-- 使用settings對Mybatis全局進行設置 -->
<settings><!-- 將xxx_xxx這樣的列名自動映射到xxXxx這樣駝峰式命名的屬性名 --><setting name="mapUnderscoreToCamelCase" value="true"/></settings>

就可以不使用別名:

<!-- Employee selectEmployee(Integer empId); -->
<select id="selectEmployee" resultType="com.doug.mybatis.entity.Employee">select emp_id,emp_name,emp_salary from t_emp where emp_id=#{empId}</select>
  1. 使用resultMap
    使用resultMap標簽定義對應關系,再在后面的SQL語句中引用這個對應關系
<!-- 專門聲明一個resultMap設定column到property之間的對應關系 -->
<resultMap id="selectEmployeeByRMResultMap" type="com.doug.mybatis.entity.Employee"><!-- 使用id標簽設置主鍵列和主鍵屬性之間的對應關系 --><!-- column屬性用于指定字段名;property屬性用于指定Java實體類屬性名 --><id column="emp_id" property="empId"/><!-- 使用result標簽設置普通字段和Java實體類屬性之間的關系 --><result column="emp_name" property="empName"/><result column="emp_salary" property="empSalary"/></resultMap><!-- Employee selectEmployeeByRM(Integer empId); -->
<select id="selectEmployeeByRM" resultMap="selectEmployeeByRMResultMap">select emp_id,emp_name,emp_salary from t_emp where emp_id=#{empId}</select>

2.4 CRUD強化練習

  • 數據庫準備
CREATE TABLE `user` (`id` INT(11) NOT NULL AUTO_INCREMENT,`username` VARCHAR(50) NOT NULL,`password` VARCHAR(50) NOT NULL,PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
  • 實體類準備
public class User {private int id;private String username;private String password;
  • 接口Mapper
public interface UserMapper {/*** 增加* @param user* @return*/int insert(User user);/*** 修改* @param user* @return*/int update(User user);/*** 刪除* @param id* @return*/int delete(Integer id);/*** 根據ID查詢一條User數據* @param id* @return*/User selectById(Integer id);/*** 查詢全部數據* @return*/List<User> selectAll();
}
  • Mapper.xml
<mapper namespace="com.wake.mapper.UserMapper"><insert id="insert">insert into user(username,password) values(#{username},#{password});</insert><update id="update">update user set username = #{username},password = #{password} where id = #{id};</update><delete id="delete">delete from user where id = #{id};</delete><select id="selectById" resultType="user">select id,username,password from user where id = #{id};</select><select id="selectAll" resultType="user">select * from user;</select>
</mapper>
  • 測試
    @Testpublic void insert01() throws IOException {InputStream ips = Resources.getResourceAsStream("Mybatis-Config.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);SqlSession sqlSession = sqlSessionFactory.openSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);User user = new User();user.setUsername("knell");user.setPassword("999");int insert = userMapper.insert(user);System.out.println(insert);sqlSession.commit();sqlSession.close();}@Testpublic void delete02() throws IOException {InputStream ips = Resources.getResourceAsStream("Mybatis-Config.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);SqlSession sqlSession = sqlSessionFactory.openSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);int delete = userMapper.delete(3);System.out.println(delete);sqlSession.commit();sqlSession.close();}@Testpublic void update03() throws IOException {InputStream ips = Resources.getResourceAsStream("Mybatis-Config.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);SqlSession sqlSession = sqlSessionFactory.openSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);User user = userMapper.selectById(4);user.setUsername("測試");user.setPassword("123456");int update = userMapper.update(user);System.out.println(update);sqlSession.commit();sqlSession.close();}@Testpublic void selectById04() throws IOException {InputStream ips = Resources.getResourceAsStream("Mybatis-Config.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);SqlSession sqlSession = sqlSessionFactory.openSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);User user = userMapper.selectById(1);System.out.println(user);sqlSession.commit();sqlSession.close();}@Testpublic void selectAll05() throws IOException {InputStream ips = Resources.getResourceAsStream("Mybatis-Config.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);SqlSession sqlSession = sqlSessionFactory.openSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);List<User> users = userMapper.selectAll();System.out.println(users);sqlSession.commit();sqlSession.close();}

1
注意更新要先根據ID查找出對象數據

2.5 mapperXML標簽總結

  • insert – 映射插入語句。
  • update – 映射更新語句。
  • delete – 映射刪除語句。
  • select – 映射查詢語句。
屬性描述
id在命名空間中唯一的標識符,可以被用來引用這條語句。
resultType期望從這條語句中返回結果的類全限定名或別名。 注意,如果返回的是集合,那應該設置為集合包含的類型,而不是集合本身的類型。 resultType 和 resultMap 之間只能同時使用一個。
resultMap對外部 resultMap 的命名引用。結果映射是 MyBatis 最強大的特性,如果你對其理解透徹,許多復雜的映射問題都能迎刃而解。 resultType 和 resultMap 之間只能同時使用一個。
timeout這個設置是在拋出異常之前,驅動程序等待數據庫返回請求結果的秒數。默認值為未設置(unset)(依賴數據庫驅動)。
statementType可選 STATEMENT,PREPARED 或 CALLABLE。這會讓 MyBatis 分別使用 Statement,PreparedStatement 或 CallableStatement,默認值:PREPARED。

總結

Mybatis操作流程:
1
ibatis 和 Mybatis :
1
Mybatis 文檔:
Mybatis 中文官網
1
類型的別名:

別名映射的類型
_bytebyte
_char (since 3.5.10)char
_character (since 3.5.10)char
_longlong
_shortshort
_intint
_integerint
_doubledouble
_floatfloat
_booleanboolean
stringString
byteByte
char (since 3.5.10)Character
character (since 3.5.10)Character
longLong
shortShort
intInteger
integerInteger
doubleDouble
floatFloat
booleanBoolean
dateDate
decimalBigDecimal
bigdecimalBigDecimal
bigintegerBigInteger
objectObject
object[]Object[]
mapMap
hashmapHashMap
listList
arraylistArrayList
collectionCollection

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

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

相關文章

Web組態可視化編輯器 快速繪制組態

隨著工業智能制造的發展&#xff0c;工業企業對設備可視化、遠程運維的需求日趨強烈&#xff0c;傳統的單機版組態軟件已經不能滿足越來越復雜的控制需求&#xff0c;那么實現Web組態可視化界面成為了主要的技術路徑。 行業痛點 對于軟件服務商來說&#xff0c;將單機版軟件轉變…

計算機視覺基礎知識(十六)--圖像識別

圖像識別 信息時代的一門重要技術;目的是讓計算機代替人類處理大量的物理信息;隨著計算機技術的發展,人類對圖像識別技術的認識越來越深刻;圖像識別技術利用計算機對圖像進行處理\分析\理解,識別不同模式的目標和對象;過程分為信息的獲取\預處理\特征抽取和選擇\分類器設計\分…

重拾C++之菜鳥刷算法第6篇---棧與隊列

棧與隊列 一、用棧實現隊列 題目 請你僅使用兩個棧實現先入先出隊列。隊列應當支持一般隊列支持的所有操作&#xff08;push、pop、peek、empty&#xff09;&#xff1a; 實現 MyQueue 類&#xff1a; void push(int x) 將元素 x 推到隊列的末尾int pop() 從隊列的開頭移除…

【Hadoop】使用Metorikku框架讀取hive數據統計分析寫入mysql

一、定義作業文件 作業文件 該文件將包括輸入源、輸出目標和要執行的配置文件的位置&#xff0c;具體內容如下 metrics:- /user/xrx/qdb.yaml # 此位置為hdfs文件系統目錄 inputs: output:jdbc:connectionUrl: "jdbc:mysql://233.233.233.233:3306/sjjc"user: &quo…

虛擬帆船:利用技術出海的探險家

在數字化的浪潮中&#xff0c;一個新時代的探險家誕生了。他們不是在尋找未知大陸的勇士&#xff0c;而是在尋求跨界電商和全球游戲市場的先鋒。這些現代探險家的帆船是由SOCKS5代理和代理IP構成的&#xff0c;他們的海圖則是由數據和市場分析繪制的。 出海的第一步&#xff1a…

WebServer -- 注冊登錄

目錄 &#x1f349;整體內容 &#x1f33c;流程圖 &#x1f382;載入數據庫表 提取用戶名和密碼 &#x1f6a9;同步線程登錄注冊 補充解釋 代碼 &#x1f618;頁面跳轉 補充解釋 代碼 &#x1f349;整體內容 概述 TinyWebServer 中&#xff0c;使用數據庫連接池實現…

Linux 內核irq_stack遍歷

環境Centos 4.18.0-80.el8.x86_64 一、x86架構堆棧類型說明 https://www.kernel.org/doc/Documentation/x86/kernel-stacks int get_stack_info(unsigned long *stack, struct task_struct *task,struct stack_info *info, unsigned long *visit_mask) {if (!stack)goto unk…

【深度學習筆記】計算機視覺——圖像增廣

圖像增廣 sec_alexnet提到過大型數據集是成功應用深度神經網絡的先決條件。 圖像增廣在對訓練圖像進行一系列的隨機變化之后&#xff0c;生成相似但不同的訓練樣本&#xff0c;從而擴大了訓練集的規模。 此外&#xff0c;應用圖像增廣的原因是&#xff0c;隨機改變訓練樣本可以…

Python + Selenium —— 下拉菜單處理!

傳統的下拉菜單 Select 元素&#xff0c;由一個 Select 一系列的 option 元素構成。 <select id"source" name"source"><option value"">--請選擇--</option><option value"1001">網絡營銷</option>&…

3.3 序列式容器-deque、stack、queue、heap、priority_queue

deque 3.1定義 std::deque&#xff08;雙端隊列&#xff09;是C標準模板庫&#xff08;STL&#xff09;中的一種容器&#xff0c;表示雙端隊列數據結構。它提供了在兩端高效地進行插入和刪除操作的能力。與vector的連續線性空間類似&#xff0c;但有所不同&#xff0c;deque動…

基于ssm旅社客房收費管理系統+vue

目 錄 目 錄 I 摘 要 III ABSTRACT IV 1 緒論 1 1.1 課題背景 1 1.2 研究現狀 1 1.3 研究內容 2 2 系統開發環境 3 2.1 vue技術 3 2.2 JAVA技術 3 2.3 MYSQL數據庫 3 2.4 B/S結構 4 2.5 SSM框架技術 4 3 系統分析 5 3.1 可行性分析 5 3.1.1 技術可行性 5 3.1.2 操作可行性 5 3…

STM32使用FlyMcu串口下載程序與STLink Utility下載程序

文章目錄 前言軟件鏈接一、FlyMcu串口下載程序原理優化手動修改跳線帽選項字節其他功能 二、STLink Utility下載程序下載程序選項字節固件更新 前言 本文主要講解使用FlyMcu配合USART串口為STM32下載程序、使用STLink Utility配合STLink為STM32下載程序&#xff0c;以及這兩個…

代碼隨想錄算法訓練營第62/63天| 503.下一個更大元素II、42. 接雨水、84.柱狀圖中最大的矩形

文章目錄 503.下一個更大元素II思路代碼 42. 接雨水思路代碼 84.柱狀圖中最大的矩形思路代碼 503.下一個更大元素II 題目鏈接&#xff1a;503.下一個更大元素II 文章講解&#xff1a;代碼隨想錄|503.下一個更大元素II 思路 和739. 每日溫度 (opens new window)也幾乎如出一轍&…

C++/數據結構:AVL樹

目錄 一、AVL樹的概念 二、AVL樹的實現 2.1節點定義 2.2節點插入 三、AVL樹的旋轉 3.1新節點插入較高左子樹的左側&#xff1a;右單旋 3.2新節點插入較高右子樹的右側&#xff1a;左單旋 3.3新節點插入較高左子樹的右側---左右&#xff1a;先左單旋再右單旋 3.4新節點插…

Rocky Linux 運維工具 Systemd

一、Systemd 的簡介 Systemd是一個用于管理Linux系統啟動進程和服務的系統和服務管理器&#xff0c;取代了傳統的init系統。它提供了并行啟動、依賴關系管理、動態加載服務文件等功能&#xff0c;成為現代Linux發行版中主流的初始化系統。 二、Systemd 的參數說明 [Unit] Des…

SLAM基礎知識-卡爾曼濾波

前言&#xff1a; 在SLAM系統中&#xff0c;后端優化部分有兩大流派。一派是基于馬爾科夫性假設的濾波器方法&#xff0c;認為當前時刻的狀態只與上一時刻的狀態有關。另一派是非線性優化方法&#xff0c;認為當前時刻狀態應該結合之前所有時刻的狀態一起考慮。 卡爾曼濾波是…

SD NAND:為車載顯示器注入智能與安全的心臟

SD NAND 在車載顯示器的應用 在車載顯示器上&#xff0c;SD NAND&#xff08;Secure Digital NAND&#xff09;可以有多種應用&#xff0c;其中一些可能包括&#xff1a; 導航數據存儲&#xff1a; SD NAND 可以用于存儲地圖數據、導航軟件以及車載系統的相關信息。這有助于提…

微服務day03-Nacos配置管理與Nacos集群搭建

一.Nacos配置管理 Nacos不僅可以作為注冊中心&#xff0c;可以進行配置管理 1.1 統一配置管理 統一配置管理可以實現配置的熱更新&#xff08;即不用重啟當服務發生變更時也可以直接更新&#xff09; dataId格式&#xff1a;服務名-環境名.yaml&#xff0c;分組一般使用默認…

InnoDB高級特性篇(5)-使用InnoDB的全文索引

InnoDB是MySQL數據庫的一個關系型存儲引擎。它提供了很多強大的功能&#xff0c;其中一個重要的功能是全文索引。全文索引允許我們在文本數據中進行高效的搜索&#xff0c;以找到包含特定關鍵詞的記錄。在本文中&#xff0c;我們將詳細介紹如何在InnoDB中使用全文索引。 首先&…

藍橋杯備戰刷題two(自用)

1.楊輝三角形 #include<iostream> using namespace std; #define ll long long const int N2e510; int a[N]; //1 0 0 0 0 0 0 //1 1 0 0 0 0 0 //1 2 1 0 0 0 0 //1 3 3 1 0 0 0 //1 4 6 4 1 0 0 //1 5 10 10 5 1 //前綴和思想 //第一列全為1,第二列為從0開始遞增1的序…