Mybatis學習之道(一)

lonecloud發表於2017-08-04

本例子為採用的mysql+maven+mybatis構建。

  初步學習mybatis:

    mybatis為一個半自動框架,相對於hibernate來說他更加輕巧,學習成本更低。

1.新建一個maven工程

2.在maven中配置依賴jar包

 1   <dependencies>
 2     <dependency>
 3       <groupId>junit</groupId>
 4       <artifactId>junit</artifactId>
 5       <version>4.11</version>
 6       <scope>test</scope>
 7     </dependency>
 8       <dependency>
 9           <groupId>org.mybatis</groupId>
10           <artifactId>mybatis</artifactId>
11           <version>3.4.1</version>
12       </dependency>
13       <dependency>
14           <groupId>mysql</groupId>
15           <artifactId>mysql-connector-java</artifactId>
16           <version>5.1.40</version>
17       </dependency>
18   </dependencies>

3.新建一個jdbc.properties檔案

 1 jdbc.driver=org.gjt.mm.mysql.Driver 2 jdbc.url=jdbc:mysql://localhost:3306/mybatisStudy 3 jdbc.username=root 4 jdbc.password=123456 

4.建立mybatis配置檔案

  propertis:匯入配置檔案

  

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6     <properties resource="jdbc.properties"></properties>
 7     <!--設定一些配置資訊-->
 8     <settings>
 9         <setting name="useGeneratedKeys" value="true"/>
10     </settings>
11     <!--設定別名-->
12     <typeAliases>
13         <typeAlias type="cn.lonecloud.d1.model.Blog" alias="Blog"></typeAlias>
14     </typeAliases>
15     <environments default="development">
16         <environment id="development">
17             <transactionManager type="JDBC"/>
18             <dataSource type="POOLED">
19                 <property name="driver" value="${jdbc.driver}"/>
20                 <property name="url" value="${jdbc.url}"/>
21                 <property name="username" value="${jdbc.username}"/>
22                 <property name="password" value="${jdbc.password}"/>
23             </dataSource>
24         </environment>
25     </environments>
26     <!--mapper對應的檔案-->
27     <mappers>
28         <mapper resource="mapper/BlogMapper.xml"></mapper>
29     </mappers>
30 </configuration>

5建立資料庫

  

 1 SET NAMES utf8;
 2 SET FOREIGN_KEY_CHECKS = 0;
 3 
 4 -- ----------------------------
 5 --  Table structure for `blog`
 6 -- ----------------------------
 7 DROP TABLE IF EXISTS `blog`;
 8 CREATE TABLE `blog` (
 9   `id` varchar(32) NOT NULL DEFAULT '',
10   `name` varchar(255) DEFAULT '',
11   PRIMARY KEY (`id`)
12 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
13 
14 SET FOREIGN_KEY_CHECKS = 1;

 

 

6.建立POJO類

 1 package cn.lonecloud.d1.model;
 2 
 3 /**
 4  * Created by lonecloud on 17/3/17.
 5  */
 6 public class Blog {
 7     private String id;
 8 
 9     private String name;
10 
11     public String getId() {
12         return id;
13     }
14 
15     @Override
16     public String toString() {
17         return "Blog{" +
18                 "id='" + id + '\'' +
19                 ", name='" + name + '\'' +
20                 '}';
21     }
22 
23     public void setId(String id) {
24         this.id = id;
25     }
26 
27     public String getName() {
28         return name;
29     }
30 
31     public void setName(String name) {
32         this.name = name;
33     }
34 }

.7建立對應的介面類

  由於mybatis是介面式程式設計,會將對應的介面通過對映的方式在其容器中通過代理方式建立出一個物件,所以不需要建立實現類

 1 package cn.lonecloud.d1.dao;
 2 
 3 import cn.lonecloud.d1.model.Blog;
 4 
 5 /**
 6  * Created by lonecloud on 17/3/17.
 7  * mybatis介面式程式設計
 8  */
 9 public interface BlogMapper {
10     Blog selectOne(String id);
11 }

8.編寫對應的mapper檔案

  namespce:名稱空間,為對這個mapper檔案進行唯一性標示,最好使用對應的介面全類名

  select:篩選語句相當於說明這是一個select查詢 id標明為該類下面的某個方法,

  resultType:返回資料型別,

  #{id}:為傳遞過來的引數,最好是和引數名相同

1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE mapper
3         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
4         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
5 <mapper namespace="cn.lonecloud.d1.dao.BlogMapper">
6     <select id="selectOne" resultType="Blog">
7         select * from Blog where id = #{id}
8     </select>
9 </mapper>

9.編寫測試類:

 1 package cn.lonecloud.d1;
 2 
 3 import cn.lonecloud.d1.dao.BlogMapper;
 4 import cn.lonecloud.d1.model.Blog;
 5 import org.apache.ibatis.io.Resources;
 6 import org.apache.ibatis.session.SqlSession;
 7 import org.apache.ibatis.session.SqlSessionFactory;
 8 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 9 import org.junit.Test;
10 
11 import java.io.IOException;
12 import java.io.InputStream;
13 
14 /**
15  * Created by lonecloud on 17/3/17.
16  */
17 public class SessionTest {
18 
19     SqlSessionFactory sqlSessionFactory;
20     @Test
21     public void session() throws IOException {
22         String resource = "mybatis-config.xml";//配置檔案
23         InputStream inputStream = Resources.getResourceAsStream(resource);//讀取配置檔案
24         sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//獲取sqlSession 物件
25         System.out.println(sqlSessionFactory);
26         SqlSession session = sqlSessionFactory.openSession();//開啟session
27         try{
28             BlogMapper blogMapper = session.getMapper(BlogMapper.class);
29             Blog blog = blogMapper.selectOne("sasa");
30             System.out.println(blog);
31         }finally {
32             session.close();
33         }
34     }
35 }

注意的是SqlSession位非執行緒安全的類,這個如果定義為類變數會導致執行緒安全性問題!!

 

本例子共享於gitOSChina中:連結

 

相關文章