话不多说,简单粗暴
pom.xml:
<!-- Mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <!-- Mybatis Spring 插件 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency>
首先编写IMybatisDao接口:
public interface IMybatisDao { public Object getObjectByID(String statement, int id) throws DaoException; public <E> List<E> getObjectList(String statement, Object parameter) throws DaoException; public <E> List<E> getObjectList(Map<String, Object> parameter) throws DaoException; public <E> ListVo<E> getObjectPage(String statement, Map<String, Object> parameter, RowBounds rowBounds) throws DaoException; public <E> ListVo<E> getObjectPage(Map<String, Object> parameter, RowBounds rowBounds) throws DaoException; public void update(String statement, Map<String, Object> parameter) throws DaoException; public void update(String statement, Object obj) throws DaoException; public void delete(String statement, Map<String, Object> parameter) throws DaoException; public void delete(String statement, Object parameter) throws DaoException; public void insert(String statement, Map<String, Object> parameter) throws DaoException; public void insert(String statement, Object parameter) throws DaoException; public Object getObjectByMap(String statement, Map<String, Object> paramMap) throws DaoException; public <T> T getUniqueObject(String statement, Object object) throws DaoException; public Long insertReturn(String statement, Map<String, Object> parameter) throws DaoException; }
然后编写实现类MybatisDaoImpl实现以上接口:
/** * mybatis数据库实现基类 */ @Repository(value = "mybatisDao") public class MybatisDaoImpl implements IMybatisDao { @Autowired private SqlSessionTemplate sqlSession; @Override public Object getObjectByID(String statement, int id) { Object object; try { object = sqlSession.selectOne(statement, id); } catch (Exception e) { e.printStackTrace(); throw new DaoException(e); } return object; } @Override public Object getObjectByMap(String statement, Map<String, Object> paramMap) { Object object; try { object = sqlSession.selectOne(statement, paramMap); } catch (Exception e) { throw new DaoException(e); } return object; } @Override public <T> T getUniqueObject(String statement, Object object) { try { return sqlSession.selectOne(statement, object); } catch (Exception e) { throw new DaoException(e); } } @Override public <E> List<E> getObjectList(String statement, Object param) { try { return sqlSession.selectList(statement, param); } catch (Exception e) { throw new DaoException(e); } } @Override public <E> List<E> getObjectList(Map<String, Object> parameter) { try { return sqlSession.selectList("common.select", parameter); } catch (Exception e) { throw new DaoException(e); } } @Override public <E> ListVo<E> getObjectPage(String statement, Map<String, Object> parameter, RowBounds rowBounds) { ListVo<E> listVo = new ListVo<E>(); try { if (rowBounds == null) { List<E> listObect = sqlSession.selectList(statement, parameter); listVo.setList(listObect); listVo.setTotalSize(-1); } else { List<E> listObect = sqlSession.selectList(statement, parameter, rowBounds); listVo.setList(listObect); listVo.setTotalSize((Integer) parameter.get("pageCount")); } } catch (Exception e) { throw new DaoException(e); } return listVo; } @Override public <E> ListVo<E> getObjectPage(Map<String, Object> parameter, RowBounds rowBounds) { ListVo<E> listVo = new ListVo<E>(); try { if (rowBounds == null) { List<E> listObect = sqlSession.selectList("common.select", parameter); listVo.setList(listObect); listVo.setTotalSize(-1); } else { List<E> listObect = sqlSession.selectList("common.select", parameter, rowBounds); listVo.setList(listObect); listVo.setTotalSize((Integer) parameter.get("pageCount")); } } catch (Exception e) { throw new DaoException(e); } return listVo; } @Override public void insert(String statement, Map<String, Object> parameter) throws DaoException { try { sqlSession.insert(statement, parameter); } catch (Exception e) { e.printStackTrace(); throw new DaoException(e); } } @Override public void insert(String statement, Object parameter) throws DaoException { try { sqlSession.insert(statement, parameter); } catch (Exception e) { e.printStackTrace(); throw new DaoException(e); } } @Override public void update(String statement, Map<String, Object> parameter) throws DaoException { try { sqlSession.update(statement, parameter); } catch (Exception e) { e.printStackTrace(); throw new DaoException(e); } } @Override public void update(String statement, Object parameter) throws DaoException { try { sqlSession.update(statement, parameter); } catch (Exception e) { e.printStackTrace(); throw new DaoException(e); } } @Override public void delete(String statement, Map<String, Object> parameter) throws DaoException { try { sqlSession.delete(statement, parameter); } catch (Exception e) { e.printStackTrace(); throw new DaoException(e); } } @Override public void delete(String statement, Object parameter) throws DaoException { try { sqlSession.delete(statement, parameter); } catch (Exception e) { e.printStackTrace(); throw new DaoException(e); } } @Override public Long insertReturn(String statement, Map<String, Object> parameter) throws DaoException { try { sqlSession.insert(statement, parameter); Long id = (Long) parameter.get("id"); return id; } catch (Exception e) { e.printStackTrace(); throw new DaoException(e); } } }
封装分页数据:
/** * 封装List数据 */ public class ListVo<T> { /** * 初始化构造方法 */ public ListVo() { this.totalSize = 0; list = new ArrayList<T>(); } /** * 记录总条数 */ private int totalSize; /** * 记录列表 */ private List<T> list; public List<T> getList() { return list; } public void setList(List<T> list) { this.list = list; } public int getTotalSize() { return totalSize; } public void setTotalSize(int totalSize) { this.totalSize = totalSize; } }
MybatisInterceptor分页查询拦截器:
/** * 分页查询拦截器 */ @Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})}) public class MybatisInterceptor implements Interceptor { protected final Logger log = Logger.getLogger(this.getClass()); @SuppressWarnings("unchecked") @Override public Object intercept(Invocation invocation) throws Throwable { StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); Connection connection = (Connection) invocation.getArgs()[0]; MetaObject metaStatementHandler = MetaObject.forObject(statementHandler, new DefaultObjectFactory(), new DefaultObjectWrapperFactory()); String originalSql = (String) metaStatementHandler.getValue("delegate.boundSql.sql"); if (originalSql.toUpperCase().indexOf("INSERT") >= 0) { } else { log.info(originalSql); } MappedStatement mappedStatement = (MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement"); RowBounds rowBounds = (RowBounds) metaStatementHandler.getValue("delegate.rowBounds"); if (rowBounds == null || rowBounds == RowBounds.DEFAULT) { return invocation.proceed(); } Configuration configuration = (Configuration) metaStatementHandler.getValue("delegate.configuration"); String dialect = null; try { dialect = configuration.getVariables().getProperty("dialect").toUpperCase(); if (dialect == null || "".equals(dialect)) { throw new RuntimeException("the value of the dialect property in configuration.xml is not defined"); } } catch (Exception e) { System.out.println("mybatis-config.xml中未设置数据库类型"); } ParameterHandler parameter = statementHandler.getParameterHandler(); if ("MYSQL".equals(dialect)) { if (parameter != null && parameter.getParameterObject() instanceof Map) { int count = this.getCount(configuration, connection, statementHandler, mappedStatement); ((Map<String, Object>) parameter.getParameterObject()).put("pageCount", count); //为参数map赋值,用以保存有多少页 } metaStatementHandler.setValue("delegate.boundSql.sql", this.getMysqlLimitString(originalSql, rowBounds.getOffset(), rowBounds.getLimit())); } metaStatementHandler.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET); metaStatementHandler.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT); // System.out.println(" 生成分页SQL : " + boundSql.getSql()); return invocation.proceed(); } private String getMysqlLimitString(String sql, int offset, int limit) { StringBuffer mysql = new StringBuffer(sql.trim()); mysql.append(" limit"); mysql.append(" " + offset); mysql.append("," + limit); return mysql.toString(); } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties arg0) { } private int getCount(Configuration configuration, Connection connection, StatementHandler statementHandler, MappedStatement mappedStatement) { int count = 0; PreparedStatement countStmt = null; ResultSet rs = null; try { BoundSql boundSql = statementHandler.getBoundSql(); Object parameterObject = statementHandler.getParameterHandler().getParameterObject(); String countSql = "select count(0) from (" + boundSql.getSql() + ")" + " as temp_table"; //记录统计 List<ParameterMapping> parameterMappingList = boundSql.getParameterMappings(); countStmt = connection.prepareStatement(countSql); BoundSql newBoundSql = new BoundSql(configuration, countSql, parameterMappingList, parameterObject); setParameters(countStmt, mappedStatement, newBoundSql, parameterObject); rs = countStmt.executeQuery(); if (rs.next()) { count = rs.getInt(1); } } catch (Exception e) { e.printStackTrace(); } return count; } /** * 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler * * @param ps * @param mappedStatement * @param boundSql * @param parameterObject * @throws SQLException */ @SuppressWarnings({"unchecked", "rawtypes"}) 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()); } } } } }
SQL日志配置mybatis.cfg.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "mybatis-3-config.dtd"> <configuration> <properties> <property name="dialect" value="mysql"/> </properties> <settings> <!-- 打印查询语句 --> <setting name="logImpl" value="LOG4J"/> <!-- 查询语句的resultType为Map时,为NULL的字段也要显示,主要针对oracle --> <setting name="callSettersOnNulls" value="true"/> </settings> <plugins> <plugin interceptor="com.test.base.common.interceptor.MybatisInterceptor"/> </plugins> </configuration>
mybatis.xml配置文件:(记得在Spring中管理<import resource="mybatis.xml"></import>)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <!-- 本地数据源开始 --> <!-- <bean id="dbPasswordCallback" class="com.test.base.util.DbPasswordCallback" lazy-init="true"/>--> <bean id="localDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${local.url}"/> <property name="username" value="${local.username}"/> <!-- <property name="connectionProperties" value="password=${local.password}"/>--> <!-- <property name="passwordCallback" ref="dbPasswordCallback"/>--> <property name="password" value="${local.password}"/> <!-- 解密密码必须要配置的项 --> <!-- 监控数据库 --> <property name="filters" value="stat,config"/> <property name="connectionProperties" value="config.decrypt=true;config.decrypt.key=${local.publicKey}"/> <!-- 初始化连接大小 --> <property name="initialSize" value="${local.initialSize}"/> <property name="driverClassName" value="${local.driverClassName}"/> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="${local.maxActive}"/> <!-- 连接池最小空闲 --> <property name="minIdle" value="${local.minIdle}"/> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${local.maxWait}"/> <!-- 用来检测连接是否有效的sql,要求是一个查询语句。如果validationQuery为null, testOnBorrow、testOnReturn、testWhileIdle都不会其作用 --> <property name="validationQuery" value="SELECT 1 FROM DUAL"/> <!-- 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 --> <property name="testOnBorrow" value="false"/> <!-- 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 --> <property name="testOnReturn" value="false"/> <!-- 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测, 如果空闲时间大于timeBetweenEvictionRunsMillis, 执行validationQuery检测连接是否有效 --> <property name="testWhileIdle" value="true"/> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000"/> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true"/> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800"/> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true"/> </bean> <!-- 事务管理器start --> <bean id="localTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="localDataSource"/> </bean> <tx:advice id="localTxAdvice" transaction-manager="localTransactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="get*" propagation="REQUIRED" read-only="true"/> <tx:method name="query*" propagation="REQUIRED" read-only="true"/> <tx:method name="find*" propagation="REQUIRED" read-only="true"/> <tx:method name="*" propagation="REQUIRED" read-only="true"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="localTxAdvicePointcut" expression="(execution(* com.test.base.service.*.*.*(..))) or (execution(* com.test.base.service.*.*(..))) "/> <aop:advisor pointcut-ref="localTxAdvicePointcut" advice-ref="localTxAdvice"/> </aop:config> <!--事务管理器end --> <bean id="localSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="localDataSource"/> <property name="configLocation" value="classpath:/mybatis/mybatis.cfg.xml"/> <property name="mapperLocations"> <list> <value>classpath:/com/test/base/dao/mapper/*.xml</value> </list> </property> </bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="localSqlSessionFactory"/> </bean> <!-- 本地数据源结束 --> </beans>
mybatis-3-config.dtd与mybatis-3-mapper.dtd文件解读: https://blog.csdn.net/ljf12138/article/details/102865440
我是把这两个文件放在这个路径下的:srcmain esourcesmybatis
mybatis-3-config.dtd:
<?xml version="1.0" encoding="UTF-8" ?> <!-- Copyright 2009-2012 The MyBatis Team Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!ELEMENT configuration (properties?, settings?, typeAliases?, typeHandlers?, objectFactory?, objectWrapperFactory?, plugins?, environments?, databaseIdProvider?, mappers?)> <!ELEMENT databaseIdProvider (property*)> <!ATTLIST databaseIdProvider type CDATA #REQUIRED > <!ELEMENT properties (property*)> <!ATTLIST properties resource CDATA #IMPLIED url CDATA #IMPLIED > <!ELEMENT property EMPTY> <!ATTLIST property name CDATA #REQUIRED value CDATA #REQUIRED > <!ELEMENT settings (setting+)> <!ELEMENT setting EMPTY> <!ATTLIST setting name CDATA #REQUIRED value CDATA #REQUIRED > <!ELEMENT typeAliases (typeAlias*,package*)> <!ELEMENT typeAlias EMPTY> <!ATTLIST typeAlias type CDATA #REQUIRED alias CDATA #IMPLIED > <!ELEMENT typeHandlers (typeHandler*,package*)> <!ELEMENT typeHandler EMPTY> <!ATTLIST typeHandler javaType CDATA #IMPLIED jdbcType CDATA #IMPLIED handler CDATA #REQUIRED > <!ELEMENT objectFactory (property*)> <!ATTLIST objectFactory type CDATA #REQUIRED > <!ELEMENT objectWrapperFactory (property*)> <!ATTLIST objectWrapperFactory type CDATA #REQUIRED > <!ELEMENT plugins (plugin+)> <!ELEMENT plugin (property*)> <!ATTLIST plugin interceptor CDATA #REQUIRED > <!ELEMENT environments (environment+)> <!ATTLIST environments default CDATA #REQUIRED > <!ELEMENT environment (transactionManager,dataSource)> <!ATTLIST environment id CDATA #REQUIRED > <!ELEMENT transactionManager (property*)> <!ATTLIST transactionManager type CDATA #REQUIRED > <!ELEMENT dataSource (property*)> <!ATTLIST dataSource type CDATA #REQUIRED > <!ELEMENT mappers (mapper*,package*)> <!ELEMENT mapper EMPTY> <!ATTLIST mapper resource CDATA #IMPLIED url CDATA #IMPLIED class CDATA #IMPLIED > <!ELEMENT package EMPTY> <!ATTLIST package name CDATA #REQUIRED >
mybatis-3-mapper.dtd:
<?xml version="1.0" encoding="UTF-8" ?> <!-- Copyright 2009-2011 The MyBatis Team Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!ELEMENT mapper (cache-ref | cache | resultMap* | parameterMap* | sql* | insert* | update* | delete* | select* )+> <!ATTLIST mapper xmlns:fo CDATA #IMPLIED namespace CDATA #IMPLIED > <!ELEMENT cache-ref EMPTY> <!ATTLIST cache-ref namespace CDATA #REQUIRED > <!ELEMENT cache (property*)> <!ATTLIST cache type CDATA #IMPLIED eviction CDATA #IMPLIED flushInterval CDATA #IMPLIED size CDATA #IMPLIED readOnly CDATA #IMPLIED > <!ELEMENT parameterMap (parameter+)?> <!ATTLIST parameterMap id CDATA #REQUIRED type CDATA #REQUIRED > <!ELEMENT parameter EMPTY> <!ATTLIST parameter property CDATA #REQUIRED javaType CDATA #IMPLIED jdbcType CDATA #IMPLIED mode (IN | OUT | INOUT) #IMPLIED resultMap CDATA #IMPLIED scale CDATA #IMPLIED typeHandler CDATA #IMPLIED > <!ELEMENT resultMap (constructor?,id*,result*,association*,collection*, discriminator?)> <!ATTLIST resultMap id CDATA #REQUIRED type CDATA #REQUIRED extends CDATA #IMPLIED autoMapping (true|false) #IMPLIED > <!ELEMENT constructor (idArg*,arg*)> <!ELEMENT id EMPTY> <!ATTLIST id property CDATA #IMPLIED javaType CDATA #IMPLIED column CDATA #IMPLIED jdbcType CDATA #IMPLIED typeHandler CDATA #IMPLIED > <!ELEMENT result EMPTY> <!ATTLIST result property CDATA #IMPLIED javaType CDATA #IMPLIED column CDATA #IMPLIED jdbcType CDATA #IMPLIED typeHandler CDATA #IMPLIED > <!ELEMENT idArg EMPTY> <!ATTLIST idArg javaType CDATA #IMPLIED column CDATA #IMPLIED jdbcType CDATA #IMPLIED typeHandler CDATA #IMPLIED select CDATA #IMPLIED resultMap CDATA #IMPLIED > <!ELEMENT arg EMPTY> <!ATTLIST arg javaType CDATA #IMPLIED column CDATA #IMPLIED jdbcType CDATA #IMPLIED typeHandler CDATA #IMPLIED select CDATA #IMPLIED resultMap CDATA #IMPLIED > <!ELEMENT collection (constructor?,id*,result*,association*,collection*, discriminator?)> <!ATTLIST collection property CDATA #REQUIRED column CDATA #IMPLIED javaType CDATA #IMPLIED ofType CDATA #IMPLIED jdbcType CDATA #IMPLIED select CDATA #IMPLIED resultMap CDATA #IMPLIED typeHandler CDATA #IMPLIED notNullColumn CDATA #IMPLIED columnPrefix CDATA #IMPLIED > <!ELEMENT association (constructor?,id*,result*,association*,collection*, discriminator?)> <!ATTLIST association property CDATA #REQUIRED column CDATA #IMPLIED javaType CDATA #IMPLIED jdbcType CDATA #IMPLIED select CDATA #IMPLIED resultMap CDATA #IMPLIED typeHandler CDATA #IMPLIED notNullColumn CDATA #IMPLIED columnPrefix CDATA #IMPLIED > <!ELEMENT discriminator (case+)> <!ATTLIST discriminator column CDATA #IMPLIED javaType CDATA #REQUIRED jdbcType CDATA #IMPLIED typeHandler CDATA #IMPLIED > <!ELEMENT case (constructor?,id*,result*,association*,collection*, discriminator?)> <!ATTLIST case value CDATA #REQUIRED resultMap CDATA #IMPLIED resultType CDATA #IMPLIED > <!ELEMENT property EMPTY> <!ATTLIST property name CDATA #REQUIRED value CDATA #REQUIRED > <!ELEMENT typeAlias EMPTY> <!ATTLIST typeAlias alias CDATA #REQUIRED type CDATA #REQUIRED > <!ELEMENT select (#PCDATA | include | trim | where | set | foreach | choose | if | bind)*> <!ATTLIST select id CDATA #REQUIRED parameterMap CDATA #IMPLIED parameterType CDATA #IMPLIED resultMap CDATA #IMPLIED resultType CDATA #IMPLIED resultSetType (FORWARD_ONLY | SCROLL_INSENSITIVE | SCROLL_SENSITIVE) #IMPLIED statementType (STATEMENT|PREPARED|CALLABLE) #IMPLIED fetchSize CDATA #IMPLIED timeout CDATA #IMPLIED flushCache (true|false) #IMPLIED useCache (true|false) #IMPLIED databaseId CDATA #IMPLIED lang CDATA #IMPLIED resultOrdered (true|false) #IMPLIED > <!ELEMENT insert (#PCDATA | selectKey | include | trim | where | set | foreach | choose | if | bind)*> <!ATTLIST insert id CDATA #REQUIRED parameterMap CDATA #IMPLIED parameterType CDATA #IMPLIED timeout CDATA #IMPLIED flushCache (true|false) #IMPLIED statementType (STATEMENT|PREPARED|CALLABLE) #IMPLIED keyProperty CDATA #IMPLIED useGeneratedKeys (true|false) #IMPLIED keyColumn CDATA #IMPLIED databaseId CDATA #IMPLIED lang CDATA #IMPLIED > <!ELEMENT selectKey (#PCDATA | include | trim | where | set | foreach | choose | if | bind)*> <!ATTLIST selectKey resultType CDATA #IMPLIED statementType (STATEMENT|PREPARED|CALLABLE) #IMPLIED keyProperty CDATA #IMPLIED order (BEFORE|AFTER) #IMPLIED databaseId CDATA #IMPLIED > <!ELEMENT update (#PCDATA | include | trim | where | set | foreach | choose | if | bind)*> <!ATTLIST update id CDATA #REQUIRED parameterMap CDATA #IMPLIED parameterType CDATA #IMPLIED timeout CDATA #IMPLIED flushCache (true|false) #IMPLIED statementType (STATEMENT|PREPARED|CALLABLE) #IMPLIED databaseId CDATA #IMPLIED lang CDATA #IMPLIED > <!ELEMENT delete (#PCDATA | include | trim | where | set | foreach | choose | if | bind)*> <!ATTLIST delete id CDATA #REQUIRED parameterMap CDATA #IMPLIED parameterType CDATA #IMPLIED timeout CDATA #IMPLIED flushCache (true|false) #IMPLIED statementType (STATEMENT|PREPARED|CALLABLE) #IMPLIED databaseId CDATA #IMPLIED lang CDATA #IMPLIED > <!-- Dynamic --> <!ELEMENT include EMPTY> <!ATTLIST include refid CDATA #REQUIRED > <!ELEMENT bind EMPTY> <!ATTLIST bind name CDATA #REQUIRED value CDATA #REQUIRED > <!ELEMENT sql (#PCDATA | include | trim | where | set | foreach | choose | if)*> <!ATTLIST sql id CDATA #REQUIRED lang CDATA #IMPLIED databaseId CDATA #IMPLIED > <!ELEMENT trim (#PCDATA | include | trim | where | set | foreach | choose | if)*> <!ATTLIST trim prefix CDATA #IMPLIED prefixOverrides CDATA #IMPLIED suffix CDATA #IMPLIED suffixOverrides CDATA #IMPLIED > <!ELEMENT where (#PCDATA | include | trim | where | set | foreach | choose | if)*> <!ELEMENT set (#PCDATA | include | trim | where | set | foreach | choose | if)*> <!ELEMENT foreach (#PCDATA | include | trim | where | set | foreach | choose | if)*> <!ATTLIST foreach collection CDATA #REQUIRED item CDATA #IMPLIED index CDATA #IMPLIED open CDATA #IMPLIED close CDATA #IMPLIED separator CDATA #IMPLIED > <!ELEMENT choose (when* , otherwise?)> <!ELEMENT when (#PCDATA | include | trim | where | set | foreach | choose | if)*> <!ATTLIST when test CDATA #REQUIRED > <!ELEMENT otherwise (#PCDATA | include | trim | where | set | foreach | choose | if)*> <!ELEMENT if (#PCDATA | include | trim | where | set | foreach | choose | if)*> <!ATTLIST if test CDATA #REQUIRED >
以上基本就完成了mybatis的封装。
接下来看看怎么调用:
this.mybatisDao.getObjectPage("userNameSpace.getUserList",paramMap, new RowBounds(NumberUtils.toInt(start), NumberUtils.toInt(limit)));
在配置文件里的mapper路径下回扫描你的Mapper文件
自定义SQL:(user.xml)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "../../../../../mybatis/mybatis-3-mapper.dtd"> <mapper namespace="userNameSpace"> <select id="getUserList" parameterType="java.util.Map" resultType="java.util.Map"> SELECT * from User </select> </mapper>