【Mybatis】MyBatis對錶執行CRUD操作(三) 【Mybatis】MyBatis配置檔案的使用(二)
阿新 • • 發佈:2019-01-14
本例在【Mybatis】MyBatis配置檔案的使用(二)基礎上繼續學習對錶執行CRUD操作
使用MyBatis對錶執行CRUD操作
1、定義sql對映xml檔案(EmployeeMapper.xml)
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 3 <!-- 4 namespace:名稱空間 5 id:唯一標識6 resultType:返回值型別 7 #{id}:從傳過來的引數中取出id值 8 --> 9 <mapper namespace="com.hd.test.mapper.EmployeeMapper"> 10 <select id="getEmployeeById" 11 resultType="com.hd.test.pojo.Employee"> 12 select id, last_name lastName, gender, email from employee where id = 13 #{id}14 </select> 15 16 <!-- public Long insertEmployee(Employee employee); --> 17 <!-- parameterType 可寫可不寫 --> 18 <insert id="insertEmployee" parameterType="com.hd.test.pojo.Employee" > 19 insert into employee(last_name, email, gender) values(#{lastName}, #{email}, #{gender})20 </insert> 21 22 <!-- public boolean updateEmployee(Employee employee); --> 23 <update id="updateEmployee"> 24 update employee 25 set last_name = #{lastName}, email = #{email}, gender = #{gender} 26 where 27 id = #{id} 28 </update> 29 30 <!-- public Integer deleteEmployeeById(Integer id); --> 31 <delete id="deleteEmployeeById"> 32 delete from employee where id = #{id} 33 </delete> 34 35 </mapper>
2、在mybatis-config.xml檔案中註冊這個對映檔案EmployeeMapper.xml
<?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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <!-- 配置資料庫連線資訊 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test_mybatis?allowPublicKeyRetrieval=true" /> <property name="username" value="admin" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <mappers> <!-- 新增sql射檔案到Mybatis的全域性配置檔案中 --> <mapper resource="mapper/EmployeeMapper.xml" /> </mappers> </configuration>
3、編寫一個EmployeeMapper介面
1 package com.hd.test.mapper; 2 3 import com.hd.test.pojo.Employee; 4 5 public interface EmployeeMapper { 6 7 public Employee getEmployeeById(Integer id); 8 9 // 新增 10 public Long insertEmployee(Employee employee); 11 12 // 修改 13 public boolean updateEmployee(Employee employee); 14 15 // 刪除 16 public Integer deleteEmployeeById(Integer id); 17 18 }
4、編寫mybatis單元測試類(TestMybatis.java)
1 package com.hd.test.mybatis; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 6 import javax.sound.midi.Soundbank; 7 8 import org.apache.ibatis.io.Resources; 9 import org.apache.ibatis.session.SqlSession; 10 import org.apache.ibatis.session.SqlSessionFactory; 11 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 12 import org.junit.Test; 13 14 import com.hd.test.mapper.EmployeeMapper; 15 import com.hd.test.pojo.Employee; 16 17 import sun.print.resources.serviceui; 18 19 20 21 /** 22 * 1、SqlSession代表和資料庫的一次會話,用完必須關閉 23 2、SqlSession和connection一樣都是非執行緒安裝的,每次使用都應該去獲取新物件 24 3、mapper介面沒有實現累,但是mybatis會為這個介面生成一個代理物件 25 (將介面和xml進行繫結) 26 EmployeeMapper empMapper = sqlSession.getMapper(EmployeeMapper.class) 27 4、連個重要的配置檔案: 28 mybatis的全域性配置檔案:包含資料庫連線資訊,事物管理等系統環境資訊 29 sql對映檔案:儲存了每一個sql語句的對映資訊: 30 將sql抽取出來。 31 * 32 */ 33 public class TestMybatis { 34 35 /** 36 * 測試增刪改 37 * 1、mybatis允許增刪改直接定義一下型別返回值 38 * Ingteger、Long、Boolean 39 * 2、需要手動提交資料 40 * SqlSession session = sqlSessionFactory.openSession(); ==> 手動提交 41 * SqlSession session = sqlSessionFactory.openSession(true); ==> 自動提交 42 * @throws IOException 43 */ 44 45 46 // 插入 47 @Test 48 public void test1() throws IOException { 49 50 // 獲取SqlSessionFactory 51 InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); 52 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 53 // 獲取的sqlsession不會自動提交資料 54 SqlSession session = sqlSessionFactory.openSession(); 55 56 try { 57 EmployeeMapper mapper = session.getMapper(EmployeeMapper.class); 58 59 // 1、插入資料 60 Employee employee = new Employee("小紅", "1", "[email protected]"); 61 Long returnValue = mapper.insertEmployee(employee); 62 System.out.println("插入返回值:" + returnValue); 63 64 // 手動提交資料 65 session.commit(); 66 67 } finally { 68 session.close(); 69 } 70 } 71 72 // 修改 73 @Test 74 public void test2() throws IOException { 75 76 // 獲取SqlSessionFactory 77 InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); 78 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 79 80 // 獲取的sqlsession 自動提交資料 81 SqlSession session = sqlSessionFactory.openSession(true); 82 try { 83 EmployeeMapper mapper = session.getMapper(EmployeeMapper.class); 84 85 // 2、更新資料 86 Employee employee = new Employee(1, "小紅", "0", "[email protected]"); 87 boolean returnValue = mapper.updateEmployee(employee); 88 System.out.println("更新返回值:" + returnValue); 89 90 } finally { 91 session.close(); 92 } 93 } 94 95 // 刪除 96 @Test 97 public void test3() throws IOException { 98 99 // 獲取SqlSessionFactory 100 InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); 101 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 102 103 // 獲取的sqlsession 自動提交資料 104 SqlSession session = sqlSessionFactory.openSession(true); 105 try { 106 EmployeeMapper mapper = session.getMapper(EmployeeMapper.class); 107 108 // 3、刪除資料 109 Integer returnValue = mapper.deleteEmployeeById(8); 110 System.out.println("刪除返回值:" + returnValue); 111 112 } finally { 113 session.close(); 114 } 115 } 116 117 118 119 /** 120 * 查詢 121 * @throws IOException 122 */ 123 @Test 124 public void test() throws IOException { 125 // 1、根據mybatis全域性配置檔案,獲取SqlSessionFactory 126 String resource = "mybatis-config.xml"; 127 // 使用MyBatis提供的Resources類載入mybatis的配置檔案,獲取輸入流 128 InputStream inputStream = Resources.getResourceAsStream(resource); 129 // 構建sqlSession的工廠 130 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 131 132 // 2、從SqlSession工廠中,獲取sqlsession,用來執行sql 133 SqlSession session = sqlSessionFactory.openSession(); 134 try { 135 // 查詢selectOne 136 // @param statement Unique identifier matching the statement to use. 一個唯一標識 137 // @param parameter A parameter object to pass to the statement. 引數 138 EmployeeMapper mapper = session.getMapper(EmployeeMapper.class); 139 Employee employee = mapper.getEmployeeById(1); 140 // 輸出資訊 141 System.out.println("查詢返回值:" + employee); 142 } finally { 143 // 關閉session 144 session.close(); 145 } 146 } 147 148 149 }
5、執行單元測試類,結果如下:
插入返回主鍵
在實際專案中,插入一條資料,id是資料庫自動生成的,但是我們插入完資料,往往需要返回資料的id進行使用。
1、在EmployeeMapper.xml對映檔案中加入2條sql
1 <!-- parameterType 可寫可不寫 --> 2 <insert id="insertEmployee" parameterType="com.hd.test.pojo.Employee"> 3 insert into employee(last_name, email, gender) values(#{lastName}, #{email}, #{gender}) 4 </insert> 5 6 <!-- 7 獲取自增主鍵的值: 8 mysql支援自增主鍵,自增主鍵值的獲取,mybatis也是利用statement.genGenreatedKeys() 9 useGeneratedKeys="true",使用自增主鍵獲取主鍵值策略 10 keyProperty:指定對應的主鍵屬性,也就是mybatis獲取到主鍵值以後,將這個值封裝給JavaBean的屬性 11 --> 12 <insert id="insertEmployeeReturnId" parameterType="com.hd.test.pojo.Employee" useGeneratedKeys="true" keyProperty="id"> 13 insert into employee(last_name, email, gender) values(#{lastName}, #{email}, #{gender}) 14 </insert>
2、EmployeeMapper介面中加入方法
1 // 新增 2 public Integer insertEmployee(Employee employee); 3 4 // 新增並返回id 5 public Integer insertEmployeeReturnId(Employee employee);
3、單元測試類方法
1 @Test 2 public void test5() throws IOException { 3 4 // 獲取SqlSessionFactory 5 InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); 6 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 7 8 // 獲取的sqlsession自動提交資料 9 SqlSession session = sqlSessionFactory.openSession(true); 10 try { 11 EmployeeMapper mapper = session.getMapper(EmployeeMapper.class); 12 13 // 插入資料 14 Employee employee = new Employee("小黑", "1", "[email protected]"); 15 Integer returnValue = mapper.insertEmployee(employee); 16 System.out.println("插入小黑返回值:" + returnValue); 17 System.out.println("插入後小黑物件:" + employee); 18 19 Employee employee2 = new Employee("小白", "1", "[email protected]"); 20 Integer returnValue2 = mapper.insertEmployeeReturnId(employee2); 21 System.out.println("插入小黑返回值:" + returnValue2); 22 System.out.println("插入後小黑物件:" + employee2); 23 24 } finally { 25 session.close(); 26 } 27 }
4、執行單元測試類,結果如下: