iBatis的基本使用
项目结构:
依赖jar:
数据库依赖:
CREATE TABLE `person` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 CREATE TABLE `user_account` (
`userid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(30) NOT NULL,
`password` varchar(30) NOT NULL,
`groupname` varchar(10) NOT NULL,
PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
INSERT INTO ssi.user_account (userid, username, password, groupname) VALUES (1, 'LMEADORS', 'PICKLE', 'EMPLOYEE');
INSERT INTO ssi.user_account (userid, username, password, groupname) VALUES (2, 'JDOE', 'TEST', 'EMPLOYEE');
数据库连接信息:db.properties
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ssi
username=root
password=
主配置文件:sqlMapConfig.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<properties resource="db.properties"/>
<!--iBatis配置信息-->
<settings enhancementEnabled="true"
useStatementNamespaces="true"
cacheModelsEnabled="true"
lazyLoadingEnabled="true"/> <!--事务管理器-->
<transactionManager type="JDBC">
<!--数据库连接信息-->
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="${driverClass}"/>
<property name="JDBC.ConnectionURL" value="${url}"/>
<property name="JDBC.Username" value="${username}"/>
<property name="JDBC.Password" value="${password}"/>
</dataSource>
</transactionManager>
<!-- 映射文件位置 -->
<sqlMap resource="org/zln/ibatis/sqlmaps/Person.xml" />
<sqlMap resource="org/zln/ibatis/sqlmaps/UserAccount.xml" />
</sqlMapConfig>
初始化配置文件
package org.zln.ibatis.utils; import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder; import java.io.IOException;
import java.io.Reader; /**
* Created by sherry on 000008/6/8 14:36.
*/
public class SqlMapUtils {
private static final String resource = "sqlMapConfig.xml";
public static SqlMapClient sqlMapClient = null; public static SqlMapClient getSqlMapClient() throws IOException {
Reader reader = Resources.getResourceAsReader(resource);
sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
return sqlMapClient;
}
}
映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap
PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-2.dtd"> <!-- 设置命名空间 -->
<sqlMap namespace="org.zln.ibatis.domain.UserAccount"> <typeAlias alias="UserAccount" type="org.zln.ibatis.domain.UserAccount"/> /*外部参数映射*/
<parameterMap id="fullUserAccountMapExport" class="UserAccount">
<parameter property="userid" jdbcType="INTEGER"/>
<parameter property="username" jdbcType="VARCHAR"/>
<parameter property="password" jdbcType="VARCHAR"/>
<parameter property="groupname" jdbcType="VARCHAR"/>
</parameterMap>
/*结果集映射*/
<resultMap id="UserAccountMap" class="UserAccount">
<result property="userid" column="userid"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
<result property="groupname" column="groupname"/>
<!--当查询tt的时候,会查询select-id对应的SQL,然后映射到JavaBean中的listColl,-->
<!--<result column="tt" property="listColl" select="select-id"/>-->
</resultMap> <select id="getUserAccountList" parameterClass="UserAccount" resultClass="UserAccount">
SELECT userid,username,password,groupname FROM user_account
<dynamic prepend="WHERE">
<isNotEmpty property="username" prepend="AND">
username LIKE '%'||#username#||'%'
</isNotEmpty>
<isNotEmpty property="password" prepend="AND">
password = #password#
</isNotEmpty>
<isNotEmpty property="groupname" prepend="AND">
groupname LIKE '%'||#groupname#||'%'
</isNotEmpty>
<!--循环标签-->
<iterate property="ids" open="(" close=")" conjunction=",">
userid = #userid#
</iterate>
</dynamic>
</select> <insert id="insertUserAccount" parameterClass="UserAccount">
INSERT INTO user_account (username,password,groupname) VALUES (#username#,#password#,#groupname#)
</insert>
/*使用外部映射*/
<insert id="insertUserAccount_1" parameterMap="fullUserAccountMapExport">
INSERT INTO user_account (username,password,groupname) VALUES (?,?,?)
</insert>
/*Oracle的序列使用演示*/
<!--<insert id="insertUserAccount_2" parameterMap="fullUserAccountMapExport">
<selectKey keyProperty="userid" resultClass="int">
SELECT nextVal(#序列#) FROM dual
</selectKey>
INSERT INTO user_account (userid,username,password,groupname) VALUES (?,?,?,?)
</insert>--> <update id="updateUserAccount" parameterClass="UserAccount">
UPDATE user_account set userid = #userid#
<dynamic>
<isNotEmpty prepend="," property="username">
username = #username#
</isNotEmpty>
<isNotEmpty prepend="," property="password">
password = #password#
</isNotEmpty>
<isNotEmpty prepend="," property="groupname">
groupname = #groupname#
</isNotEmpty>
</dynamic>
WHERE userid = #userid#
</update> <sql id="select-user_account-list">
SELECT userid,username,password,groupname FROM user_account
</sql>
<sql id="select-user_account-count">
SELECT COUNT(1) FROM user_account
</sql>
<sql id="where-user_account">
<![CDATA[
WHERE userid > #userid:INTEGER#
]]>
</sql>
<select id="selectUserAccountsAfterId" parameterClass="UserAccount" resultClass="UserAccount">
<include refid="select-user_account-list"/>
<include refid="where-user_account"/>
</select> /*调用存储过程演示*/
<!--<procedure id="callProDemo" parameterClass="string" resultClass="int">
{call product(?)}
</procedure>--> </sqlMap>
BaseDao.java
package org.zln.ibatis.dao.base; import com.ibatis.sqlmap.client.SqlMapClient;
import org.zln.ibatis.utils.SqlMapUtils; import java.io.IOException; /**
* Created by sherry on 000008/6/8 15:16.
*/
public class BaseDao {
public SqlMapClient sqlMapClient; {
try {
sqlMapClient = SqlMapUtils.getSqlMapClient();
} catch (IOException e) {
e.printStackTrace();
}
}
}
UserAccountDaoImpl.java
package org.zln.ibatis.dao.impl; import org.zln.ibatis.dao.UserAccountDao;
import org.zln.ibatis.dao.base.BaseDao;
import org.zln.ibatis.domain.UserAccount; import java.sql.SQLException;
import java.util.List;
import java.util.Map; /**
* Created by sherry on 000008/6/8 15:15.
*/
public class UserAccountDaoImpl extends BaseDao implements UserAccountDao { @Override
public List<UserAccount> getUserAccountList(UserAccount userAccount){
List<UserAccount> userAccounts = null;
try {
userAccounts = sqlMapClient.queryForList("org.zln.ibatis.domain.UserAccount.getUserAccountList",userAccount); //start test queryForMap
Map<String,UserAccount> map = sqlMapClient.queryForMap("org.zln.ibatis.domain.UserAccount.getUserAccountList",userAccount,"username");
System.out.println(map);
//end
} catch (SQLException e) {
e.printStackTrace();
}
return userAccounts;
} @Override
public List<UserAccount> getUserAccountListAfterId(UserAccount userAccount) {
List<UserAccount> userAccounts = null;
try {
userAccounts = sqlMapClient.queryForList("org.zln.ibatis.domain.UserAccount.selectUserAccountsAfterId",userAccount); } catch (SQLException e) {
e.printStackTrace();
}
return userAccounts;
} @Override
public void insertUserAccount(List<UserAccount> userAccounts) {
try {
/*批处理*/
sqlMapClient.startTransaction();
sqlMapClient.startBatch();
for (UserAccount userAccount:userAccounts){
sqlMapClient.insert("org.zln.ibatis.domain.UserAccount.insertUserAccount",userAccount);
}
sqlMapClient.executeBatch();
sqlMapClient.commitTransaction();
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
sqlMapClient.endTransaction();
} catch (SQLException e) {
e.printStackTrace();
}
}
} @Override
public void updateUserAccount(UserAccount userAccount) {
try {
sqlMapClient.update("org.zln.ibatis.domain.UserAccount.updateUserAccount",userAccount);
} catch (SQLException e) {
e.printStackTrace();
}
} }
日志配置文件:log4j.properties
## LOGGERS ##
#define a logger
#log4j.rootLogger=DEBUG,console,file
log4j.rootLogger=INFO,console
## APPENDERS ## log4j.appender.console=org.apache.log4j.ConsoleAppender
# define an appender named file, which is set to be a RollingFileAppender
log4j.appender.file=org.apache.log4j.RollingFileAppender
#set the log's size
log4j.appender.file.MaxFileSize=1000KB
log4j.appender.file.MaxBackupIndex=
## LAYOUTS ##
# assign a SimpleLayout to console appender
log4j.appender.console.layout=org.apache.log4j.SimpleLayout
# assign a PatternLayout to file appender
log4j.appender.file.layout=org.apache.log4j.PatternLayout
# For debug
# log4j.appender.file.layout.ConversionPattern=[%-5p][%t][%C][%d{yyyy-MM-dd HH:mm:ss}] %m%n
# For deployment
log4j.appender.file.layout.ConversionPattern=[%-5p][%d{yyyy-MM-dd HH:mm:ss}] %m%n
# show SQL Where ibatis run
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
iBatis的基本使用的更多相关文章
- 值得注意的ibatis动态sql语法格式
一.Ibatis常用动态sql语法,简单粗暴用一例子 <select id="iBatisSelectList" parameterClass="java.util ...
- org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): da.huying.usermanag ...
- [入门级] visual studio 2010 mvc4开发,用ibatis作为数据库访问媒介(一)
[入门级] visual studio 2010 mvc4开发,用ibatis作为数据库访问媒介(一) Date 周二 06 一月 2015 By 钟谢伟 Tags mvc4 / asp.net 示 ...
- Spring+ibatis动态管理数据源
Spring动态配置多数据源,即在大型应用中对数据进行切分,并且采用多个数据库实例进行管理,这样可以有效提高系统的水平伸缩性.而这样的方案就会不同于常见的单一数据实例的方案,这就要程序在运行时根据当时 ...
- iBatis.net 循环iterate,没有foreach
3.9.4. Iterate Element This tag will iterate over a collection and repeat the body content for each ...
- ibatis 轻松入门
1.总中的配置文件 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMapConfig ...
- IBatis.Net使用总结(四)-- IBatis 调用存储过程
IBatis 调用存储过程 http://www.cnblogs.com/jeffwongishandsome/archive/2010/01/10/1543219.html http://www.c ...
- MyBatis-Exception:org.apache.ibatis.exceptions.PersistenceException
错误信息如下: HTTP Status 500 - org.mybatis.spring.MyBatisSystemException: nested exception is org.apache. ...
- Exception:HTTP Status 500 - org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)
主要错误信息如下: HTTP Status 500 - org.apache.ibatis.binding.BindingException: Invalid bound statement (not ...
- ibatis 和 mybatis
ibatis 在daoImpl 层 继承 SqlMapClientDaoSupport 实现 dao 层的接口. this.getSqlMapClientTemplate().queryForObj ...
随机推荐
- jQuery 切换图片(图标)效果
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 富文本编辑器 wangEditor.js
1.引用 wangEditor 相关js 和 css 下载地址:https://files.cnblogs.com/files/kitty-blog/WangEditor.zip 3.页面: < ...
- css实现未知元素宽高垂直居中和水平居中的方法
第一种:display:table-cell的方式 .container { /*父级容器*/ display:table-cell; text-align:center; vertical-alig ...
- C#正则表达式Regex类的使用
C#中为正则表达式的使用提供了非常强大的功能,这就是Regex类.这个包包含于System.Text.RegularExpressions命名空间下面,而这个命名空间所在DLL基本上在所有的项目模板中 ...
- CPS---(Cyber-Physical Sytem,信息物理融合系统)
1.CPS定义 CPS是连接计算机虚拟世界与物理现实世界的系统.---We refer to systems that bridge the cyber-world of computing and ...
- (数据科学学习手札05)Python与R数据读入存出方式的总结与比较
在数据分析的过程中,外部数据的导入和数据的导出是非常关键的部分,而Python和R在这方面大同小异,且针对不同的包或模块,对应着不同的函数来完成这部分功能: Python 1.TXT文件 导入: 以某 ...
- lambda, 匿名函数, 变量,传参
lambda: # 无参数函数情况 def delete_one(): pass Button(otherFrame, text="删除", width=4, command=de ...
- 2.PostgreSQL安装详细步骤(windows)【转】
感谢 Junn9527 PostgreSQL安装:一.windows下安装过程安装介质:postgresql-9.1.3-1-windows.exe(46M),安装过程非常简单,过程如下:1.开始安装 ...
- stm32--FatFs移植(SPIFlash)
前言 硬件: 单片机:stm32f072CB,sram大小16k.(其他单片机只要sram>8k即可通用) SPIFlash:W25Q128FV,16Mbyte,单次擦除最小4k. 程序使用Ke ...
- Vuex实践
本文来自网易云社区 作者:刘凌阳 前言 2017年对于Vue注定是不平凡的一年.凭借着自身简介.轻量.快速等特点,Vue俨然成为最火的前端MVVM开发框架.随着Vue2.0的release,越来越多的 ...