`
amigo
  • 浏览: 50752 次
  • 来自: ...
社区版块
存档分类
最新评论

Creating Mybatis Mapper xmls and usage of MapperFactoryBean, MapperScannerConfig

 
阅读更多
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 :

1 public 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
分享到:
评论

相关推荐

    Spring+mvc+mybatis Mapper xml自动加载

    "Spring+mvc+mybatis Mapper xml自动加载"这个主题聚焦于如何在开发过程中优化配置,使得改动Mapper XML文件后,无需重启Tomcat服务器,就可以立即生效,从而提高开发效率。 Spring MVC是Spring框架的一部分,它...

    mybatis Mapper.xml中传参多选 字符串形式逗号分隔 AND中拼接OR.rar

    标题和描述所提及的问题是关于如何在Mapper.xml文件中处理字符串形式的参数,这些参数由逗号分隔,并在`AND`语句中拼接`OR`子句来实现动态查询。这种场景在处理用户多选过滤条件时非常常见,比如在一个搜索框中,...

    IntelliJ IDEA修改了mybatis mapper xml后不用重启tomcat,自动热发布 热更新 热部署.zip

    在开发Java Web应用程序时,尤其是使用Mybatis作为持久层框架的时候,经常遇到的一个问题是:当我们在IntelliJ IDEA中修改了Mapper XML文件后,需要手动重启Tomcat服务器才能看到改动的效果,这无疑降低了开发效率。...

    springboot mybatis mapper.xml 配置

    在Spring Boot集成MyBatis的过程中,`mapper.xml`配置文件起着至关重要的作用。它用于定义SQL语句,实现数据库的CRUD操作。本示例将深入探讨如何配置`mapper.xml`,并提供新增、修改、删除、查询及分页查询的实践...

    mybatis修改了mapper xml不用重启tomcat,热发布热更新.zip_mybatis的xml模糊查询

    mybatis修改了mapper xml不用重启tomcat,热发布热更新.zip

    Mybatis Mapper的使用

    Mybatis Mapper通过动态代理机制,使得我们可以直接在XML映射文件中定义SQL,然后在接口中声明对应的方法,系统会在运行时自动生成实现类,这样就消除了对实现类的直接依赖。 下面我们将详细探讨Mybatis Mapper的几...

    mybatis mapper 和xml文件生成

    本篇文章将深入探讨MyBatis的Mapper和XML文件生成,以及如何使用`mybatis-generator-core-1.3.2`工具进行自动化生成。 首先,让我们理解Mapper接口。Mapper接口是MyBatis中的一个关键概念,它允许开发者定义数据库...

    mybatis_xml关联插件

    在Eclipse中,打开项目的“属性”(Properties)设置,找到"Mybatis"或"MyBatis Configuration"选项,这里可以添加Mybatis的配置文件(mybatis-config.xml),并指定Mapper XML文件所在的目录。这一步确保Eclipse知道...

    mybatis mapper自动生成

    4. **整合**:最后,将生成的文件导入到Maven项目中,并在项目中配置MyBatis的SqlSessionFactory,确保能正确加载Mapper XML文件。 关于`mysql-connector-java-5.1.38.jar`,这是一个MySQL的JDBC驱动包,它是连接...

    springboot整合mybatis基于mapperXML模式.zip

    在本文中,我们将深入探讨如何将SpringBoot与MyBatis框架整合,并且使用MapperXML模式进行数据库操作。SpringBoot以其简化配置和快速启动的特点,深受开发者喜爱,而MyBatis则是一个优秀的持久层框架,提供了灵活的...

    Mybatis Mapper生成器示例

    根据项目模块来生成对应的Mapper,这里采用Maven构建项目。Mybatis Generator插件怎么使用请参考:https://my.oschina.net/boonya/blog/719502。更多代码生成器介绍请参考:...

    spring boot + mybatis +mapper.xml 项目

    Spring Boot + MyBatis + Mapper.xml 项目是一个基础但实用的Java Web开发框架组合,它大大简化了传统Spring项目的配置和启动过程。本项目利用Spring Boot的自动配置特性,配合MyBatis作为持久层框架,以及Mapper....

    mybatis_xml插件

    MyBatis_XML插件的主要功能是为IDE(如IntelliJ IDEA或Eclipse)提供增强的功能,使得开发者可以直接在IDE中关联和查看Mapper.xml文件。这大大简化了开发过程中查找对应XML映射文件的步骤,提高了开发效率。当我们在...

    idea好用的插件:Free Mybatis自动对应mapper层的xml文件

    idea好用的插件:Free Mybatis自动对应mapper层的xml文件

    mybatis基本文件xml、mapper等自动生成工具

    mybatis基本文件xml、mapper等自动生成工具 可自己根据自己的项目路径自行配置文件夹路径,本DEMO是使用的mysql数据库,可自行更换其他数据源 本DEMO会自动生成dao、model、mapper、xml文件,自带基本方法,可自动...

    MyBatis Mapper映射文件

    MyBatis Mapper映射文件

    用java程序生成mybatis的mapper.xml和mapper.java文件

    本文将详细讲解如何使用Java程序生成Mybatis的mapper.xml和mapper.java文件,以便于简化开发过程,提高代码的可维护性和效率。 首先,理解mapper.xml和mapper.java的作用是关键。mapper.xml文件是Mybatis中的SQL...

    MyBatis的helloworld(不使用Mapper接口实现MyBatis查询数据库).zip

    总结来说,本示例展示了如何在不使用Mapper接口的情况下,通过MyBatis的XML配置文件和SqlSession执行SQL查询。这种方式虽然略显繁琐,但对于学习MyBatis的基本操作非常有帮助。在实际开发中,结合Mapper接口和注解...

    mybatis根据数据库表自动生成mapper和实体及xml项目示例

    本示例"mybatis根据数据库表自动生成mapper和实体及xml项目"就是这样一个实用工具,它能够帮助开发者快速构建MyBatis项目。 首先,MyBatis是一个优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。MyBatis...

    java后端+mybatis-plus自动生成+xmlmapper模板+新增修改

    用mybatis-plus的自动生成器,我们一般只用到entity和mapperXML,其他mapper接口和service类都要自己写。 可以下载之后,根据自己表生成mapperXML,然后用全局替换来修改一些细节。

Global site tag (gtag.js) - Google Analytics