What is mybatis
MyBatis is an excellent persistence layer framework that supports plain SQL queries, stored procedures and advanced mapping. MyBatis eliminates the manual setting of almost all JDBC code and parameters and the retrieval of result sets. MyBatis uses simple XML or annotations for configuration and original mapping, mapping interfaces and Java's POJOs (Plan Old Java Objects, ordinary Java objects) into records in the database.
The basic idea of orm tools
Whether it is used hibernate or mybatis, you can have one thing in common with Dharma:
1. Get sessionfactory from the configuration file (usually an XML configuration file).
2. Generate session from sessionfactory
3. Complete data addition, deletion, modification and query, transaction submission, etc. in the session.
4. Close session after use.
5. There is a configuration file for mapping between the java object and the database, usually an xml file.
One of mybatis practical tutorials (mybatis in action): Development environment construction
Mybatis development environment is built, select: eclipse j2ee version, mysql 5.1, jdk 1.7, mybatis3.2.0.jar package. These software tools can be downloaded on their respective official websites.
First create a dynamic web project named MyBaits
1. At this stage, you can directly build java projects, but generally develop web projects. This series of tutorials is also web at the end, so you can build web projects from the beginning.
2. Copy mybatis-3.2.0-SNAPSHOT.jar, mysql-connector-java-5.1.22-bin.jar to the lib directory of the web project.
3. Create mysql test database and user table. Note that the utf-8 encoding is used here.
Create a user table and insert a test data
Program code
Create TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT,`userName` varchar(50) DEFAULT NULL,`userAge` int(11) DEFAULT NULL,`userAddress` varchar(200) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;Insert INTO `user` VALUES ('1', 'summer', '100', 'shanghai,pudong');So far, the preliminary preparations are completed. Let’s start to configure the mybatis project.
1. Create two source code directories in MyBatis, namely src_user, test_src, and create them in the following way, right-click on JavaResource.
2. Set mybatis configuration file: Configuration.xml, create this file in the src_user directory, the content is as follows:
Program code
< ?xml version="1.0" encoding="UTF-8" ?>< !DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">< configuration><typeAliases> <typeAlias alias="User" type="com.yihaomen.mybatis.model.User"/> </typeAliases> <environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis" /><property name="username" value="root"/><property name="password" value="password"/><property name="password"/></dataSource></environment></environments><mappers><mapper resource="com/yihaomen/mybatis/model/User.xml"/></mappers></configuration>
3. Create a java class and mapping file corresponding to the database.
Create package:com.yihaomen.mybatis.model under src_user, and create User class under this package:
Program code
package com.yihaomen.mybatis.model;public class User {private int id;private String userName;private String userAge;private String userAddress;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getUserAge() {return userAge;}public void setUserAge(String userAge) {this.userAge = userAge;}public String getUserAddress() {return userAddress;}public void setUserAddress(String userAddress) {this.userAddress = userAddress;}}At the same time, create the User mapping file User.xml:
Program code
< ?xml version="1.0" encoding="UTF-8" ?>< !DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">< mapper namespace="com.yihaomen.mybatis.models.UserMapper"><select id="selectUserByID" parameterType="int" resultType="User">select * from `user` where id = #{id}</select>< /mapper>The following explanations are given to these configuration files:
1.Configuration.xml is used by mybatis to establish a sessionFactory. It mainly contains database connection-related things, as well as the alias corresponding to the java class. For example, the alias alias="User" type="com.yihaomen.mybatis.model.User"/> This alias is very important. In the mapping of specific classes, such as resultType in User.xml, it corresponds to here. To be consistent, of course, there is another separate definition of resultType here, which will be discussed later.
2. The <mapper resource="com/yihaomen/mybatis/model/User.xml"/> in Configuration.xml is the xml configuration file containing the class to be mapped.
3. In the User.xml file, it mainly defines various SQL statements, as well as the parameters of these statements, as well as the types to be returned, etc.
Start the test
Create the com.yihaomen.test package in the test_src source code directory and create the test class Test:
Program code
package com.yihaomen.test;import java.io.Reader;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import com.yihaomen.mybatis.model.User;public class Test {private static SqlSessionFactory sqlSessionFactory;private static Reader reader; static{try{reader = Resources.getResourceAsReader("Configuration.xml");sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);}catch(Exception e){e.printStackTrace();}}public static SqlSessionFactory getSession(){return sqlSessionFactory;}public static void main(String[] args) {SqlSession session = sqlSessionFactory.openSession();try {User user = (User) session.selectOne("com.yihaomen.mybatis.models.UserMapper.selectUserByID", 1);System.out.println(user.getUserAddress());System.out.println(user.getUserName());} finally {session.close();}}} Now run this program and you will get the query result. Congratulations, the environment is successfully built and configured. Next, the second chapter will talk about the interface-based operation methods, adding, deleting, modifying and checking.
The entire project directory structure is as follows:
Mybatis practice tutorial (mybatis in action) 2: Programming in an interface
In the previous chapter, the environment of eclipse, mybatis, mysql has been built and a simple query has been implemented. Please note that this method is to use the SqlSession instance to directly execute the mapped SQL statement:
session.selectOne("com.yihaomen.mybatis.models.UserMapper.selectUserByID", 1)In fact, there are simpler methods, and better methods, using interfaces that reasonably describe parameters and SQL statement return values (such as IUserOperation.class), so that you can now get to this simpler and safer code without easy string literals and conversion errors. The following is the detailed process:
Create the com.yihaomen.mybatis.inter package in the src_user source code directory, and create the interface class IUserOperation, the content is as follows:
Program code
package com.yihaomen.mybatis.inter;import com.yihaomen.mybatis.model.User;public interface IUserOperation { public User selectUserByID(int id);}Please note that there is a method name selectUserByID here that must correspond to the id of the select configured in User.xml (<select id="selectUserByID")
Rewrite the test code
public static void main(String[] args) {SqlSession session = sqlSessionFactory.openSession();try {IUserOperation userOperation=session.getMapper(IUserOperation.class);User user = userOperation.selectUserByID(1);System.out.println(user.getUserAddress());System.out.println(user.getUserName());} finally {session.close();}}The entire engineering structure diagram is now as follows:
Run this test program and you will see the results.
Mybatis practical tutorial (mybatis in action) 3: Implement data addition, deletion, modification and search
I have already talked about programming using interfaces. One thing to pay attention to in this way is. In the User.xml configuration file, mapper namespace="com.yihaomen.mybatis.inter.IUserOperation" namespace is very important, there must be no errors, it must be consistent with the package and interface we define. If there is inconsistency, there will be errors. This chapter mainly completes the following things based on interface programming in the previous lecture:
1. Use mybatis to query data, including list
2. Use mybatis to increase data
3. Update data with mybatis.
4. Use mybatis to delete data.
Querying data, as mentioned above, we mainly look at querying the list
Query the list, that is, return list, in our example, List<User>. In this way, you need to configure the returned type resultMap in User.xml. Note that it is not resultType, and the corresponding resultMap should be configured by ourselves.
Program code
< !-- returnMap defined to return list type --><resultMap type="User" id="resultListUser"><id column="id" property="id" /><result column="userName" property="userName" /><result column="userAge" property="userAge" /><result column="userAddress" property="userAddress" /></resultMap>
The statement query list is in User.xml
Program code
< !-- Return the select statement of list, note that the value of resultMap points to the previously defined --><select id="selectUsers" parameterType="string" resultMap="resultListUser">select * from user where userName like #{userName}</select>Add method to the IUserOperation interface: public List<User> selectUsers(String userName);
Now do the test in the Test class
Program code
public void getUserList(String userName){SqlSession session = sqlSessionFactory.openSession();try {IUserOperation userOperation=session.getMapper(IUserOperation.class); List<User> users = userOperation.selectUsers(userName); for(User user:users){System.out.println(user.getId()+":"+user.getUserName()+":"+user.getUserAddress());}} finally {session.close();}}Now in the main method you can test:
Program code
public static void main(String[] args) {Test testUser=new Test();testUser.getUserList("%");}You can see that the result was successfully queried. If you are querying a single data, just use the method used in the second lecture.
Use mybatis to increase data
Add method to the IUserOperation interface: public void addUser(User user);
Configure in User.xml
Program code
< !--Sql statement that performs an increase operation. id and parameterType are the same as the name and parameter type of the addUser method in the IUserOperation interface. References the name attribute of the Student parameter in the form of #{name}, and MyBatis will use reflection to read this attribute of the Student parameter. Name case sensitive in #{name}. Referring to other properties such as gender is consistent with this. seGeneratedKeys set to "true" indicates that MyBatis wants to obtain the primary key automatically generated by the database; keyProperty="id" specifies injecting the obtained primary key value into the Student's id property --> <insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id"> insert into user(userName,userAge,userAddress) values(#{userName},#{userAge},#{userAddress}) </insert>Then write the test method in Test:
Program code
/*** Test increases. After the increase, the transaction must be submitted, otherwise it will not be written to the database.*/public void addUser(){User user=new User();user.setUserAddress("People's Square");user.setUserName("Flying Bird");user.setUserAge(80);SqlSession session = sqlSessionFactory.openSession();try {IUserOperation userOperation=session.getMapper(IUserOperation.class);userOperation.addUser(user);session.commit();System.out.println("The current increased user id is:"+user.getId());} finally {session.close();}}Update data with mybatis
The method is similar. First add the method to IUserOperation: public void addUser(User user);
Then configure User.xml
Program code
<update id="updateUser" parameterType="User" >update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id}</update>The total test methods of the Test class are as follows:
Program code
public void updateUser(){//Get the user first, then modify and submit. SqlSession session = sqlSessionFactory.openSession();try {IUserOperation userOperation=session.getMapper(IUserOperation.class);User user = userOperation.selectUserByID(4); user.setUserAddress("It turns out to be Pudong Innovation Park in the Magic City");userOperation.updateUser(user);session.commit();} finally {session.close();}}Use mybatis to delete data
Similarly, the IUserOperation addition method: public void deleteUser(int id);
Configure User.xml
Program code
<delete id="deleteUser" parameterType="int">delete from user where id=#{id}</delete>Then write the test method in the Test class:
Program code
/*** To delete data, you must commit.* @param id*/public void deleteUser(int id){SqlSession session = sqlSessionFactory.openSession();try {IUserOperation userOperation=session.getMapper(IUserOperation.class); userOperation.deleteUser(id);session.commit(); } finally {session.close();}}In this way, all additions, deletions, modifications and checks are completed. Please note that session.commit() should be called when adding, changing, and deleting, so that the database will be operated in real time, otherwise it will not be submitted.
So far, I should be able to do simple single-table operations. In the next time, I will talk about multi-table joint query and the selection of result sets.
Mybatis practical tutorial (mybatis in action) 4: Implementing the query of related data
With the foundation of the previous chapters, some simple applications can be processed, but in actual projects, it is often queried for associative tables, such as the most common many-to-one, one-to-many, etc. How are these queries processed? This talk will talk about this issue. We first create an Article table and initialize the data.
Program code
Drop TABLE IF EXISTS `article`;Create TABLE `article` (`id` int(11) NOT NULL auto_increment,`userid` int(11) NOT NULL,`title` varchar(100) NOT NULL,`content` text NOT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;-- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- INTO `article` VALUES ('1', '1', 'test_title', 'test_content');Insert INTO `article` VALUES ('2', '1', 'test_title_2', 'test_content_2');Insert INTO `article` VALUES ('3', '1', 'test_title_3', 'test_content_3');Insert INTO `article` VALUES ('4', '1', 'test_title_4', 'test_content_4');You should have found that the userid corresponding to these articles is 1, so you need to have data with id=1 in the user table user. It can be modified to data that meets your own conditions. According to the orm rules, the table has been created, so an object must be corresponding to it, so we add an Article class
Program code
package com.yihaomen.mybatis.model;public class Article {private int id;private User user;private String title;private String content;public int getId() {return id;}public void setId(int id) {this.id = id;}public User getUser() {return user;}public void setUser(User user) {this.user = user;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}}Note how the user of the article defines it, it is a User object that is directly defined. Not the int type.
Many-to-one implementation
Scenario: Read all articles published by a certain user. Of course, you still need to configure the select statement in User.xml, but the key point is what kind of data does the resultMap of this select correspond to. This is the key point. Here we need to introduce association and see the definition as follows:
Program code
< !-- User Configure one of the query methods for joint articles (many-to-one) --> <resultMap id="resultUserArticleList" type="Article"><id property="id" column="aid" /><result property="title" column="title" /><result property="content" column="content" /><association property="user" javaType="User"><id property="id" column="id" /><result property="userName" column="userName" /><result property="userAddress" column="userAddress" /> </association> </resultMap>< select id="getUserArticles" parameterType="int" resultMap="resultUserArticleList">select user.id,user.userName,user.userAddress,article.id aid,article.title,article.content from user,articlewhere user.id=article.userid and user.id=#{id}</select>After this configuration, it's fine. Combine the select statement and the mapping corresponding to the resultMap and you will understand. Use association to get associated users, this is a many-to-one situation, because all articles belong to the same user.
There is another way to deal with it, which can reuse the resultMap we have defined earlier. We have defined a resultListUser before to see how this second method is implemented:
Program code
<resultMap type="User" id="resultListUser"><id column="id" property="id" /><result column="userName" property="userName" /><result column="userAge" property="userAge" /><result column="userAddress" property="userAddress" /></resultMap><!-- User Joint articles to conduct query methods two (a many-to-one method) --> <resultMap id="resultUserArticleList-2" type="Article"><id property="id" column="aid" /><result property="title" column="title" /><result property="content" column="content" /> <association property="user" javaType="User" resultMap="resultListUser" /> </resultMap><select id="getUserArticles" parameterType="int" resultMap="resultUserArticleList">select user.id,user.userName,user.userAddress,article.id aid,article.title,article.content from user,articlewhere user.id=article.userid and user.id=#{id}</select>Extract the corresponding maps in the association independently to achieve the purpose of multiplexing.
OK, now write the test code in the Test class:
Program code
public void getUserArticles(int userid){SqlSession session = sqlSessionFactory.openSession();try {IUserOperation userOperation=session.getMapper(IUserOperation.class); List<Article> articles = userOperation.getUserArticles(userid); for(Article article:articles){System.out.println(article.getTitle()+":"+article.getContent()+":The author is:"+article.getUser().getUserName()+":Address:"+article.getUser().getUserAddress());}} finally {session.close();}} A little missed, we must add the same method with the same id name as the select corresponding to the IUserOperation interface:
public List<Article> getUserArticles(int id);
Then run and test it.
Mybatis practical tutorial (mybatis in action) 5: Integration with spring3
In this series of articles, the examples of purely using mybatis to connect to the database, then perform addition, deletion, modification and query, and multi-table joint query. However, in actual projects, spring is usually used to manage datasources, etc. Make full use of spring interface-based programming and the convenience brought by aop and ioc. Using spring to manage mybatis has many similarities to managing hibernate. Today's focus is data source management and bean configuration.
You can download the source code and compare it. The source code does not have a jar package, it is too large and has limited space. There are screenshots, and you can see which jar packages are used. The source code is at the end of this article.
1. First, make some changes to the previous engineering structure, create a folder config in the src_user source code directory, and move the original mybatis configuration file Configuration.xml to this folder, and create a spring configuration file: applicationContext.xml in the config file folder. The most important configuration in this configuration file:
Program code
< !--This example uses a DBCP connection pool, and the DBCP jar package should be copied to the project's lib directory in advance. --> <bean id="dataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf8"/><property name="username" value="root"/> <property name="password" value="password"/> </bean> <bean id="sqlSessionFactory"> <!--dataSource property specifies the connection pool to be used--> <property name="dataSource" ref="dataSource"/> <!--configLocation property specifies the core configuration file of mybatis --> <property name="configLocation" value="config/Configuration.xml"/> </bean> <bean id="userMapper"> <!--sqlSessionFactory property specifies the instance of SqlSessionFactory to be used --> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> <!--mapperInterface property specifies the mapper interface, which is used to implement this interface and generate the mapper object --> <property name="mapperInterface" value="com.yihaomen.mybatis.inter.IUserOperation" /></bean>
[b]The key point here is that org.mybatis.spring.SqlSessionFactoryBean and org.mybatis.spring.mapper.MapperFactoryBean[b] implement the spring interface and generate objects. For details, you can view the mybatis-spring code. (http://code.google.com/p/mybatis/), if you only use it, fix the mode, so that the configuration is good.
Then write a test program
package com.yihaomen.test;import java.util.List;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.yihaomen.mybatis.inter.IUserOperation;import com.yihaomen.mybatis.model.Article;import com.yihaomen.mybatis.model.User;public class MybatisSprintTest {private static ApplicationContext ctx; static { ctx = new ClassPathXmlApplicationContext("config/applicationContext.xml"); } public static void main(String[] args) { IUserOperation mapper = (IUserOperation)ctx.getBean("userMapper"); //Test the user query with id=1. According to the situation in the database, it can be changed to your own.System.out.println("getUserAddress()"); User user = mapper.selectUserByID(1); System.out.println(user.getUserAddress()); //Get the article list test System.out.println("Get the list of all articles with user id 1"); List<Article> articles = mapper.getUserArticles(1); for(Article article:articles){System.out.println(article.getContent()+"--"+article.getTitle());}} }Run it to get the corresponding results.
Engineering drawings:
The jar package used is as shown in the figure below:
Mybatis practice tutorial (mybatis in action) 6: Integration with Spring MVC
The previous articles have already talked about the integration of mybatis and spring. But at this time, all the projects are not web projects, although I have always created web projects. Today, I will directly integrate mybatis and Spring mvc, and the source code will be downloaded at the end of this article. There are mainly the following configurations
1. web.xml configure spring dispatchservlet, for example: mvc-dispatcher
2. mvc-dispatcher-servlet.xml file configuration
3. spring applicationContext.XML file configuration (related to database, integrated with mybatis sqlSessionFaction, scan all mybatis mapper files, etc.)
4. Write the controller class
5. Write page code.
First, there is a rough image, and the entire project drawing is as follows:
1. web.xml configure spring dispatchservlet, for example: mvc-dispatcher
Program code Program code
<context-param><param-name>contextConfigLocation</param-name><param-value>classpath*:config/applicationContext.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><listener><listener-class>org.springframework.web.context.ContextClean upListener</listener-class></listener><servlet><servlet-name>mvc-dispatcher</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>mvc-dispatcher</servlet-name><url-pattern>/</url-pattern></servlet-mapping>
2. Configure the mvc-dispatcher-servlet.xml file in the same directory as web.xml. The previous part of this file name must correspond to the servlet name of the DispatcherServlet you configured in web.xml. The content is:
Program code
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"><context:component-scan base-package="com.yihaomen.controller" /><mvc:annotation-driven /><mvc:resources mapping="/static/**" location="/WEB-INF/static/"/> <mvc:default-servlet-handler//> <beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix"><value>/WEB-INF/pages/</value></property></property></beans>
3. Configure the spring configuration file applicationContext.xml in the source code directory config directory
Program code
< !--This example uses a DBCP connection pool, and the DBCP jar package should be copied to the project's lib directory in advance. --> <context:property-placeholder location="classpath:/config/database.properties" /><bean id="dataSource"destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"p:url="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf8" p:username="root" p:password="password" p:maxActive="10" p:maxIdle="10"></bean><bean id="transactionManager"><property name="dataSource" ref="dataSource" /></bean><bean id="sqlSessionFactory"> <!--dataSource property specifies the connection pool to be used--> <property name="dataSource" ref="dataSource"/> <!--configLocation property specifies the core configuration file of mybatis--> <property name="configLocation" value="classpath:config/Configuration.xml" /><!-- All configured mapper files--><property name="mapperLocations" value="classpath*:com/yihaomen/mapper/*.xml" /></bean> <bean><property name="basePackage" value="com.yihaomen.inter" /> </bean>
For some reason, once I use MapperScannerConfigurer to scan all mapper interfaces, the database configuration datasource cannot use the database.properties file to read. Error: Cannot load JDBC driver class '${jdbc.driverClassName}'. Some people on the Internet say that using sqlSessionFactionBean injection under spring 3.1.1 can solve it, but I still have problems using spring 3.1.3, so I had to configure the database connection information directly in the XML file.
4. Write the controller layer
Program code
package com.yihaomen.controller;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;import com.yihaomen.inter.IUserOperation;import com.yihaomen.model.Article;@Controller@RequestMapping("/article")public class UserController {@AutowiredIUserOperation userMapper;@RequestMapping("/list")public ModelAndView list(HttpServletRequest request,HttpServletResponse response){List<Article> articles=userMapper.getUserArticles(1); ModelAndView mav=new ModelAndView("list");mav.addObject("articles",articles);return mav;}}5. Page file:
< c:forEach items="${articles}" var="item"> ${item.id }--${item.title }--${item.content }<br /></c:forEach>Running results:
Of course, there is also the Configure.xml configuration file of mybatis, which is similar to the previous one. The only difference is that you no longer need to configure the following: <mapper resource="com/yihaomen/mapper/User.xml"/> , all of which are left to import by <property name="mapperLocations" value="classpath*:com/yihaomen/mapper/*.xml" /> when configuring the sqlSessionFactory.
Database download:
Download file spring mvc database test file
Mybatis Practical Tutorial (mybatis in action) 7: Implementing mybatis paging (source code download)
The previous article has already talked about the integration of mybatis and spring MVC, and has made a list display to display all article lists, but no pagination is used. In actual projects, pagination is definitely needed. And it is physical paging, not memory paging. For physical paging schemes, different databases have different implementation methods. For mysql, it is implemented using limit offset and pagesize. oracle is implemented through rownum. If you are familiar with the operations of related databases, it is also very good to extend. This article uses mysql as an example to illustrate. Let’s take a look at the renderings first (the source code is provided for download at the end of the article):
One of the easiest ways to implement mybatis physical paging is to directly write the following method in your mapper SQL statement:
Program code
<select id="getUserArticles" parameterType="Your_params" resultMap="resultUserArticleList">select user.id,user.userName,user.userAddress,article.id aid,article.title,article.content from user,articlewhere user.id=article.userid and user.id=#{id} limit #{offset},#{pagesize}</select>Please note that the parameterType here is the parameter class you passed in, or map, which contains offset, pagesize, and other parameters you need. In this way, you can definitely implement pagination. This is an easy way. But a more general way is to use the mybatis plugin. I have referenced a lot of information on the Internet, including mybatis plugin. Write your own plugin.
Program code
package com.yihaomen.util;import java.lang.reflect.Field;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.List;import java.util.Map;import java.util.Properties;import javax.xml.bind.PropertyException;import org.apache.ibatis.builder.xml.dynamic.ForEachSqlNode;import org.apache.ibatis.executor.ErrorContext;import org.apache.ibatis.executor.Executor;import org.apache.ibatis.executor.ExecutorException;import org.apache.ibatis.executor.statement.BaseStatementHandler;import org.apache.ibatis.executor.statement.RoutingStatementHandler;import org.apache.ibatis.executor.statement.StatementHandler;import org.apache.ibatis.mapping.BoundSql;import org.apache.ibatis.mapping.MappedStatement;import org.apache.ibatis.mapping.ParameterMapping;import org.apache.ibatis.mapping.ParameterMode;import org.apache.ibatis.plugin.Interceptor;import org.apache.ibatis.plugin.Intercepts;import org.apache.ibatis.plugin.Invocation;import org.apache.ibatis.plugin.Plugin;import org.apache.ibatis.plugin.Signature;import org.apache.ibatis.reflection.MetaObject;import org.apache.ibatis.reflection.property.PropertyTokenizer;import org.apache.ibatis.session.Configuration;import org.apache.ibatis.session.ResultHandler;import org.apache.ibatis.session.RowBounds;import org.apache.ibatis.type.TypeHandler;import org.apache.ibatis.type.TypeHandlerRegistry;@Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class }) }) public class PagePlugin implements Intercept {private static String dialect = "";private static String pageSqlId = "";@SuppressWarnings("unchecked")public Object intercept(Invocation ivk) throws Throwable {if (ivk.getTarget() instanceof RoutingStatementHandler) {RoutingStatementHandler statementHandler = (RoutingStatementHandler) ivk.getTarget();BaseStatementHandler delegate = (BaseStatementHandler) ReflectHelper.getValueByFieldName(statementHandler, "delegate");MappedStatement mappedStatement = (MappedStatement) ReflectHelper.getValueByFieldName(delegate, "mappedStatement");if (mappedStatement.getId().matches(pageSqlId)) {BoundSql boundSql = delegate.getBoundSql();Object parameterObject = boundSql.getParameterObject();if (parameterObject == null) {throw new NullPointerException("parameterObject error");} else {Connection connection = (Connection) ivk.getArgs()[0];String sql = boundSql.getSql();String countSql = "select count(0) from (" + sql + ") myCount";System.out.println("Total number of sql statement:"+countSql);PreparedStatement countStmt = connection.prepareStatement(countSql);BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), countSql,boundSql.getParameterMappings(), parameterObject);setParameters(countStmt, mappedStatement, countBS, parameterObject);ResultSet rs = countStmt.executeQuery();int count = 0;if (rs.next()) {count = rs.getInt(1);}rs.close();countStmt.close();PageInfo page = null;if (parameterObject instanceof PageInfo) {page = (PageInfo) parameterObject;page.setTotalResult(count);} else if(parameterObject instanceof Map){Map<String, Object> map = (Map<String, Object>)parameterObject;page = (PageInfo)map.get("page");if(page == null)page = new PageInfo();page.setTotalResult(count);}else {Field pageField = ReflectHelper.getFieldByFieldName(parameterObject, "page");if (pageField != null) {page = (PageInfo) ReflectHelper.getValueByFieldName(parameterObject, "page");if (page == null)page = new PageInfo();page.setTotalResult(count);ReflectHelper.setValueByFieldName(parameterObject,"page", page);} else {throw new NoSuchFieldException(parameterObject.getClass().getName());}}String pageSql = generatePageSql(sql, page);System.out.println("page sql:"+pageSql);ReflectHelper.setValueByFieldName(boundSql, "sql", pageSql);}}}return ivk.proceed();}private void setParameters(PreparedStatement ps,MappedStatement mappedStatement, BoundSql boundSql,Object parameterObject) throws SQLException {ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();if (parameterMappings != null) {Configuration configuration = mappedStatement.getConfiguration();TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();MetaObject metaObject = parameterObject == null ? null: configuration.newMetaObject(parameterObject);for (int i = 0; i < parameterMappings.size(); i++) {ParameterMapping parameterMapping = parameterMappings.get(i);if (parameterMapping.getMode() != ParameterMode.OUT) {Object value;String propertyName = parameterMapping.getProperty();PropertyTokenizer prop = new PropertyTokenizer(propertyName);if (parameterObject == null) {value = null;} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {value = parameterObject;} else if (boundSql.hasAdditionalParameter(propertyName)) {value = boundSql.getAdditionalParameter(propertyName);} else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX)&& boundSql.hasAdditionalParameter(prop.getName())) {value = boundSql.getAdditionalParameter(prop.getName());if (value != null) {value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()));}} else {value = metaObject == null ? null : metaObject.getValue(propertyName);}TypeHandler typeHandler = parameterMapping.getTypeHandler();if (typeHandler == null) {throw new ExecutorException("There was no TypeHandler found for parameter "+ propertyName + " of statement "+ mappedStatement.getId());}typeHandler.setParameter(ps, i + 1, value,parameterMapping.getJdbcType());}}}}private String generatePageSql(String sql, PageInfo page) {if (page != null && (dialect !=null || !dialect.equals(""))) {StringBuffer pageSql = new StringBuffer();if ("mysql".equals(dialect)) {pageSql.append(sql);pageSql.append(" limit " + page.getCurrentResult() + ","+ page.getShowCount());} else if ("oracle".equals(dialect)) {pageSql.append("select * from (select tmp_tb.*,ROWNUM row_id from (");pageSql.append(sql);pageSql.append(") tmp_tb where ROWNUM<=");pageSql.append(page.getCurrentResult() + page.getShowCount());pageSql.append(") where row_id>");pageSql.append(page.getCurrentResult());}return pageSql.toString();} else {return sql;}}public Object plugin(Object arg0) {// TODO Auto-generated method stubreturn Plugin.wrap(arg0, this);}public void setProperties(Properties p) {dialect = p.getProperty("dialect");if (dialect ==null || dialect.equals("")) {try {throw new PropertyException("dialect property is not found!");} catch (PropertyException e) {// TODO Auto-generated catch blocke.printStackTrace();}}pageSqlId = p.getProperty("pageSqlId");if (dialect ==null || dialect.equals("")) {try {throw new PropertyException("pageSqlId property is not found!");} catch (PropertyException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}此插件有两个辅助类:PageInfo,ReflectHelper,你可以下载源代码参考。
写了插件之后,当然需要在mybatis 的配置文件Configuration.xml 里配置这个插件
Program code
<plugins><plugin interceptor="com.yihaomen.util.PagePlugin"><property name="dialect" value="mysql" /><property name="pageSqlId" value=".*ListPage.*" /></plugin></plugins>
请注意,这个插件定义了一个规则,也就是在mapper中sql语句的id 必须包含ListPage才能被拦截。否则将不会分页处理.
插件写好了,现在就可以在spring mvc 中的controller 层中写一个方法来测试这个分页:
Program code
@RequestMapping("/pagelist")public ModelAndView pageList(HttpServletRequest request,HttpServletResponse response){int currentPage = request.getParameter("page")==null?1:Integer.parseInt(request.getParameter("page"));int pageSize = 3;if (currentPage<=0){currentPage =1;}int currentResult = (currentPage-1) * pageSize;System.out.println(request.getRequestURI());System.out.println(request.getQueryString());PageInfo page = new PageInfo();page.setShowCount(pageSize);page.setCurrentResult(currentResult);List<Article> articles=iUserOperation.selectArticleListPage(page,1);System.out.println(page);int totalCount = page.getTotalResult();int lastPage=0;if (totalCount % pageSize==0){lastPage = totalCount % pageSize;}else{lastPage =1+ totalCount / pageSize;}if (currentPage>=lastPage){currentPage =lastPage;}String pageStr = "";pageStr=String.format("<a href=/"%s/">上一页</a> <a href=/"%s/">下一页</a>",request.getRequestURI()+"?page="+(currentPage-1),request.getRequestURI()+"?page="+(currentPage+1) );//制定视图,也就是list.jspModelAndView mav=new ModelAndView("list");mav.addObject("articles",articles);mav.addObject("pageStr",pageStr);return mav;}然后运行程序,进入分页页面,你就可以看到结果了:
相关jar 包下载,请到下载这里例子中的jar
http://www.yihaomen.com/article/java/318.htm (文章最后有源代码下载,里面有jar 包,拷贝到上面源代码里面所需要的lib 目录下.)
另外,你还得在前面提到的数据库artilce表里面,多插入一些记录,分页效果就更好。
mybatis实战教程(mybatis in action)之八:mybatis 动态sql语句
mybatis 的动态sql语句是基于OGNL表达式的。可以方便的在sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类:
1. if 语句(简单的条件判断)
2. choose (when,otherwize) ,相当于java 语言中的switch ,与jstl 中的choose 很类似.
3. trim (对包含的内容加上prefix,或者suffix 等,前缀,后缀)
4. where (主要是用来简化sql语句中where条件判断的,能智能的处理and or ,不必担心多余导致语法错误)
5. set (主要用于更新时)
6. foreach (在实现mybatis in 语句查询时特别有用)
下面分别介绍这几种处理方式
1. mybaits if 语句处理
Program code
<select id="dynamicIfTest" parameterType="Blog" resultType="Blog">select * from t_blog where 1 = 1<if test="title != null">and title = #{title}</if><if test="content != null">and content = #{content}</if><if test="owner != null">and owner = #{owner}</if></select>这条语句的意思非常简单,如果你提供了title参数,那么就要满足title=#{title},同样如果你提供了Content和Owner的时候,它们也需要满足相应的条件,之后就是返回满足这些条件的所有Blog,这是非常有用的一个功能,以往我们使用其他类型框架或者直接使用JDBC的时候, 如果我们要达到同样的选择效果的时候,我们就需要拼SQL语句,这是极其麻烦的,比起来,上述的动态SQL就要简单多了
2.2. choose (when,otherwize) ,相当于java 语言中的switch ,与jstl 中的choose 很类似
Program code
<select id="dyamicChooseTest" parameterType="Blog" resultType="Blog">select * from t_blog where 1 = 1 <choose><when test="title != null">and title = #{title}</when><when test="content != null">and content = #{content}</when><otherwise>and owner = "owner1"</otherwise></choose></select>when元素表示当when中的条件满足的时候就输出其中的内容,跟JAVA中的switch效果差不多的是按照条件的顺序,当when中有条件满足的时候,就会跳出choose,即所有的when和otherwise条件中,只有一个会输出,当所有的我很条件都不满足的时候就输出otherwise中的内容。所以上述语句的意思非常简单, 当title!=null的时候就输出and titlte = #{title},不再往下判断条件,当title为空且content!=null的时候就输出and content = #{content},当所有条件都不满足的时候就输出otherwise中的内容。
3.trim (对包含的内容加上prefix,或者suffix 等,前缀,后缀)
Program code
<select id="dynamicTrimTest" parameterType="Blog" resultType="Blog">select * from t_blog <trim prefix="where" prefixOverrides="and |or"><if test="title != null">title = #{title}</if><if test="content != null">and content = #{content}</if><if test="owner != null">or owner = #{owner}</if></trim></select>trim元素的主要功能是可以在自己包含的内容前加上某些前缀,也可以在其后加上某些后缀,与之对应的属性是prefix和suffix;可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverrides;正因为trim有这样的功能,所以我们也可以非常简单的利用trim来代替where元素的功能
4. where (主要是用来简化sql语句中where条件判断的,能智能的处理and or 条件
Program code
<select id="dynamicWhereTest" parameterType="Blog" resultType="Blog">select * from t_blog <where><if test="title != null">title = #{title}</if><if test="content != null">and content = #{content}</if><if test="owner != null">and owner = #{owner}</if></where></select>where元素的作用是会在写入where元素的地方输出一个where,另外一个好处是你不需要考虑where元素里面的条件输出是什么样子的,MyBatis会智能的帮你处理,如果所有的条件都不满足那么MyBatis就会查出所有的记录,如果输出后是and 开头的,MyBatis会把第一个and忽略,当然如果是or开头的,MyBatis也会把它忽略;此外,在where元素中你不需要考虑空格的问题,MyBatis会智能的帮你加上。像上述例子中,如果title=null, 而content != null,那么输出的整个语句会是select * from t_blog where content = #{content},而不是select * from t_blog where and content = #{content},因为MyBatis会智能的把首个and 或or 给忽略。
5.set (主要用于更新时)
Program code
<update id="dynamicSetTest" parameterType="Blog">update t_blog<set><if test="title != null">title = #{title},</if><if test="content != null">content = #{content},</if><if test="owner != null">owner = #{owner}</if></set>where id = #{id}</update>set元素主要是用在更新操作的时候,它的主要功能和where元素其实是差不多的,主要是在包含的语句前输出一个set,然后如果包含的语句是以逗号结束的话将会把该逗号忽略,如果set包含的内容为空的话则会出错。有了set元素我们就可以动态的更新那些修改了的字段
6. foreach (在实现mybatis in 语句查询时特别有用)
foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有item,index,collection,open,separator,close。item表示集合中每一个元素进行迭代时的别名,index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔符,close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况:
如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key
1.1.单参数List的类型
Program code
<select id="dynamicForeachTest" resultType="Blog">select * from t_blog where id in<foreach collection="list" index="index" item="item" open="(" separator="," close=")">#{item}</foreach></select>上述collection的值为list,对应的Mapper是这样的
Program code
public List<Blog> dynamicForeachTest(List<Integer> ids);
测试代码
@Testpublic void dynamicForeachTest() {SqlSession session = Util.getSqlSessionFactory().openSession();BlogMapper blogMapper = session.getMapper(BlogMapper.class);List<Integer> ids = new ArrayList<Integer>();ids.add(1);ids.add(3);ids.add(6);List<Blog> blogs = blogMapper.dynamicForeachTest(ids);for (Blog blog : blogs)System.out.println(blog);session.close();}2.数组类型的参数
Program code
<select id="dynamicForeach2Test" resultType="Blog">select * from t_blog where id in<foreach collection="array" index="index" item="item" open="(" separator="," close=")">#{item}</foreach></select>对应mapper
Program code
public List<Blog> dynamicForeach2Test(int[] ids);
3. Map 类型的参数
Program code
<select id="dynamicForeach3Test" resultType="Blog">select * from t_blog where title like "%"#{title}"%" and id in<foreach collection="ids" index="index" item="item" open="(" separator="," close=")">#{item}</foreach></select>mapper 应该是这样的接口:
Program code
public List<Blog> dynamicForeach3Test(Map<String, Object> params);
通过以上方法,就能完成一般的mybatis 的动态SQL 语句.最常用的就是if where foreach这几个,一定要重点掌握.
mybatis实战教程(mybatis in action)之九:mybatis 代码生成工具的使用
mybatis 应用程序,需要大量的配置文件,对于一个成百上千的数据库表来说,完全手工配置,这是一个很恐怖的工作量. 所以mybatis 官方也推出了一个mybatis代码生成工具的jar包. 今天花了一点时间,按照mybatis generator 的doc 文档参考,初步配置出了一个可以使用的版本,我把源代码也提供下载,mybatis 代码生成工具,主要有一下功能:
1.生成pojo 与数据库结构对应
2.如果有主键,能匹配主键
3.如果没有主键,可以用其他字段去匹配
4.动态select,update,delete 方法
5.自动生成接口(也就是以前的dao层)
6.自动生成sql mapper,增删改查各种语句配置,包括动态where语句配置
7.生成Example 例子供参考
下面介绍下详细过程
1. 创建测试工程,并配置mybatis代码生成jar包下载地址:http://code.google.com/p/mybatis/downloads/list?can=3&q=Product%3DGenerator
mysql 驱动下载:http://dev.mysql.com/downloads/connector/j/
这些jar包,我也会包含在源代码里面,可以在文章末尾处,下载源代码,参考。
用eclipse 建立一个dynamic web project。
解压下载后的mybatis-generator-core-1.3.2-bundle.zip 文件,其中有两个目录:一个目录是文档目录docs,主要介绍这个代码生成工具如何使用,另一个是lib目录,里面的内容主要是jar 包,这里我们需要mybatis-generator-core-1.3.2.jar,这个jar 包. 将它拷贝到我们刚刚创建的web工程的WebContent/WEB-INF/lib 目录下.在这个目录下也放入mysql 驱动jar包.因为用mysql 做测试的.
2.在数据库中创建测试表
在mybatis数据库中创建用来测试的category表(如果没有mybatis这个数据库,要创建,这是基于前面这个系列文章而写的,已经有了mybatis 这个数据库)
Program code
Drop TABLE IF EXISTS `category`;Create TABLE `category` (`id` int(11) NOT NULL AUTO_INCREMENT,`catname` varchar(50) NOT NULL,`catdescription` varchar(200) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3. 配置mybatis 代码生成工具的配置文件
在创建的web工程中,创建相应的package 比如:
com.yihaomen.inter 用来存放mybatis 接口对象.
com.yihaomen.mapper用来存放sql mapper对应的映射,sql语句等.
com.yihaomen.model 用来存放与数据库对应的model 。
在用mybatis 代码生成工具之前,这些目录必须先创建好,作为一个好的应用程序,这些目录的创建也是有规律的。
根据mybatis代码生成工具文档,需要一个配置文件,这里命名为:mbgConfiguration.xml 放在src 目录下. 配置文件内容如下:
Program code
< ?xml version="1.0" encoding="UTF-8"?>< !DOCTYPE generatorConfigurationPUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN""http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">< generatorConfiguration><!-- 配置mysql 驱动jar包路径.用了绝对路径--><classPathEntry location="D:/Work/Java/eclipse/workspace/myBatisGenerator/WebContent/WEB-INF/lib/mysql-connector-java-5.1.22-bin.jar" /><context id="yihaomen_mysql_tables" targetRuntime="MyBatis3"><!-- 为了防止生成的代码中有很多注释,比较难看,加入下面的配置控制--><commentGenerator><property name="suppressAllComments" value="true" /><property name="suppressDate" value="true" /></commentGenerator><!-- 注释控制完毕--><!-- 数据库连接--><jdbcConnection driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf8"userId="root"password="password"></jdbcConnection><javaTypeResolver ><property name="forceBigDecimals" value="false" /></javaTypeResolver><!-- 数据表对应的model 层--><javaModelGenerator targetPackage="com.yihaomen.model" targetProject="src"><property name="enableSubPackages" value="true" /><property name="trimStrings" value="true" /></javaModelGenerator><!-- sql mapper 隐射配置文件--><sqlMapGenerator targetPackage="com.yihaomen.mapper" targetProject="src"><property name="enableSubPackages" value="true" /></sqlMapGenerator><!-- 在ibatis2 中是dao层,但在mybatis3中,其实就是mapper接口--><javaClientGenerator type="XMLMAPPER" targetPackage="com.yihaomen.inter" targetProject="src"><property name="enableSubPackages" value="true" /></javaClientGenerator><!-- 要对那些数据表进行生成操作,必须要有一个. --><table schema="mybatis" tableName="category" domainObjectName="Category" enableCountByExample="false" enableUpdateByExample="false"enableDeleteByExample="false" enableSelectByExample="false"selectByExampleQueryId="false"> </table></context>< /generatorConfiguration>
用一个main 方法来测试能否用mybatis 成生成刚刚创建的`category`表对应的model,sql mapper等内容.
创建一个com.yihaomen.test 的package ,并在此package 下面建立一个测试的类GenMain:
Program code
package com.yihaomen.test;import java.io.File;import java.io.IOException;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import org.mybatis.generator.api.MyBatisGenerator;import org.mybatis.generator.config.Configuration;import org.mybatis.generator.config.xml.ConfigurationParser;import org.mybatis.generator.exception.InvalidConfigurationException;import org.mybatis.generator.exception.XMLParserException;import org.mybatis.generator.internal.DefaultShellCallback;public class GenMain {public static void main(String[] args) {List<String> warnings = new ArrayList<String>();boolean overwrite = true;String genCfg = "/mbgConfiguration.xml";File configFile = new File(GenMain.class.getResource(genCfg).getFile());ConfigurationParser cp = new ConfigurationParser(warnings);Configuration config = null;try {config = cp.parseConfiguration(configFile);} catch (IOException e) {e.printStackTrace();} catch (XMLParserException e) {e.printStackTrace();}DefaultShellCallback callback = new DefaultShellCallback(overwrite);MyBatisGenerator myBatisGenerator = null;try {myBatisGenerator = new MyBatisGenerator(config, callback, warnings);} catch (InvalidConfigurationException e) {e.printStackTrace();}try {myBatisGenerator.generate(null);} catch (SQLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}}}到此为止,eclipse项目工程图应该如下:
4.运行测试的main 方法,生成mybatis 相关代码
运行GenMain类里的main方法,并刷新工程,你会发现各自package 目录下已经响应生成了对应的文件,完全符合mybatis 规则,效果图如下:
5.注意事项
如果你想生成example 之类的东西,需要在<table></table>里面去掉
Program code
enableCountByExample="false" enableUpdateByExample="false"enableDeleteByExample="false" enableSelectByExample="false"selectByExampleQueryId="false"
这部分配置,这是生成Example而用的,一般来说对项目没有用.
另外生成的sql mapper 等,只是对单表的增删改查,如果你有多表join操作,你就可以手动配置,如果调用存储过程,你也需要手工配置. 这时工作量已经少很多了。
如果你想用命令行方式处理,也是可以的.
Program code
for example:
java -jar mybatis-generator-core-1.3.2.jar -mbgConfiguration.xm -overwrite
这时,要用绝对路径才行. 另外mbgConfiguration.xml 配置文件中targetProject 的配置也必须是绝对路径了。
mybatis SqlSessionDaoSupport的使用
前面的系列mybatis 文章,已经基本讲到了mybatis的操作,但都是基于mapper隐射操作的,在mybatis 3中这个mapper 接口貌似充当了以前在ibatis 2中的DAO 层的作用。但事实上,如果有这个mapper接口不能完成的工作,或者需要更复杂的扩展的时候,你就需要自己的DAO 层. 事实上mybatis 3 也是支持DAO 层设计的,类似于ibatis 2 .下面介绍下.
首先创建一个com.yihaomen.dao的package.然后在里面分别创建接口UserDAO,以及实现该接口的UserDAOImpl
Program code
package com.yihaomen.dao;import java.util.List;import com.yihaomen.model.Article;public interface UserDAO {public List<Article> getUserArticles(int userid);}Program code
package com.yihaomen.dao;import java.util.List;import org.mybatis.spring.support.SqlSessionDaoSupport;import org.springframework.stereotype.Repository;import com.yihaomen.model.Article;@Repositorypublic class UserDAOImpl extends SqlSessionDaoSupport implements UserDAO {@Overridepublic List<Article> getUserArticles(int userid) { return this.getSqlSession().selectList("com.yihaomen.inter.IUserOperation.getUserArticles",userid);}}执行的SQL 语句采用了命名空间+sql 语句id的方式,后面是参数.
注意继承了"SqlSessionDaoSupport" ,利用方法getSqlSession() 可以得到SqlSessionTemplate ,从而可以执行各种sql语句,类似于hibernatetemplate一样,至少思路一样.
如果与spring 3 mvc 集成要用autowire的话,在daoimpl 类上加上注解“@Repository” ,另外还需要在spring 配置文件中加入<context:component-scan base-package="com.yihaomen.dao" /> 这样在需要调用的地方,就可以使用autowire自动注入了。
当然,你也可以按一般程序的思路,创建一个service 的package, 用service 去调用dao层,我这里就没有做了,因为比较简单,用类似的方法,也机注意自动注入时,也要配置<context:component-scan base-package="com.yihaomen.service" /> 等这样的。
在controller层中测试,直接调用dao层方法在controller中加入方法:
Program code
@AutowiredUserDAO userDAO;.......@RequestMapping("/daolist")public ModelAndView listalldao(HttpServletRequest request,HttpServletResponse response){List<Article> articles=userDAO.getUserArticles(1);//制定视图,也就是list.jspModelAndView mav=new ModelAndView("list");mav.addObject("articles",articles);return mav;}这样可以得到同样的结果,而且满足了一般程序的设计方法.代码结构如下:
以上所述是本文给大家介绍的Mybatis实战教程之入门到精通(经典)的相关知识,希望对大家有所帮助。