设为首页 收藏本站
查看: 943|回复: 0

[经验分享] Creating Mybatis Mapper xmls and usage of MapperFactoryBean, MapperScannerConfig

[复制链接]

尚未签到

发表于 2016-11-26 09:55:27 | 显示全部楼层 |阅读模式
We are going to use Spring 3x and Mybatis 3x in conjunction here.

Pre-requisite :
Download the Mybatis-Spring bundle : mybatis-spring-1.1.1-bundle and use the libs assorted.
Spring version : 3.1.1
Mybatis version : 3.1.0
Please note the version 1.1.1 for mybatis-spring bundle. There were some issues with 1.1.0 bundle for loading of properties using Spring’s PropertyPlaceHolderConfigurer, but more on that later.

Mybatis

Mybatis is a persistence framework. Mybatis is not an ORM framework and doesn’t map Java objects to database rows. However, it maps methods to SQL statements.

Mybatis vs. Hibernate

I have used both Mybatis and Hibernate in my applications, and both have their pros and cons. However, of late, I have moved more and more towards Mybatis.

IMO, if the object graph is complex, then it is better to use Mybatis and not Hibernate. Hibernate has its own version of lazy loading, but the more associations an object has or the heavier an object is, the more it becomes a performance hit.

In one of our applications which used Hibernate, we finally had to rewrite several queries in order to perform thin loading, or loading only those attributes which are required.

For further details regarding Mybatis, please visit http://en.wikipedia.org/wiki/MyBatis
For Spring-Mybatis, :here

Spring vs Struts for MVC

As regards Spring vs Struts for MVC, again to each his own. Struts 2x is pretty good when it comes to writing less code to do more and I had recently developed an application using Struts 2x. However, most of the transaction management there was programmatic, which needless to say is ugly and error prone. I had to spend lots of time testing out my code.

Now, this last statement is not strictly a Spring MVC advantage or a Struts flaw, because its just an MVC framework and nothing more. However, when we talk about Spring, we get to use the IOC container as well along with its declarative transaction management. Plus, the community support is really good, which invariably helps if you hit a roadblock. One more thing, which I really like about Spring is its view-agnostic (Yes I picked up this word somewhere on the net) It means that it really allows you to custom build any view implementation you like and not just stick to JSPs.(Though Struts 2x has some similar implementations using FreeMarker)

We would be using Eclipse as an IDE to do our development and this is an image of all jars which will be required eventually. Some of them like the commons*.jar and mybatis-ehcache*.jar will have to be downloaded separately.

spring mybatis libs/ jars

Since, by now we have a working Spring MVC application here, we will piggyback on it and add the required configurations. We will revisit our application’s web.xml. (This is just the relevant part, for the entire xml, please refer here.)

01<context-param>
02 <param-name>contextConfigLocation</param-name>
03 <param-value>
04 /WEB-INF/spring/app-config.xml
05 /WEB-INF/spring/database-config.xml
06 /WEB-INF/spring/mapper-config.xml
07 </param-value>
08 </context-param>
09<listener>
10 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
11 </listener>

Right, so from here we can see that the ContextLoaderListener will check on

    database-config.xml which will contain the database configuration.
    mapper-config.xml which will point to the individual Mybatis interfaces.

database-config.xml

01<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
02 destroy-method="close">
03 <property name="driverClassName" value="${driver}" />
04 <property name="url" value="${url}" />
05 <property name="username" value="${username}" />
06 <property name="password" value="${password}" />
07 <property name="defaultAutoCommit" value="false" />
08 </bean>
09<bean id="txManager"
10 class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
11 <property name="dataSource" ref="dataSource" />
12 </bean>
13<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
14 <property name="dataSource" ref="dataSource" />
15 <property name="mapperLocations" value="classpath:com/mybatis/mappers/*.xml" />
16 <property name="configLocation" value="WEB-INF/mybatis-config/mybatis-config.xml" />
17 </bean>

