MyBatis是一個支持普通SQL查詢,存儲過程和高級映射的優秀持久層框架。MyBatis消除了幾乎所有的JDBC代碼和參數的手工設置以及對結果集的檢索封裝。MyBatis可以使用簡單的XML或注解用于配置和原始映射,將接口和Java的POJO(Plain Old Java Objects,普通的Java對象)映射成數據庫中的記錄。
一對一映射
在生活中,一對一的例子還是有的,比如啦,學生和身份證哦,或者在我國,實行的是一夫一妻制度哦。那么我們以學生和身份證每個學生只有一張身份證,而每張身份證的主人當然只有一個啦。
數據庫腳本:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
-- 刪除數據庫 drop database if exists mybaits; -- 創建數據庫 create database if not exists mybatis default character set utf8; -- 選擇數據庫 use mybatis; -- 刪除數據表 drop table if exists student ; drop table if exists card; -- 創建數據表 create table card( cid int ( 255 ), num varchar( 18 ), constraint pk_cid primary key (cid) ); create table student( sid int ( 255 ), sname varchar( 32 ), scid int ( 255 ), constraint pk_sid primary key (sid), constraint fk_scid foreign key (scid) references card(cid) ); -- 增加測試數據 insert into card (cid,num) values( 1 , '123456789012345678' ); insert into student (sid,sname,scid) values( 1 , '哈哈' , 1 ); |
新建一個one2one.Card.java類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
package one2one; import java.io.Serializable; /** * 身份證 * @author Administrator * */ @SuppressWarnings ( "serial" ) public class Card implements Serializable{ private Integer cid; private String num; public Integer getCid() { return cid; } public void setCid(Integer cid) { this .cid = cid; } public String getNum() { return num; } public void setNum(String num) { this .num = num; } } |
新建one2one.Student.java類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
package one2one; import java.io.Serializable; /** * 學生 * @author Administrator * */ @SuppressWarnings ( "serial" ) public class Student implements Serializable{ private Integer sid; private String sname; private Card card; public Integer getSid() { return sid; } public void setSid(Integer sid) { this .sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this .sname = sname; } public Card getCard() { return card; } public void setCard(Card card) { this .card = card; } } |
在one2one包下新建CardMapper.xml文件
1
2
3
4
5
6
7
8
9
|
<?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= "cardNameSpace" > <resultMap type= "one2one.Card" id= "cardMap" > <id column= "cid" property= "cid" /> <result column= "num" property= "num" /> </resultMap> </mapper> |
同理,在one2one包下新建StudentMapper.xml文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<?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= "studentNameSpace" > <resultMap type= "one2one.Student" id= "studentMap" > <id column= "sid" property= "sid" /> <result column= "sname" property= "sname" /> <!-- 關聯字段不要寫 --> </resultMap> <select id= "findById" parameterType= "integer" resultMap= "studentMap" > select s.sid,s.sname,c.cid,c.num from student s,card c where s.scid = c.cid and s.sid = #{sid} </select> </mapper> |
在src下新建一個mybatis.cfg.xml文件,并包含StudentMapper.xml和CardMapper.xml文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
<?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 = "mysql_developer" > <!-- 連接MySQL環境信息 --> <environment id= "mysql_developer" > <!-- MyBatis使用jdbc事務管理器 --> <transactionManager type= "jdbc" /> <!-- MyBatis使用連接池方式來獲取連接對象 --> <dataSource type= "pooled" > <!-- 配置與數據庫交互的 4 個必要屬性 --> <property name= "driver" value= "com.mysql.jdbc.Driver" /> <property name= "url" value= "jdbc:mysql://127.0.0.1:3306/mybatis" /> <property name= "username" value= "root" /> <property name= "password" value= "mysqladmin" /> </dataSource> </environment> <!-- 連接Oracle環境信息 --> <environment id= "oracle_developer" > <!-- MyBatis使用jdbc事務管理器 --> <transactionManager type= "jdbc" /> <!-- MyBatis使用連接池方式來獲取連接對象 --> <dataSource type= "pooled" > <!-- 配置與數據庫交互的 4 個必要屬性 --> <property name= "driver" value= "oracle.jdbc.driver.OracleDriver" /> <property name= "url" value= "jdbc:oracle:thin:@127.0.0.1:1521:orcl" /> <property name= "username" value= "scott" /> <property name= "password" value= "tiger" /> </dataSource> </environment> </environments> <!-- 加載映射文件 --> <mappers> <mapper resource= "one2one/CardMapper.xml" /> <mapper resource= "one2one/StudentMapper.xml" /> </mappers> </configuration> |
在util包下新建一個工具類MyBatisUtil.java類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
package util; import java.io.IOException; import java.io.Reader; import java.sql.Connection; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisUtil { private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>(); public static SqlSessionFactory sqlSessionFactory ; //私有化構造方法 private MyBatisUtil(){} //加載位于src/Mybatis.cfg.xml static { try { Reader reader = Resources.getResourceAsReader( "mybatis.cfg.xml" ); sqlSessionFactory= new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); } } /** * 獲取SQLSession * @return */ public static SqlSession getSqlSession(){ //從當前線程中獲取SqlSession對象 SqlSession sqlSession = threadLocal.get(); if (sqlSession == null ){ if (sqlSessionFactory != null ){ sqlSession = sqlSessionFactory.openSession(); //講sqlSession與當前線程綁定在一起 threadLocal.set(sqlSession); } } return sqlSession; } /** * 關閉SqlSession 并與當前線程分開 */ public static void closeSqlSession(){ //從當前線程中獲取SqlSession對象 SqlSession sqlSession = threadLocal.get(); //如果SqlSession對象非空 if (sqlSession != null ){ //關閉SqlSession對象 sqlSession.close(); //分離當前線程與SqlSession的關系 threadLocal.remove(); } } //測試 public static void main(String[] args) { SqlSession sqlSession = MyBatisUtil.getSqlSession(); Connection conn= sqlSession.getConnection(); System.out.println(conn != null ? "連接成功" : "連接失敗" ); } } |
新建持久層類StuentCardDAO.java類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
package one2one; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import util.MyBatisUtil; /** * 持久層 * @author Administrator * */ public class StudentCardDAO { /** * 查詢1號學生的信息與身份證信息 * @param id * @return * @throws Exception */ public Student findById(Integer id) throws Exception{ SqlSession sqlSession = null ; try { sqlSession = MyBatisUtil.getSqlSession(); return sqlSession.selectOne( "studentNameSpace.findById" , id); } catch (Exception e) { e.printStackTrace(); throw e; } finally { MyBatisUtil.closeSqlSession(); } } //測試 查詢1號學生的信息與身份證信息 @Test public void testFindById() throws Exception{ StudentCardDAO dao = new StudentCardDAO(); Student student = dao.findById( 1 ); System.out.println(student.getSid()+ ":" +student.getSname() } } |
這時我們只能查詢1號學生的姓名,但是我們不能去查詢它的身份號號,因為此時的card屬性的值為null,從StudentMapper.xml中可以看出
1
|
<select id= "findById" parameterType= "integer" resultMap= "studentMap" > |
MyBatis在解析這一句的時候只能將查詢的數據封裝到sid,sname中,所以怎么辦?
在StudentMapper.xml中的
1
2
3
4
|
<resultMap type= "one2one.Card" id= "cardMap" > <id column= "cid" property= "cid" /> <result column= "num" property= "num" /> </resultMap> |
增加
1
2
3
4
5
|
<!-- 引入CardMapper.xml文件中的映射信息 property表示Student的關聯屬性 --> <association property= "card" resultMap= "cardNameSpace.cardMap" /> |
那么此時的StudentMapper.xml的完整內容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<?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= "studentNameSpace" > <resultMap type= "one2one.Student" id= "studentMap" > <id column= "sid" property= "sid" /> <result column= "sname" property= "sname" /> <!-- 引入CardMapper.xml文件中的映射信息 property表示Student的關聯屬性 --> <association property= "card" resultMap= "cardNameSpace.cardMap" /> </resultMap> <select id= "findById" parameterType= "integer" resultMap= "studentMap" > select s.sid,s.sname,c.cid,c.num from student s,card c where s.scid = c.cid and s.sid = #{sid} </select> </mapper> |
現在可以測試學生的身份證號碼了
將持久層類StuentCardDAO.java類的測試方法改為
1
2
3
4
5
6
7
|
//測試 查詢1號學生的信息與身份證信息 @Test public void testFindById() throws Exception{ StudentCardDAO dao = new StudentCardDAO(); Student student = dao.findById( 1 ); System.out.println(student.getSid()+ ":" +student.getSname()+ ":" +student.getCard().getNum()); } |
同理
在StudentDAO.java類中增加 查詢“哈哈”學生的信息與身份證信息的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
/** * 查詢“哈哈”學生的信息與身份證信息 * @param name * @return * @throws Exception */ public Student findByName(String name) throws Exception{ SqlSession sqlSession = null ; try { sqlSession = MyBatisUtil.getSqlSession(); return sqlSession.selectOne( "studentNameSpace.findByName" , name); } catch (Exception e) { e.printStackTrace(); throw e; } finally { MyBatisUtil.closeSqlSession(); } } |
并增加測試方法哦
1
2
3
4
5
6
7
|
//測試 查詢“哈哈”學生的信息與身份證信息 @Test public void testFindByName() throws Exception{ StudentCardDAO dao = new StudentCardDAO(); Student student = dao.findByName( "哈哈" ); System.out.println(student.getSid()+ ":" +student.getSname()+ ":" +student.getCard().getNum()); } |
當然如果你現在就測試,你會死的很慘,因為你沒有在StudentMapper.xml文件中配置<select>哦,所以在StudentMapper.xml文件中增加<select>配置信息
1
2
3
4
5
|
<select id= "findByName" parameterType= "string" resultMap= "studentMap" > select s.sid,s.sname,c.cid,c.num from student s,card c where s.scid = c.cid and s.sname = #{sname} </select> |
這樣就可以測試成功了。大功告成。
完整代碼如下:
MySQL數據庫腳本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
-- 刪除數據庫 drop database if exists mybaits; -- 創建數據庫 create database if not exists mybatis default character set utf8; -- 選擇數據庫 use mybatis; -- 刪除數據表 drop table if exists student ; drop table if exists card; -- 創建數據表 create table card( cid int ( 255 ), num varchar( 18 ), constraint pk_cid primary key (cid) ); create table student( sid int ( 255 ), sname varchar( 32 ), scid int ( 255 ), constraint pk_sid primary key (sid), constraint fk_scid foreign key (scid) references card(cid) ); -- 增加測試數據 insert into card (cid,num) values( 1 , '123456789012345678' ); insert into student (sid,sname,scid) values( 1 , '哈哈' , 1 ); |
工具類MyBatis.java類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
package util; import java.io.IOException; import java.io.Reader; import java.sql.Connection; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisUtil { private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>(); public static SqlSessionFactory sqlSessionFactory ; //私有化構造方法 private MyBatisUtil(){} //加載位于src/Mybatis.cfg.xml static { try { Reader reader = Resources.getResourceAsReader( "mybatis.cfg.xml" ); sqlSessionFactory= new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); } } /** * 獲取SQLSession * @return */ public static SqlSession getSqlSession(){ //從當前線程中獲取SqlSession對象 SqlSession sqlSession = threadLocal.get(); if (sqlSession == null ){ if (sqlSessionFactory != null ){ sqlSession = sqlSessionFactory.openSession(); //講sqlSession與當前線程綁定在一起 threadLocal.set(sqlSession); } } return sqlSession; } /** * 關閉SqlSession 并與當前線程分開 */ public static void closeSqlSession(){ //從當前線程中獲取SqlSession對象 SqlSession sqlSession = threadLocal.get(); //如果SqlSession對象非空 if (sqlSession != null ){ //關閉SqlSession對象 sqlSession.close(); //分離當前線程與SqlSession的關系 threadLocal.remove(); } } //測試 public static void main(String[] args) { SqlSession sqlSession = MyBatisUtil.getSqlSession(); Connection conn= sqlSession.getConnection(); System.out.println(conn != null ? "連接成功" : "連接失敗" ); } } |
mybatis.cfg.xml文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
<?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 = "mysql_developer" > <!-- 連接MySQL環境信息 --> <environment id= "mysql_developer" > <!-- MyBatis使用jdbc事務管理器 --> <transactionManager type= "jdbc" /> <!-- MyBatis使用連接池方式來獲取連接對象 --> <dataSource type= "pooled" > <!-- 配置與數據庫交互的 4 個必要屬性 --> <property name= "driver" value= "com.mysql.jdbc.Driver" /> <property name= "url" value= "jdbc:mysql://127.0.0.1:3306/mybatis" /> <property name= "username" value= "root" /> <property name= "password" value= "mysqladmin" /> </dataSource> </environment> <!-- 連接Oracle環境信息 --> <environment id= "oracle_developer" > <!-- MyBatis使用jdbc事務管理器 --> <transactionManager type= "jdbc" /> <!-- MyBatis使用連接池方式來獲取連接對象 --> <dataSource type= "pooled" > <!-- 配置與數據庫交互的 4 個必要屬性 --> <property name= "driver" value= "oracle.jdbc.driver.OracleDriver" /> <property name= "url" value= "jdbc:oracle:thin:@127.0.0.1:1521:orcl" /> <property name= "username" value= "scott" /> <property name= "password" value= "tiger" /> </dataSource> </environment> </environments> <!-- 加載映射文件 --> <mappers> <mapper resource= "one2one/CardMapper.xml" /> <mapper resource= "one2one/StudentMapper.xml" /> </mappers> </configuration> |
Card.java和Student.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
package one2one; import java.io.Serializable; /** * 身份證 * @author Administrator * */ @SuppressWarnings ( "serial" ) public class Card implements Serializable{ private Integer cid; private String num; public Integer getCid() { return cid; } public void setCid(Integer cid) { this .cid = cid; } public String getNum() { return num; } public void setNum(String num) { this .num = num; } } package one2one; import java.io.Serializable; /** * 學生 * @author Administrator * */ @SuppressWarnings ( "serial" ) public class Student implements Serializable{ private Integer sid; private String sname; private Card card; public Integer getSid() { return sid; } public void setSid(Integer sid) { this .sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this .sname = sname; } public Card getCard() { return card; } public void setCard(Card card) { this .card = card; } } |
Card.java的映射文件CardMapper.xml文件
1
2
3
4
5
6
7
8
9
|
<?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= "cardNameSpace" > <resultMap type= "one2one.Card" id= "cardMap" > <id column= "cid" property= "cid" /> <result column= "num" property= "num" /> </resultMap> </mapper> |
Student.java類對應的映射文件StudentMapper.xml文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<?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= "studentNameSpace" > <resultMap type= "one2one.Student" id= "studentMap" > <id column= "sid" property= "sid" /> <result column= "sname" property= "sname" /> <!-- 引入CardMapper.xml文件中的映射信息 property表示Student的關聯屬性 --> <association property= "card" resultMap= "cardNameSpace.cardMap" /> </resultMap> <select id= "findById" parameterType= "integer" resultMap= "studentMap" > select s.sid,s.sname,c.cid,c.num from student s,card c where s.scid = c.cid and s.sid = #{sid} </select> <select id= "findByName" parameterType= "string" resultMap= "studentMap" > select s.sid,s.sname,c.cid,c.num from student s,card c where s.scid = c.cid and s.sname = #{sname} </select> </mapper> |
持久層類StudentCardDAO.java類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
package one2one; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import util.MyBatisUtil; /** * 持久層 * @author Administrator * */ public class StudentCardDAO { /** * 查詢1號學生的信息與身份證信息 * @param id * @return * @throws Exception */ public Student findById(Integer id) throws Exception{ SqlSession sqlSession = null ; try { sqlSession = MyBatisUtil.getSqlSession(); return sqlSession.selectOne( "studentNameSpace.findById" , id); } catch (Exception e) { e.printStackTrace(); throw e; } finally { MyBatisUtil.closeSqlSession(); } } /** * 查詢“哈哈”學生的信息與身份證信息 * @param name * @return * @throws Exception */ public Student findByName(String name) throws Exception{ SqlSession sqlSession = null ; try { sqlSession = MyBatisUtil.getSqlSession(); return sqlSession.selectOne( "studentNameSpace.findByName" , name); } catch (Exception e) { e.printStackTrace(); throw e; } finally { MyBatisUtil.closeSqlSession(); } } //測試 查詢1號學生的信息與身份證信息 @Test public void testFindById() throws Exception{ StudentCardDAO dao = new StudentCardDAO(); Student student = dao.findById( 1 ); System.out.println(student.getSid()+ ":" +student.getSname()+ ":" +student.getCard().getNum()); } //測試 查詢“哈哈”學生的信息與身份證信息 @Test public void testFindByName() throws Exception{ StudentCardDAO dao = new StudentCardDAO(); Student student = dao.findByName( "哈哈" ); System.out.println(student.getSid()+ ":" +student.getSname()+ ":" +student.getCard().getNum()); } } |
以上所述是小編給大家介紹的MyBatis一對一映射初識教程,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://11841428.blog.51cto.com/11831428/1832270