当前位置:首页 » 数据仓库 » mybatis数据库方言
扩展阅读
webinf下怎么引入js 2023-08-31 21:54:13
堡垒机怎么打开web 2023-08-31 21:54:11

mybatis数据库方言

发布时间: 2022-08-26 18:26:04

Ⅰ MyBatis如何连接数据库

通过配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 开启注解扫描 -->
<context:component-scan base-package="com.ijava.springmvc."/>
<!-- 加载配置文件 --> <!-- placeholder 占位符 -->
<context:property-placeholder location="classpath:resources/db.properties"/>

<!-- 数据库连接池 -->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>

<!-- 创建对象 -->
<bean id="userDao" class="com.ijava.springmvc..UserDaoImpl"></bean>
<bean id="userService" class="com.ijava.springmvc.service.UserServiceImpl"></bean>
<bean class="org.springframework.jdbc.core.JdbcTemplate">

<property name="dataSource" ref="datasource"></property>
</bean>
</beans>

Ⅱ spring mvc中的mybatis怎么使用

spring mvc+myBatis配置详解
一、spring mvc
Spring框架(框架即:编程注解+xml配置的方式)MVC是Spring框架的一大特征,Spring框架有三大特征(IOC(依赖注入),AOP(面向切面),MVC(建模M-视图V-控制器C)。框架一般用于团队开发,使用分层的方式使每个人完成不同的模块,然后再组合在一起,使完成项目。
以下是Spring mvc具有的能加速开发的功能列表:
Spring mvc中提供了一个DispatchServlet,无需额外开发Spring mvc中使用基于xml的配置文件,可以编辑,而无需重新编译应用程序Spring mvc实例化控制器,并根据用户输入来构造Bean。
Spring mvc可以自动绑定用户输入,并正确的转换数据类型。例如,Spring mvc能自动解析字符串,并设置float或decimal类型的属性.
Spring mvc可以校验用户输入,若校验不通过,则重定向回输入表单。输入校验是可选的,支持编程方式以及声明。关于这一点,Spring mvc内置了常见的校验器Spring mvc是Spring框架的一部分,可以利用Spring提供的其他能力。
Spring mvc支持国际化和本地化。支持根据用户区域显示多国语言Spring mvc支持多种视图技术。最常见的JSP技术以及其他技术包括Velocity和FreeMarker.
配置spring mvc
1、导入Spring需要的jar 包
2、配置spring-mvc.xml
复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="springframework/schema/beans"xmlns:xsi="w3/2001/XMLSchema-instance"xmlns:context="springframework/schema/context"xmlns:jdbc="springframework/schema/jdbc"xmlns:jee="springframework/schema/jee"xmlns:tx="springframework/schema/tx"xmlns:aop="springframework/schema/aop"xmlns:mvc="springframework/schema/mvc"xmlns:util="springframework/schema/util"xmlns:jpa="springframework/schema/data/jpa"xsi:schemaLocation="springframework/schema/beans springframework/schema/beans/spring-beans-3.2.xswww.66298899.comrk/schema/context springframework/schema/context/spring-context-3.2.xswww.66298899.comrk/schema/jdbc springframework/schema/jdbc/spring-jdbc-3.2.xswww.66298899.comrk/schema/jee springframework/schema/jee/spring-jee-3.2.xswww.66298899.comrk/schema/tx springframework/schema/tx/spring-tx-3.2.xswww.66298899.comrk/schema/data/jpa springframework/schema/data/jpa/spring-jpa-1.3.xswww.66298899.comrk/schema/aop springframework/schema/aop/spring-aop-3.2.xswww.66298899.comrk/schema/mvc springframework/schema/mvc/spring-mvc-3.2.xswww.66298899.comrk/schema/util springframework/schema/util/spring-util-3.2.xsd">
<!-- HandlerMapping -->
<mvc:annotation-driven/>
开启spring mvc注解扫描,如果不基于注解: 该类需要继承 CommandController 或者 其他很多 参见 spring帮助.我用的是基于注解的,这样比较方便<!-- 扫描Controller,Service -->
<context:component-scan
base-package="com.包名"/>
开启组件扫描,请确保所有的控制器都在基本包下,并且不要制定一个太宽泛的基本包</beans>
复制代码
补充:
第一个为开启spring mvc注解扫描,如果不基于注解: 该类需要继承 CommandController 或者 其他很多 参见 spring帮助.我用的是基于注解的,这样比较方便第二个为开启组件扫描Spring使用扫描机制来找到应用程序中所有基于注解的控制器类,为了能保证Spring你那个找到你的控制器,a.需要在Spring mvc中配置spring-contextb.在<context:component-scan base-package="com.包名"/>元素中指定控制器类的基本包基于此,在Controller中可以方便调用了,实例见最下方3.部署web.xmlDispatcherServlet作为Spring mvc框架中的一级控制器(前端控制器),是浏览器发送请求的入口该Servlet的全称是org.springframework.web.servlet.DispatcherServlet.
要使用这个Servlet,需要把他配置在部署描述符(web.xml),应用servlet和servlet-mapping元素如下:
相关解释:
1、servlet元素内的on-startup元素是可选的。if存在,表示它将在应用程序启动时就装在servlet并调用它的init方法。else,则在该servlet的第一个请求是加载。
2、Dispatcher Servlet将会使用spring mvc诸多默认组件。此外,初始化时,它会寻找一个在应用程序下的web-INF目录下 的配置文件,该配置文件的命名规则如下;servletName-servlet.xml其中servletName是在部署描述符中的Dispatcher Servlet的名字。如图所示,本例中的servlet-name为springmvc,则在初始化的时候会找到第二步配置的springmvc.xml文件.
3、当然springmvc.xml文件也可以放到应用程序目录中的任何地方,<init-param></init-param>元素就是为了实现这个功能的。
其中的<param-name>不用改,而<param-value>则包含配置文件的路劲。
补充一下:(1)Spring可以通过指定classpath*:与classpath:前缀加路径的方式从classpath加载文件,如bean的定义文件.
classpath*:的出现是为了从多个jar文件中加载相同的文件.
classpath:只能加载找到的第一个文件
(2)url-pattern的写法
1 三种写法
①完全匹配
<url-pattern>/test/list.do</url-pattern>
② 目录匹配
<url-pattern>/test/*</url-pattern>
③ 扩展名匹配
<url-pattern>*.do</url-pattern>
2 注意事项
容器会首先查找完全匹配,如果找不到,再查找目录匹配,如果也找不到,就查找扩展名匹配。
如果一个请求匹配多个“目录匹配”,容器会选择最长的匹配。
定义”/*.action”这样一个看起来很正常的匹配会报错?因为这个匹配即属于路径映射,也属于扩展映射,导致容器无法判断。
“/” 是用来定义default servlet映射的。
*.do它不是一个文件,并没有一个真正的.do文件存在,只是一个servlet映射.意思是URL里一切以.do结尾的URL都驱动servlet里设置的那个类;而*则是所有请求都交由servlet里设置的那个类处理!
二、MyBatis的配置和使用
Spring与MyBatis结合,主要是由Spring管理数据库访问组件Dao,数据库访问组件主要是基于MyBatis实现,在Spring环境中使用MyBatis实现数据库访问组件过程是:首先需要引入一个Spring和MyBatis整合的开发包 mybatis-spring-1.2.2.jar。在Spring配置中定义sqlSessionFactoryBean,等价于SqlSessionFactory放入Spring容器管理。(不需要开发者利用手工创建SqlSessionFactory对象,需要开发者定义式注入连接信息和SQL定义的XML信息)在Spring配置中定义MapperFactoryBean,可以根据指定的Mapper接口生成一个Mapper实现类接口。需引入引入开发包:spring ioc,spring aop,dbcp,mybatis,驱动,mybatis-spring.jar。添加Spring框架的配置文件主要有applicationContext.xml,根据user表编写实体类User,编写UserMapper.xml(定义SQL语句),并且编写UserMapper接口(与UserMapper.xml映射),在applicationContext.xml中配置组件SqlSessionFactoryBean,Mapper FactoryBean。最后测试MapperFactoryBean生成的UserMapperDao实例。
MyBatis的两个特点:
1.MyBatis采用SQL与Entity映射,对JDBC封装程度较轻2.MyBatis自己写SQL,更具有灵活性配置MyBatis
(1)导入jar包
(2)创建数据库
(3)添加MyBatis.xml配置文件
复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="springframework/schema/beans"xmlns:xsi="w3/2001/XMLSchema-instance"xmlns:context="springframework/schema/context"xmlns:jdbc="springframework/schema/jdbc"xmlns:jee="springframework/schema/jee"xmlns:tx="springframework/schema/tx"xmlns:aop="springframework/schema/aop"xmlns:mvc="springframework/schema/mvc"xmlns:util="springframework/schema/util"xmlns:jpa="springframework/schema/data/jpa"xsi:schemaLocation="springframework/schema/beans springframework/schema/beans/spring-beans-3.2.xswww.66298899.comrk/schema/context springframework/schema/context/spring-context-3.2.xswww.66298899.comrk/schema/jdbc springframework/schema/jdbc/spring-jdbc-3.2.xswww.66298899.comrk/schema/jee springframework/schema/jee/spring-jee-3.2.xswww.66298899.comrk/schema/tx springframework/schema/tx/spring-tx-3.2.xswww.66298899.comrk/schema/data/jpa springframework/schema/data/jpa/spring-jpa-1.3.xswww.66298899.comrk/schema/aop springframework/schema/aop/spring-aop-3.2.xswww.66298899.comrk/schema/mvc springframework/schema/mvc/spring-mvc-3.2.xswww.66298899.comrk/schema/util springframework/schema/util/spring-util-3.2.xsd">
<bean id="dbcp"
class="org.apachemons.dbcp.BasicDataSource">
<property name="username" value="****">
</property>
<property name="password" value="***">
</property>
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url"
value="jdbc:mysql:///cloud_note">
</property>
<!-- <property name="url" value="jdbc:mysql://localhost:3306/cloud_note?useUnicode=true&characterEncoding=utf-8"></property> -->
</bean>
<bean id="ssf"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dbcp">
</property>
<property name="mapperLocations"
value="classpath:com/niuniu/sql/*.xml">
</property>
</bean>
<bean id="mapperscanner"
class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactory" ref="ssf">
</property>
<property name="basePackage"
value="com.niuniu.">
</property>
</bean>
</beans>
复制代码
(4)定义表所对应的实体类,如下图所示
代码如下:
复制代码
package com.niuniu.entity;
import java.io.Serializable;
public class User implements Serializable {private String cn_user_id;private String cn_user_name;
private String cn_user_password;
private String cn_user_token;
private String cn_user_nick;
public String getCn_user_id() {
return cn_user_id;
}
public void setCn_user_id(String cnUserId) {cn_user_id = cnUserId;}
public String getCn_user_name() {
return cn_user_name;
}
public void setCn_user_name(String cnUserName) {cn_user_name = cnUserName;}
public String getCn_user_password() {
return cn_user_password;
}
public void setCn_user_password(String cnUserPassword) {cn_user_password = cnUserPassword;}
public String getCn_user_token() {
return cn_user_token;
}
public void setCn_user_token(String cnUserToken) {cn_user_token = cnUserToken;}
public String getCn_user_nick() {
return cn_user_nick;
}
public void setCn_user_nick(String cnUserNick) {cn_user_nick = cnUserNick;}
}
复制代码
(5)定义操作users表的sql映射文件UserMapping.xml复制代码<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache//DTD Mapper 3.0//EN""http://ibatis.apache/dtd/ibatis-3-mapper.dtd">
<mapper namespace="com.niuniu..UserDao">
<insert id="save" parameterType="com.niuniu.entity.User">
insert into cn_user(
cn_user_id,cn_user_name,
cn_user_password,cn_user_token,
cn_user_nick)
values(#{cn_user_id},#{cn_user_name},#{cn_user_password},#{cn_user_token},#{cn_user_nick})</insert>
<select id="findByName" parameterType="string"resultType="com.niuniu.entity.User">
select * from cn_user
where cn_user_name=#{name}
</select>
</mapper>
复制代码
(6)写Controller,进行测试。
复制代码
@Controller//将类名前加上该注解,当spring启动或者web服务启动 spring会自动扫描所有包(当然,这个可以设置,见上述Springmvc的配置)作用: 就是告诉服务器这个类是MVC中的C, 这个类可以接收用户请求、处理用户请求@RequestMapping("/note")//这个控制类里面可以有很多方法,哪个方法用来处理用户请求,就在那个方法前面 加 @RequestMapping(“/xxxxx请求路径”)public class LoadNoteDetailController {@Resource//直接使用@Resource注解一个域(field)同样是可能的。通过不暴露setter方法,代码愈发紧凑并且还提供了域不可修改的额外益处。
//正如下面将要证明的,@Resource注解甚至不需要一个显式的字符串值,在没有提供任何值的情况下,域名将被当作默认值。
//该方式被应用到setter方法的时候,默认名是从相应的属性衍生出来,换句话说,命名为'setDataSource'的方法被用来处理名为'dataSource'的属性。
private NoteService noteService;
@RequestMapping("/loaddetail.do")//映射到JSP的前台页面中ajax发布的请求,打开相应的页面↑@ResponseBody ↑public NoteResult execute(String noteId){ ↑NoteResult result=noteService.loadDetail(noteId); ↑return result;//当请求处理完毕后,返回值决定了该处理完毕后,用户将跳转到那个页面.这个很重要。service调util}
}
复制代码
知识补充:
@Resource
@Resource默认按照ByName自动注入,有两个重要的属性:name和type,而Spring将@Resource注解的name属性解析为bean的名字,而type属性 则解析为bean的类型。所以,如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既 不制定name也不制定type属性,这时将通过反射机制使用byName自动注入策略。
@ResponseBody
作用:
该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。
使用时机:
返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

Ⅲ 为什么springMVC和Mybatis逐渐流行起来了

springmvc与Spring框架完美对接,可以让开发者单纯面向mvc来编程,不需要考虑太多,而且取参和返回给前台的数据封装做的很好。mybatis就是持久化数据的时候能让数据库不受限于某一种方言,屏蔽了sql,数据库兼容很强大,效率和稳定性也很高.同时还便于后续维护

Ⅳ mybatis原理

MyBatis 的工作原理:读取 MyBatis 配置文件、加载映射文件、构造会话工厂、创建会话对象、Executor 执行器、输入参数映射、输出结果映射。


mybatis原理具体介绍如下:


1、读取 MyBatis 配置文件:


mybatis-config.xml 为 MyBatis 的全局配置文件,配置了 MyBatis 的运行环境等信息,例如数据库连接信息。


2、加载映射文件:


映射文件即 SQL 映射文件,该文件中配置了操作数据库的 SQL 语句,需要在 MyBatis 配置文件 mybatis-config.xml 中加载。mybatis-config.xml 文件可以加载多个映射文件,每个文件对应数据库中的一张表。


3、构造会话工厂:

通过 MyBatis 的环境等配置信息构建会话工厂 SqlSessionFactory。


4、创建会话对象:

由会话工厂创建 SqlSession 对象,该对象中包含了执行 SQL 语句的所有方法。


5、Executor 执行器:


MyBatis 底层定义了一个 Executor 接口来操作数据库,它将根据 SqlSession 传递的参数动态地生成需要执行的 SQL 语句,同时负责查询缓存的维护。



8、输出结果映射:


输出结果类型可以是 Map、 List 等集合类型,也可以是基本数据类型和 POJO 类型。输出结果映射过程类似于 JDBC 对结果集的解析过程。

Ⅳ springmvc mybatis怎么实现分页查询

1.封装分页Page类

package com.framework.common.page.impl;

import java.io.Serializable;

import com.framework.common.page.IPage;
/**
*
*
*
*/
public abstract class BasePage implements IPage, Serializable {

/**
*
*/
private static final long serialVersionUID = -3623448612757790359L;

public static int DEFAULT_PAGE_SIZE = 20;
private int pageSize = DEFAULT_PAGE_SIZE;
private int currentResult;
private int totalPage;
private int currentPage = 1;
private int totalCount = -1;

public BasePage(int currentPage, int pageSize, int totalCount) {
this.currentPage = currentPage;
this.pageSize = pageSize;
this.totalCount = totalCount;
}

public int getTotalCount() {
return this.totalCount;
}

public void setTotalCount(int totalCount) {
if (totalCount < 0) {
this.totalCount = 0;
return;
}
this.totalCount = totalCount;
}

public BasePage() {
}

public int getFirstResult() {
return (this.currentPage - 1) * this.pageSize;
}

public void setPageSize(int pageSize) {
if (pageSize < 0) {
this.pageSize = DEFAULT_PAGE_SIZE;
return;
}
this.pageSize = pageSize;
}

public int getTotalPage() {
if (this.totalPage <= 0) {
this.totalPage = (this.totalCount / this.pageSize);
if ((this.totalPage == 0) || (this.totalCount % this.pageSize != 0)) {
this.totalPage += 1;
}
}
return this.totalPage;
}

public int getPageSize() {
return this.pageSize;
}

public void setPageNo(int currentPage) {
this.currentPage = currentPage;
}

public int getPageNo() {
return this.currentPage;
}

public boolean isFirstPage() {
return this.currentPage <= 1;
}

public boolean isLastPage() {
return this.currentPage >= getTotalPage();
}

public int getNextPage() {
if (isLastPage()) {
return this.currentPage;
}
return this.currentPage + 1;
}

public int getCurrentResult() {
this.currentResult = ((getPageNo() - 1) * getPageSize());
if (this.currentResult < 0) {
this.currentResult = 0;
}
return this.currentResult;
}

public int getPrePage() {
if (isFirstPage()) {
return this.currentPage;
}
return this.currentPage - 1;
}


}package com.framework.common.page.impl;

import java.util.List;
/**
*
*
*
*/
public class Page extends BasePage {

/**
*
*/
private static final long serialVersionUID = -970177928709377315L;

public static ThreadLocal<Page> threadLocal = new ThreadLocal<Page>();

private List<?> data;

public Page() {
}

public Page(int currentPage, int pageSize, int totalCount) {
super(currentPage, pageSize, totalCount);
}

public Page(int currentPage, int pageSize, int totalCount, List<?> data) {
super(currentPage, pageSize, totalCount);
this.data = data;
}

public List<?> getData() {
return data;
}

public void setData(List<?> data) {
this.data = data;
}


}


2.封装分页插件

package com.framework.common.page.plugin;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

import javax.xml.bind.PropertyException;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
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.reflection.MetaObject;
import org.apache.ibatis.reflection.property.PropertyTokenizer;
import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;

import com.framework.common.page.impl.Page;
import com.framework.common.utils.ReflectUtil;
/**
*
*
*
*/
@Intercepts({ @org.apache.ibatis.plugin.Signature(type = org.apache.ibatis.executor.statement.StatementHandler.class, method = "prepare", args = { Connection.class }) })
public class PagePlugin implements Interceptor {

private String dialect = "";
private String pageSqlId = "";

@Override
public Object intercept(Invocation invocation) throws Throwable {
if (invocation.getTarget() instanceof RoutingStatementHandler) {
BaseStatementHandler delegate = (BaseStatementHandler) ReflectUtil
.getValueByFieldName(
(RoutingStatementHandler) invocation.getTarget(),
"delegate");
MappedStatement mappedStatement = (MappedStatement) ReflectUtil
.getValueByFieldName(delegate,
"mappedStatement");

Page page = Page.threadLocal.get();
if (page == null) {
page = new Page();
Page.threadLocal.set(page);
}

if (mappedStatement.getId().matches(".*(" + this.pageSqlId + ")$") && page.getPageSize() > 0) {
BoundSql boundSql = delegate.getBoundSql();
Object parameterObject = boundSql.getParameterObject();

String sql = boundSql.getSql();
String countSqlId = mappedStatement.getId().replaceAll(pageSqlId, "Count");
MappedStatement countMappedStatement = null;
if (mappedStatement.getConfiguration().hasStatement(countSqlId)) {
countMappedStatement = mappedStatement.getConfiguration().getMappedStatement(countSqlId);
}
String countSql = null;
if (countMappedStatement != null) {
countSql = countMappedStatement.getBoundSql(parameterObject).getSql();
} else {
countSql = "SELECT COUNT(1) FROM (" + sql + ") T_COUNT";
}

int totalCount = 0;
PreparedStatement countStmt = null;
ResultSet resultSet = null;
try {
Connection connection = (Connection) invocation.getArgs()[0];
countStmt = connection.prepareStatement(countSql);
BoundSql countBoundSql = new BoundSql(mappedStatement.getConfiguration(), countSql, boundSql.getParameterMappings(), parameterObject);

setParameters(countStmt, mappedStatement, countBoundSql, parameterObject);

resultSet = countStmt.executeQuery();
if(resultSet.next()) {
totalCount = resultSet.getInt(1);
}
} catch (Exception e) {
throw e;
} finally {
try {
if (resultSet != null) {
resultSet.close();
}
} finally {
if (countStmt != null) {
countStmt.close();
}
}
}

page.setTotalCount(totalCount);

ReflectUtil.setValueByFieldName(boundSql, "sql", generatePageSql(sql,page));
}
}

return invocation.proceed();
}


/**
* 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler
* @param ps
* @param mappedStatement
* @param boundSql
* @param parameterObject
* @throws SQLException
*/
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
* @param sql
* @param page
* @return
*/
private String generatePageSql(String sql,Page page){
if(page!=null && StringUtils.isNotBlank(dialect)){
StringBuffer pageSql = new StringBuffer();
if("mysql".equals(dialect)){
pageSql.append(sql);
pageSql.append(" LIMIT "+page.getCurrentResult()+","+page.getPageSize());
}else if("oracle".equals(dialect)){
pageSql.append("SELECT * FROM (SELECT TMP_TB.*,ROWNUM ROW_ID FROM (");
pageSql.append(sql);
pageSql.append(") AS TMP_TB WHERE ROWNUM <= ");
pageSql.append(page.getCurrentResult()+page.getPageSize());
pageSql.append(") WHERE ROW_ID > ");
pageSql.append(page.getCurrentResult());
}
return pageSql.toString();
}else{
return sql;
}
}

@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}

@Override
public void setProperties(Properties properties) {
try {
if (StringUtils.isEmpty(this.dialect = properties
.getProperty("dialect"))) {
throw new PropertyException("dialect property is not found!");
}
if (StringUtils.isEmpty(this.pageSqlId = properties
.getProperty("pageSqlId"))) {
throw new PropertyException("pageSqlId property is not found!");
}
} catch (PropertyException e) {
e.printStackTrace();
}
}

}

附上出处链接:http://www.jb51.net/article/71829.htm

Ⅵ mybatis标签问题疑惑,什么是sql dialect

: sql dialect是数据库方言,
不过mybatis应该不用配置方言吧,
一般是hibernate有这个配置埃

Ⅶ 用mybatis向数据库插入数据,空指针异常

mybatis不能向数据库里面插入数据原因可能是执行了插入动作,但是没有最终commit到数据库服务器导致。

mybatis插入数据的例子如下:
package com.mybatis.demo;
import java.io.Reader;
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 void addUser(){
User user = new User();
user.setId(4);
user.setUserAddress("人民广场");
user.setUserName("Birds");
user.setUserAge("102");
SqlSession session = sqlSessionFactory.openSession();
try{
IUserOperation userOperation = session.getMapper(IUserOperation.class);
session.commit();
System.out.println("当前增加的用户id为:"+user.getId());
}
finally{
session.close();
}
}
public static void main(String[] args) {
Test testUser = new Test();
testUser.addUser();
}
}
当执行到 testUser.addUser();后执行到session.commit();数据就会插入表。

Ⅷ mybatis标签问题疑惑,什么是sql dialect

sql dialect是数据库方言,不过mybatis应该不用配置方言吧,一般是hibernate有这个配置啊。