MyBatis教程– CRUD操作和映射关系–第2部分
為了說明這一點,我們正在考慮以下示例域模型:
會有用戶,每個用戶可能都有一個博客,每個博客可以包含零個或多個帖子。
這三個表的數據庫結構如下:
在這里,我將解釋如何獲取和映射*-一對一和一對多結果映射。
package com.sivalabs.mybatisdemo.domain;public class User {private Integer userId;private String emailId;private String password;private String firstName;private String lastName;private Blog blog;//setters and getters } package com.sivalabs.mybatisdemo.domain;import java.util.ArrayList; import java.util.Date; import java.util.List;public class Blog {private Integer blogId;private String blogName;private Date createdOn;private List<Post> posts = new ArrayList<Post>();//setters and getters } package com.sivalabs.mybatisdemo.domain;import java.util.Date;public class Post {private Integer postId;private String title;private String content;private Date createdOn;//setters and getters }在mybatis-config.xml中,為bean配置類型別名。
<typeAliases><typeAlias type='com.sivalabs.mybatisdemo.domain.User' alias='User'/><typeAlias type='com.sivalabs.mybatisdemo.domain.Blog' alias='Blog'/><typeAlias type='com.sivalabs.mybatisdemo.domain.Post' alias='Post'/> </typeAliases>
*-具有一個結果映射:
在UserMapper.xml中,如下配置sql查詢和結果映射:
<mapper namespace='com.sivalabs.mybatisdemo.mappers.UserMapper'><resultMap type='User' id='UserResult'><id property='userId' column='user_id'/><result property='emailId' column='email_id'/><result property='password' column='password'/><result property='firstName' column='first_name'/><result property='lastName' column='last_name'/><association property='blog' resultMap='BlogResult'/></resultMap><resultMap type='Blog' id='BlogResult'><id property='blogId' column='blog_id'/><result property='blogName' column='BLOG_NAME'/><result property='createdOn' column='CREATED_ON'/> </resultMap><select id='getUserById' parameterType='int' resultMap='UserResult'>SELECT U.USER_ID, U.EMAIL_ID, U.PASSWORD, U.FIRST_NAME, U.LAST_NAME, B.BLOG_ID, B.BLOG_NAME, B.CREATED_ONFROM USER U LEFT OUTER JOIN BLOG B ON U.BLOG_ID=B.BLOG_IDWHERE U.USER_ID = #{userId}</select><select id='getAllUsers' resultMap='UserResult'>SELECT U.USER_ID, U.EMAIL_ID, U.PASSWORD, U.FIRST_NAME, U.LAST_NAME, B.BLOG_ID, B.BLOG_NAME, B.CREATED_ONFROM USER U LEFT OUTER JOIN BLOG B ON U.BLOG_ID=B.BLOG_ID</select></mapper>在JUnit Test中,編寫一種方法來測試關聯加載。
public void getUserById() {SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();try{UserMapper userMapper = sqlSession.getMapper(UserMapper.class);User user = userMapper.getUserById(1);System.out.println(user.getBlog());}finally{sqlSession.close();} }
一對多結果映射:
在BlogMapper.xml中,如下配置Blog to Posts關系:
<mapper namespace='com.sivalabs.mybatisdemo.mappers.BlogMapper'><resultMap type='Blog' id='BlogResult'><id property='blogId' column='blog_id'/><result property='blogName' column='BLOG_NAME'/><result property='createdOn' column='CREATED_ON'/><collection property='posts' ofType='Post' resultMap='PostResult' columnPrefix='post_'></collection></resultMap><resultMap type='Post' id='PostResult'><id property='postId' column='post_id'/><result property='title' column='title'/><result property='content' column='content'/><result property='createdOn' column='created_on'/></resultMap><select id='getBlogById' parameterType='int' resultMap='BlogResult'>SELECT b.blog_id, b.blog_name, b.created_on, p.post_id as post_post_id, p.title as post_title, p.content as post_content, p.created_on as post_created_onFROM blog b left outer join post p on b.blog_id=p.blog_idWHERE b.BLOG_ID=#{blogId}</select><select id='getAllBlogs' resultMap='BlogResult'>SELECT b.blog_id, b.blog_name, b.created_on as blog_created_on, p.post_id as post_post_id, p.title as post_title, p.content as post_content, p.created_on as post_created_onFROM blog b left outer join post p on b.blog_id=p.blog_id</select></mapper>在JUnit Test中,編寫一種測試方法來測試博客到帖子的關系映射。
public void getBlogById() {SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();try{BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);Blog blog = blogMapper.getBlogById(1);System.out.println(blog);List<Post> posts = blog.getPosts();for (Post post : posts) {System.out.println(post);}}finally{sqlSession.close();} }
支持 整合
MyBatis-Spring是MyBatis的子項目,并提供Spring集成支持,從而大大簡化了MyBatis的用法。 對于那些熟悉Spring依賴注入方法的人來說,使用MyBatis-Spring非常簡單。
首先讓我們看看不使用Spring的MyBatis的使用過程。
1.通過傳遞包含數據源屬性,映射器XML列表和TypeAliases等的mybatis-config.xml,使用SqlSessionFactoryBuilder創建SqlSessionFactory。
2.從SqlSessionFactory創建SqlSession對象
3.從SqlSession中獲取Mapper實例并執行查詢。
4.使用SqlSession對象提交或回滾事務。
使用MyBatis-Spring,可以在Spring ApplicationContext中配置上述大多數步驟,并且可以將SqlSession或Mapper實例注入到Spring Bean中。 然后,我們可以使用Spring的TransactionManagement功能,而無需在整個代碼中編寫事務提交/回滾代碼。
現在讓我們看看如何配置MyBatis + Spring集成的東西。
步驟#1:在pom.xml中配置MyBatis-Spring依賴項
步驟#2:您不需要在mybatis-config.xml中配置數據庫屬性。
我們可以在Spring Container中配置DataSource并使用它來構建MyBatis SqlSessionFactory。
MyBatis-Spring使用org.mybatis.spring.SqlSessionFactoryBean代替SqlSessionFactoryBuilder來構建SqlSessionFactory。
我們可以將dataSource,Mapper XML文件位置,typeAliases等傳遞給SqlSessionFactoryBean。
<bean id='dataSource' class='org.apache.commons.dbcp.BasicDataSource'><property name='driverClassName' value='${jdbc.driverClassName}'/><property name='url' value='${jdbc.url}'/><property name='username' value='${jdbc.username}'/><property name='password' value='${jdbc.password}'/></bean><bean id='sqlSessionFactory' class='org.mybatis.spring.SqlSessionFactoryBean'><property name='dataSource' ref='dataSource' /><property name='typeAliasesPackage' value='com.sivalabs.mybatisdemo.domain'/><property name='mapperLocations' value='classpath*:com/sivalabs/mybatisdemo/mappers/**/*.xml' /></bean>步驟#3:配置提供ThreadSafe SqlSession對象的SqlSessionTemplate。
<bean id='sqlSession' class='org.mybatis.spring.SqlSessionTemplate'><constructor-arg index='0' ref='sqlSessionFactory' /></bean>
步驟#4:為了能夠直接注入Mapper,我們應該注冊org.mybatis.spring.mapper.MapperScannerConfigurer并配置要在其中找到Mapper接口的包名稱。
步驟5:將 TransactionManager配置為支持基于注釋的事務支持。
步驟#6:更新Service類并在Spring容器中注冊它們。
注意:當我們可以直接注入Mappers時,為什么還要注入SqlSession對象? 因為SqlSession對象包含更細粒度的方法,所以有時會派上用場。
例如:如果我們想獲取更新查詢更新了多少條記錄,可以使用SqlSession,如下所示:
int updatedRowCount = sqlSession.update('com.sivalabs.mybatisdemo.mappers.UserMapper.updateUser', user);到目前為止,我還沒有找到一種無需使用SqlSession對象即可獲取行更新計數的方法。
步驟#7編寫JUnit測試以測試UserService和BlogService。
參考: MyBatis教程:第3部分-映射關系 , ? MyBatis教程:第4部分–來自JCG合作伙伴 Siva Reddy的Spring Integration,來自My Experiments on Technology博客。
翻譯自: https://www.javacodegeeks.com/2012/11/mybatis-tutorial-crud-operations-and-mapping-relationships-part-2.html
總結
以上是生活随笔為你收集整理的MyBatis教程– CRUD操作和映射关系–第2部分的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 打印机详细使用教程电脑如何使用打印机
- 下一篇: 笔记本如何设置定时关机笔记本电脑如何关机