mybatis crud_MyBatis教程– CRUD操作和映射关系–第2部分
mybatis crud
為了說(shuō)明這一點(diǎn),我們正在考慮以下示例域模型:
會(huì)有用戶,每個(gè)用戶可能都有一個(gè)博客,每個(gè)博客可以包含零個(gè)或多個(gè)帖子。
這三個(gè)表的數(shù)據(jù)庫(kù)結(jié)構(gòu)如下:
在這里,我將解釋如何獲取和映射*-一對(duì)一和一對(duì)多結(jié)果映射。
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>
*-具有一個(gè)結(jié)果映射:
在UserMapper.xml中,如下配置sql查詢和結(jié)果映射:
<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中,編寫一種方法來(lái)測(cè)試關(guān)聯(lián)加載。
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();} }
一對(duì)多結(jié)果映射:
在BlogMapper.xml中,如下配置Blog to Posts關(guān)系:
<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中,編寫一種測(cè)試方法來(lái)測(cè)試博客到帖子的關(guān)系映射。
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的子項(xiàng)目,并提供Spring集成支持,從而大大簡(jiǎn)化了MyBatis的用法。 對(duì)于那些熟悉Spring的依賴注入方法的人來(lái)說(shuō),使用MyBatis-Spring非常簡(jiǎn)單。
首先讓我們看看不使用Spring的MyBatis的使用過(guò)程。
1.通過(guò)傳遞包含數(shù)據(jù)源屬性,映射器XML列表和TypeAliases等的mybatis-config.xml,使用SqlSessionFactoryBuilder創(chuàng)建SqlSessionFactory。
2.從SqlSessionFactory創(chuàng)建SqlSession對(duì)象
3.從SqlSession中獲取Mapper實(shí)例并執(zhí)行查詢。
4.使用SqlSession對(duì)象提交或回滾事務(wù)。
使用MyBatis-Spring,可以在Spring ApplicationContext中配置上述大多數(shù)步驟,并且可以將SqlSession或Mapper實(shí)例注入到Spring Beans中。 然后,我們可以使用Spring的TransactionManagement功能,而無(wú)需在整個(gè)代碼中編寫事務(wù)提交/回滾代碼。
現(xiàn)在讓我們看看如何配置MyBatis + Spring集成的東西。
步驟#1:在pom.xml中配置MyBatis-Spring依賴項(xiàng)
步驟#2:您不需要在mybatis-config.xml中配置數(shù)據(jù)庫(kù)屬性。
我們可以在Spring Container中配置DataSource并使用它來(lái)構(gòu)建MyBatis SqlSessionFactory。
MyBatis-Spring使用org.mybatis.spring.SqlSessionFactoryBean代替SqlSessionFactoryBuilder來(lái)構(gòu)建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對(duì)象的SqlSessionTemplate。
<bean id='sqlSession' class='org.mybatis.spring.SqlSessionTemplate'><constructor-arg index='0' ref='sqlSessionFactory' /></bean>
步驟#4:為了能夠直接注入Mapper,我們應(yīng)該注冊(cè)org.mybatis.spring.mapper.MapperScannerConfigurer并配置要在其中找到Mapper接口的包名稱。
步驟5:將 TransactionManager配置為支持基于注釋的事務(wù)支持。
步驟#6:更新Service類并在Spring容器中注冊(cè)它們。
注意:當(dāng)我們可以直接注入Mappers時(shí),為什么還要注入SqlSession對(duì)象? 因?yàn)镾qlSession對(duì)象包含更細(xì)粒度的方法,所以有時(shí)會(huì)派上用場(chǎng)。
例如:如果我們想獲取更新查詢更新了多少條記錄,可以使用SqlSession,如下所示:
int updatedRowCount = sqlSession.update('com.sivalabs.mybatisdemo.mappers.UserMapper.updateUser', user);到目前為止,我還沒(méi)有找到一種無(wú)需使用SqlSession對(duì)象就可以獲取行更新計(jì)數(shù)的方法。
步驟#7編寫JUnit測(cè)試以測(cè)試UserService和BlogService。
參考: MyBatis教程:第3部分-映射關(guān)系 , ? MyBatis教程:第4部分– JCG合作伙伴 Siva Reddy的My Integrations on Technology上的Spring Integration 。
翻譯自: https://www.javacodegeeks.com/2012/11/mybatis-tutorial-crud-operations-and-mapping-relationships-part-2.html
mybatis crud
總結(jié)
以上是生活随笔為你收集整理的mybatis crud_MyBatis教程– CRUD操作和映射关系–第2部分的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 印刷备案流程图(印刷备案)
- 下一篇: 通过分区在Kafka中实现订单保证人