1. 程式人生 > 其它 >MyBatis 速成手冊

MyBatis 速成手冊

入門案例

現有一張資料表:

mysql> use mybatis;
Database changed
mysql> select * from tbl_employee;
+----+-----------+--------+-------------+
| id | last_name | gender | email |
+----+-----------+--------+-------------+
|  1 | tom | 0      | [email protected] |
+----+-----------+--------+-------------+
1 row in set (0.00 sec)

該如何通過MyBatis對其進行查詢?首先建立對應的Java類:

package com.wwj.mybatis.bean;

public class Employee {
 
 private Integer id;
 private String lastName;
 private String email;
 private String gender;
 
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getLastName() {
  
return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getGender() { return gender; } public void setGender(String gender) { this
.gender = gender; } @Override public String toString() { return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + "]"; } }

其次編寫MyBatis的全域性配置檔案(mybatis-config.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:///mybatis"/>
          <property name="username" value="root"/>
           <property name="password" value="123456"/>
         </dataSource>
     </environment>
 </environments>
 <mappers>
  <mapper resource="EmployeeMapper.xml"/>
 </mappers>
</configuration>

全域性配置檔案中主要配置的是資料來源資訊,然後是最後的mappers標籤,該標籤配置的是sql語句的對映檔案。

所以我們接著建立sql語句的對映檔案(EmployeeMapper.xml):

<?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.wwj.mybatis.bean.Employee">
  <select id="selectEmp" resultType="com.wwj.mybatis.bean.Employee">
     select id,last_name lastName,email,gender from tbl_employee where id = #{id}
   </select>
</mapper>

其中mapper標籤的namespace屬性設定的是需要對映的類全名;select標籤表示查詢語句,其中的id屬性是該sql的唯一標識,resultType表示返回值的型別;然後在select標籤中編寫需要執行的sql語句。

一切準備就緒後,開始編寫測試程式碼:

@Test
void test() throws IOException {
 String resource = "mybatis-config.xml";
 InputStream inputStream = Resources.getResourceAsStream(resource);
 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 SqlSession session = sessionFactory.openSession();
 Employee employee = session.selectOne("com.wwj.mybatis.bean.Employee.selectEmp",1);
 System.out.println(employee);
 session.close();
}

https://mp.weixin.qq.com/s/wmkRTbBjWMd-SDaJm6W-FA

故鄉明