We see 3 beans here :dataSource, txManager and sqlSessionFactory . For dataSource, we will be using dbcp’s BasicDataSource. We would come to the txmanager later.

Now, if you are observant, you would see that the credentials of the datasource are encoded. This is an industry standard, where sensitive information is stored on a keystore or an external property file. Then, the access for this file is controlled by the system administrators on the server. We would see later how, Spring help to retrieve these property values.

For now, let’s concentrate only on the sqlSessionFactory and its attributes.

It has 3 attributes :

    refers to the dataSource,
    mapperLocations which is where we would store our mybatis xml files. Ant style configuration for mapperLocation: if we put it as value=“classpath*:com/mybatis/mappers/*.xml” /> then it will also look into the subpackages recursively
    configLocation where we would store a custom mybatis configuration file to override some important settings.

mapper-config.xml

1<bean id="baseMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
2 <property name="mapperInterface" value="com.mybatis.dao.BaseMapperInterface" />
3 <property name="sqlSessionFactory" ref="sqlSessionFactory" />
4 </bean>
5<bean id="employeeMapper" parent="baseMapper">
6 <property name="mapperInterface" value="com.mybatis.dao.EmployeeMapperInterface" />
7 </bean>

2 important concepts explained here:

    We have a BaseMapperInterface which contains a reference to the sqlSessionFactory and this class is simply extended by the rest of the mapper interfaces so that individual interfaces do not have to link in the sqlSessionFactory.
    Presence of a MapperFactoryBean which we will revisit later.

mybatis-config.xml

This is a bare-bones configuration file which we will augment as we learn more about Mybatis.

01<?xml version="1.0" encoding="UTF-8" ?>
02 <!DOCTYPE configuration
03 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
04 "http://mybatis.org/dtd/mybatis-3-config.dtd">
05 <configuration>
06 <settings>
07 <setting name="cacheEnabled" value="true" />
08 <setting name="lazyLoadingEnabled" value="true" />
09 <setting name="multipleResultSetsEnabled" value="true" />
10 <setting name="useColumnLabel" value="true" />
11 <setting name="useGeneratedKeys" value="false" />
12 <setting name="defaultExecutorType" value="SIMPLE" />
13 <setting name="defaultStatementTimeout" value="100" />
14 <setting name="safeRowBoundsEnabled" value="false" />
15 <setting name="mapUnderscoreToCamelCase" value="false" />
16 <setting name="localCacheScope" value="SESSION" />
17 <setting name="jdbcTypeForNull" value="OTHER" />
18 <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString" />
19 </settings>
20</configuration>

So, we have done our configurations. One more small thing of using Spring to decipher the properties for us. We can put this in the app-config.xml which is also listened to by the ContextLoaderListener(check the web.xml earlier on this page)

1<bean class=<em>"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"</em>>
2<property name="location">
3<value>classpath:config.properties</value>
4</property>
5</bean>

Interesting Note: we can use our custom PropertyPlaceHolderConfigurer by extending the above mentioned class.We only need to override the following method :

1public String convertPropertyValue(final String originalValue) {
2//whatever decoding/decrypting logic u want to put.
3//U can first encrypt and then encode the property in the property file.
4}

Right, so our configurational changes have been completed.

Now a typical approach is having the service layer get access to the Mapper interfaces.

So, the interaction would be like Controller(Web layer) accesses the Service Façade which accesses the Mybatis DAO layer/interfaces.

Our sample application would have a login screen for a manager. When the manager successfully logs in, he or she would be able to view his/her employees. On clicking any of the employee’s hyperlink, the manager would get access to the employee’s details which can then be modified.

In step 2, we will be creating our controllers.

This tutorial has been linked in Mybatis wiki : http://code.google.com/p/mybatis

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-305758-1-1.html 上篇帖子: mybatis Invalid bound statement(not found) 下篇帖子: Mybatis List列表In查询实现
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表