Hello Mybatis 03 数据关联
ResultMap
在實際的開發中,數據庫不總是我們希望看到的樣子。比如我們希望User的主鍵是id但是數據庫偏偏喜歡叫它u_id,這樣一來原先的resultType似乎就失效了,不帶這么玩的,整個人都不好了。
于是mybatis給出了他的方案——resultMap。把我們從復雜的命名問題中解救出來~~~
在上一篇中已經用mybatis generator生成好了一個BlogMapper.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 <mapper namespace="pro.app.inter.BlogMapper" > 4 <resultMap id="BaseResultMap" type="pro.app.model.Blog" > 5 <id column="b_id" property="bId" jdbcType="INTEGER" /> 6 <result column="b_title" property="bTitle" jdbcType="VARCHAR" /> 7 <result column="b_content" property="bContent" jdbcType="VARCHAR" /> 8 <result column="user_id" property="userId" jdbcType="INTEGER" /> 9 </resultMap> 10 11 <sql id="Base_Column_List" > 12 b_id, b_title, b_content, user_id 13 </sql> 14 <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > 15 select 16 <include refid="Base_Column_List" /> 17 from blog 18 where b_id = #{bId,jdbcType=INTEGER} 19 </select> 20 <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > 21 delete from blog 22 where b_id = #{bId,jdbcType=INTEGER} 23 </delete> 24 <insert id="insert" parameterType="pro.app.model.Blog" > 25 <selectKey resultType="java.lang.Integer" keyProperty="bId" order="AFTER" > 26 SELECT LAST_INSERT_ID() 27 </selectKey> 28 insert into blog (b_title, b_content, user_id 29 ) 30 values (#{bTitle,jdbcType=VARCHAR}, #{bContent,jdbcType=VARCHAR}, #{userId,jdbcType=INTEGER} 31 ) 32 </insert> 33 <insert id="insertSelective" parameterType="pro.app.model.Blog" > 34 <selectKey resultType="java.lang.Integer" keyProperty="bId" order="AFTER" > 35 SELECT LAST_INSERT_ID() 36 </selectKey> 37 insert into blog 38 <trim prefix="(" suffix=")" suffixOverrides="," > 39 <if test="bTitle != null" > 40 b_title, 41 </if> 42 <if test="bContent != null" > 43 b_content, 44 </if> 45 <if test="userId != null" > 46 user_id, 47 </if> 48 </trim> 49 <trim prefix="values (" suffix=")" suffixOverrides="," > 50 <if test="bTitle != null" > 51 #{bTitle,jdbcType=VARCHAR}, 52 </if> 53 <if test="bContent != null" > 54 #{bContent,jdbcType=VARCHAR}, 55 </if> 56 <if test="userId != null" > 57 #{userId,jdbcType=INTEGER}, 58 </if> 59 </trim> 60 </insert> 61 <update id="updateByPrimaryKeySelective" parameterType="pro.app.model.Blog" > 62 update blog 63 <set > 64 <if test="bTitle != null" > 65 b_title = #{bTitle,jdbcType=VARCHAR}, 66 </if> 67 <if test="bContent != null" > 68 b_content = #{bContent,jdbcType=VARCHAR}, 69 </if> 70 <if test="userId != null" > 71 user_id = #{userId,jdbcType=INTEGER}, 72 </if> 73 </set> 74 where b_id = #{bId,jdbcType=INTEGER} 75 </update> 76 <update id="updateByPrimaryKey" parameterType="pro.app.model.Blog" > 77 update blog 78 set b_title = #{bTitle,jdbcType=VARCHAR}, 79 b_content = #{bContent,jdbcType=VARCHAR}, 80 user_id = #{userId,jdbcType=INTEGER} 81 where b_id = #{bId,jdbcType=INTEGER} 82 </update> 83 </mapper>在文件的開頭位置,就能夠發現一個名為BaseResultMap的resultMap標簽。在這個標簽當中我們可以發現幾個子標簽。這幾個子標簽對通過column和property屬性將數據庫字段和model對應類型關聯起來。而<id/>標簽代表這個model類的屬性對應的數據庫字段為這張表的主鍵。定義完成這個BaseResultMap之后,我們就可以在后面的標簽對中使用它作為返回的結果使用。?這里可以注意到select的屬性resultMap="BaseResultMap" 。返回的數據通過resultMap被封裝成了相應的對象,如果返回的數據是多條,mybatis也會自動將結果集轉換為List集合。
這里還可以關注下resultMap下的sql標簽對,在這個標簽對中可以寫入數據庫的字段名稱。在CRUD的xml文件中使用<include/>標簽引用這它,在數據庫需要修改的時候,我們就不用去修改這個配置文件下每一個sql語句。
數據關聯
有人會說。這樣resultMap和resultType有什么區別!還要多寫這么一堆配置,這不是吃飽了撐著么!!!真的是這個樣子?
我們之前設計了兩張表,一個用戶表和一個博客列表,一個用戶可以有多篇博客吧,一篇博客只有一個作者。現在就讓resultMap幫助我們把數據關聯起來~
先給表Blog添加幾條數據
1 INSERT INTO `blog`.`blog` (`b_id`, `b_title`, `b_content`, `user_id`) VALUES ('1', '001', 'mybatis001', '1'); 2 INSERT INTO `blog`.`blog` (`b_id`, `b_title`, `b_content`, `user_id`) VALUES ('2', '002', 'mybatis002', '1'); 3 INSERT INTO `blog`.`blog` (`b_id`, `b_title`, `b_content`, `user_id`) VALUES ('3', '003', 'mybatis003', '1'); 4 INSERT INTO `blog`.`blog` (`b_id`, `b_title`, `b_content`, `user_id`) VALUES ('4', '004', 'mybatis004', '1'); 5 INSERT INTO `blog`.`blog` (`b_id`, `b_title`, `b_content`, `user_id`) VALUES ('5', '005', 'mybatis005', '1');?
在此之前我們需要再定義一個BlogVo類,并繼承Blog類,然后添加一個User類型屬性user。
1 package pro.app.model; 2 3 public class BlogVo extends Blog{ 4 private User user; 5 public User getUser() { 6 return user; 7 } 8 public void setUser(User user) { 9 this.user = user; 10 } 11 }接著在BlogMapper.xml中添加一個resultMap。
1 <resultMap id="BaseResultMapWithUser" type="pro.app.model.BlogVo" > 2 <id column="b_id" property="bId" jdbcType="INTEGER" /> 3 <result column="b_title" property="bTitle" jdbcType="VARCHAR" /> 4 <result column="b_content" property="bContent" jdbcType="VARCHAR" /> 5 <association property="user" javaType="pro.app.model.User"> 6 <id column="user_id" property="id" jdbcType="INTEGER" /> 7 <result column="name" property="name" jdbcType="VARCHAR" /> 8 <result column="age" property="age" jdbcType="INTEGER" /> 9 </association> 10 </resultMap>在resultMap中通過子標簽association,我們將外鍵與對應的model類型對應起來。用association中的property屬性對應java屬性的用戶。association下的子標簽id對應blog表中的外鍵,這也是數據關聯的關鍵!接著再給這個文件添加一個select標簽。
1 <select id="selectByPrimaryKeyWithUser" resultMap="BaseResultMapWithUser" parameterType="java.lang.Integer" > 2 select * 3 from blog b 4 join user u 5 on b.user_id=u.id 6 where b.b_id= #{id,jdbcType=INTEGER} 7 </select>ok,讓我們在BlogMapper.java里添加一個selectByPrimaryKeyWithUser()方法。
1 package pro.app.inter; 2 3 import org.apache.ibatis.annotations.Param; 4 5 import pro.app.model.Blog; 6 import pro.app.model.BlogVo; 7 8 public interface BlogMapper { 9 int deleteByPrimaryKey(Integer bId); 10 11 int insert(Blog record); 12 13 int insertSelective(Blog record); 14 15 Blog selectByPrimaryKey(Integer bId); 16 17 int updateByPrimaryKeySelective(Blog record); 18 19 int updateByPrimaryKey(Blog record); 20 21 BlogVo selectByPrimaryKeyWithUser(@Param("id")Integer id); 22 23 }建立一個測試類來看看效果
1 package pro.test; 2 3 import java.io.Reader; 4 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 10 import pro.app.inter.BlogMapper; 11 import pro.app.model.Blog; 12 import pro.app.model.BlogVo; 13 14 public class BlogVoTest { 15 private static SqlSessionFactory sqlSessionFactory; 16 private static Reader reader; 17 static{ 18 try{ 19 reader= Resources.getResourceAsReader("Configuration.xml"); 20 sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); 21 }catch(Exception e){ 22 e.printStackTrace(); 23 } 24 } 25 public static SqlSessionFactory getSession(){ 26 return sqlSessionFactory; 27 } 28 public static void main(String[] args) { 29 SqlSession session = sqlSessionFactory.openSession(); 30 try { 31 BlogMapper blogs = session.getMapper(BlogMapper.class); 32 BlogVo bv=blogs.selectByPrimaryKeyWithUser(1); 33 System.out.println(bv.getUser().getName()); 34 } finally { 35 session.close(); 36 } 37 } 38 }控制臺輸出了:
Mybatisok!mybatis幫我們把博客的作者選出來了。現在我們來通過作者選出他所有的文章。
同樣我們在UserMapper.xml里添加一個resultMap
1 <resultMap id="BaseResultMapWithBlogs" type="pro.app.model.UserVo" > 2 <id column="id" property="id" jdbcType="INTEGER" /> 3 <result column="name" property="name" jdbcType="VARCHAR" /> 4 <result column="age" property="age" jdbcType="INTEGER" /> 5 <collection property="blogs" ofType="pro.app.model.Blog" column="b_id"> 6 <id column="b_id" property="bId" jdbcType="INTEGER" /> 7 <result column="b_title" property="bTitle" jdbcType="VARCHAR" /> 8 <result column="b_content" property="bContent" jdbcType="VARCHAR" /> 9 </collection> 10 </resultMap>這里的resultMap還多個了一個collection標簽,顧名思義這表示一個集合,collection的column表示結果集對應的table的主鍵。現在再添加一個select標簽。
1 <select id="selectOneWithBlogs" resultMap="BaseResultMapWithBlogs" parameterType="java.lang.Integer"> 2 select * 3 from blog b 4 join user u 5 on b.user_id=u.id 6 where u.id = #{id,jdbcType=INTEGER} 7 </select>在UserDAO.java里添加一個selectOneWithBlogs()方法。
1 package pro.app.inter; 2 import org.apache.ibatis.annotations.Param; 3 4 import pro.app.model.User; 5 import pro.app.model.UserVo; 6 7 public interface UserDAO { 8 public User selectOne(@Param("id")Integer id); 9 10 public void insertOne(User user); 11 12 public void deleteOne(@Param("id")Integer id); 13 14 public void updateOne(User user); 15 16 UserVo selectOneWithBlogs(@Param("id")Integer id); 17 }新建一個測試類,觀察結果。
1 package pro.test; 2 3 import java.io.Reader; 4 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 10 import pro.app.inter.UserDAO; 11 import pro.app.model.Blog; 12 import pro.app.model.UserVo; 13 14 public class UserVoTest { 15 private static SqlSessionFactory sqlSessionFactory; 16 private static Reader reader; 17 static{ 18 try{ 19 reader= Resources.getResourceAsReader("Configuration.xml"); 20 sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); 21 }catch(Exception e){ 22 e.printStackTrace(); 23 } 24 } 25 public static SqlSessionFactory getSession(){ 26 return sqlSessionFactory; 27 } 28 public static void main(String[] args) { 29 SqlSession session = sqlSessionFactory.openSession(); 30 try { 31 UserDAO users = session.getMapper(UserDAO.class); 32 UserVo user=users.selectOneWithBlogs(1); 33 for(Blog b:user.getBlogs()){ 34 System.out.println(b.getbTitle()); 35 System.out.println(b.getbContent()); 36 } 37 } finally { 38 session.close(); 39 } 40 } 41 }控制臺輸出
001 mybatis001 002 mybatis002 003 mybatis003 004 mybatis004 005 mybatis005bingo!!!用戶對應的博客都被選出來了~
總結
?通過resultMap?實現數據的關聯。
?
轉載于:https://www.cnblogs.com/whthomas/p/3762445.html
總結
以上是生活随笔為你收集整理的Hello Mybatis 03 数据关联的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 举例什么时候会用到 call(), ap
- 下一篇: Gmail POP3设置