Ⅰ 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有這個配置啊。