从数据库中查询一条记录,演示Spring与iBatis的集成

1 编写sqlmaps与Domain对象

 <?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.domain.User"> <typeAlias alias="User" type="org.zln.domain.User"/> <parameterMap id="User-Par-Map" class="User">
<parameter property="userId" jdbcType="int"/>
<parameter property="userName" jdbcType="VARCHAR"/>
<parameter property="credits" jdbcType="int"/>
<parameter property="password" jdbcType="VARCHAR"/>
<parameter property="lastVisit" jdbcType="Date"/>
<parameter property="lastIp" jdbcType="VARCHAR"/>
</parameterMap>
<resultMap id="User-Res-Map" class="User">
<result property="userId" column="user_id"/>
<result property="userName" column="user_name"/>
<result property="credits" column="credits"/>
<result property="password" column="password"/>
<result property="lastVisit" column="last_visit"/>
<result property="lastIp" column="last_ip"/> </resultMap>
<sql id="select-user-list">
SELECT
user_id
,user_name
,credits
,password
,last_visit
,last_ip
FROM t_user
</sql>
<sql id="where-user-parameter">
<dynamic prepend="WHERE">
<isNotEmpty prepend="AND" property="userId">
user_id = #userId#
</isNotEmpty>
<isNotEmpty prepend="AND" property="userName">
user_name LIKE '%'||#userName#||'%'
</isNotEmpty>
</dynamic>
</sql>
<select id="getUserList" parameterMap="User-Par-Map" resultMap="User-Res-Map">
<include refid="select-user-list"/>
<include refid="where-user-parameter"/>
</select>
</sqlMap>

D:\GitHub\tools\JavaEEDevelop\Lesson8_Spring2_iBatis2_Demo1\src\org\zln\domain\sqlmaps\User.xml

package org.zln.domain;

import java.util.Date;

/**
* Created by sherry on 15-6-27.
*/
public class User {
private int userId;
private String userName;
private String password;
private int credits;
private String lastIp;
private Date lastVisit; @Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", credits=" + credits +
", lastIp='" + lastIp + '\'' +
", lastVisit=" + lastVisit +
'}';
} public int getUserId() {
return userId;
} public void setUserId(int userId) {
this.userId = userId;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public int getCredits() {
return credits;
} public void setCredits(int credits) {
this.credits = credits;
} public String getLastIp() {
return lastIp;
} public void setLastIp(String lastIp) {
this.lastIp = lastIp;
} public Date getLastVisit() {
return lastVisit;
} public void setLastVisit(Date lastVisit) {
this.lastVisit = lastVisit;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
}
}

/home/sherry/WorkPlace/git/tools/JavaEEDevelop/Lesson8_Spring2_iBatis2_Demo1/src/org/zln/domain/User.java

2 编写sqlmap配置文件

<?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>
<!--iBatis配置信息-->
<settings enhancementEnabled="true"
useStatementNamespaces="true"
cacheModelsEnabled="true"
lazyLoadingEnabled="true"/> <!-- 映射文件位置 -->
<sqlMap resource="org/zln/domain/sqlmaps/User.xml" />
</sqlMapConfig>

/home/sherry/WorkPlace/git/tools/JavaEEDevelop/Lesson8_Spring2_iBatis2_Demo1/src/sql-map-config.xml

3 编写Dao接口及其实现类

package org.zln.dao;

import org.zln.domain.User;

import java.util.List;

/**
* Created by sherry on 15-6-27.
*/
public interface UserDao { List<User> getUserList(User user);
}

/home/sherry/WorkPlace/git/tools/JavaEEDevelop/Lesson8_Spring2_iBatis2_Demo1/src/org/zln/dao/UserDao.java

package org.zln.dao.ibatis;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.zln.dao.UserDao;
import org.zln.domain.User; import java.util.List; /**
* Created by sherry on 15-6-27.
*/
public class UserDaoImpl extends SqlMapClientDaoSupport implements UserDao{
@Override
public List<User> getUserList(User user) {
List<User> users = getSqlMapClientTemplate().queryForList("org.zln.domain.User.getUserList", user);
return users;
}
}

/home/sherry/WorkPlace/git/tools/JavaEEDevelop/Lesson8_Spring2_iBatis2_Demo1/src/org/zln/dao/ibatis/UserDaoImpl.java

4 编写Service

package org.zln.service;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.zln.dao.UserDao;
import org.zln.domain.User; import javax.annotation.Resource;
import java.util.List; /**
* Created by sherry on 15-6-27.
*/
@Transactional(rollbackFor = Exception.class)
public class UserService {
@Resource
private UserDao userDao; @Transactional(propagation = Propagation.NOT_SUPPORTED)
public List<User> getUserList(User user){
return userDao.getUserList(user);
}
}

/home/sherry/WorkPlace/git/tools/JavaEEDevelop/Lesson8_Spring2_iBatis2_Demo1/src/org/zln/service/UserService.java

5 编写Spring配置文件

<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!--注解注入-->
<context:annotation-config/>
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean> <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocation" value="classpath:sql-map-config.xml" />
<property name="dataSource" ref="dataSource" />
</bean> <!--JDBC数据源事务管理器-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--使用注解配置事务-->
<tx:annotation-driven transaction-manager="txManager"/> <bean id="abstractDao" abstract="true">
<property name="sqlMapClient" ref="sqlMapClient" />
</bean> <bean id="userDao" parent="abstractDao" class="org.zln.dao.ibatis.UserDaoImpl" />
<bean id="userService" class="org.zln.service.UserService"/>
</beans>

/home/sherry/WorkPlace/git/tools/JavaEEDevelop/Lesson8_Spring2_iBatis2_Demo1/src/application.xml

6 编写测试类

package org.zln.service;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.zln.domain.User; import java.util.List; /**
* Created by sherry on 15-6-27.
*/
public class UserServiceTest { private static ApplicationContext applicationContext;
private static String[] CONFIG_FILES = {"application.xml"};
private UserService userService;
@BeforeClass
public static void setUpBeforeClass() throws Exception{
applicationContext = new ClassPathXmlApplicationContext(CONFIG_FILES);
} @Before
public void setUp() throws Exception {
userService = (UserService) applicationContext.getBean("userService");
} @Test
public void testGetUserList() throws Exception {
User user = new User();
user.setUserId(2);
List<User> userList = userService.getUserList(user);
userList.forEach(System.out::println);
}
}

/home/sherry/WorkPlace/git/tools/JavaEEDevelop/Lesson8_Spring2_iBatis2_Demo1/test/org/zln/service/UserServiceTest.java

其他

/home/sherry/WorkPlace/git/tools/JavaEEDevelop/Lesson8_Spring2_iBatis2_Demo1/src/jdbc.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/Lesson8_Spring2_Demo1?useUnicode=true&amp;characterEncoding=UTF-8
username=root
password=123456
initialSize=1
maxActive=500
maxIdle=2
minIdle= /home/sherry/WorkPlace/git/tools/JavaEEDevelop/Lesson8_Spring2_iBatis2_Demo1/src/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=20
## 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
#打印JdbcTemplate执行的SQL
log4j.logger.org.springframework.jdbc.core.JdbcTemplate=debug #hibernate 配置
#log4j.appender.stdout.Threshold=trace
log4j.category.org.hibernate.SQL=trace
log4j.category.org.hibernate.type=trace

Spring2集成iBatis2的更多相关文章

  1. spring帝国-开篇

    spring简介: spring是一个开源框架,spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Dev ...

  2. 多数据源问题--Spring+Ibatis 访问多个数据源(非分布式事务)

    有的时候,我在一个工程中需要访问两个以上的数据源,尤其是在系统集成的时候,以下是我在系统集成的时候遇到的情况,我的工程的架构是:spring2.0+ibatis2.0+struts1.2. 数据库是o ...

  3. spring开篇

    本文引用http://www.cnblogs.com/ityouknow/p/5292559.html spring简介: spring是一个开源框架,spring是于2003 年兴起的一个轻量级的J ...

  4. Struts1 Spring2 iBatis2 框架的集成

    这个是属于比较老的框架了,奈何现在公司用的产品就是如此,闲来就搭一个集成框架吧 依赖jar包 antlr-.jar aspectj-.jar aspectjrt.jar aspectjweaver-. ...

  5. Spring2.0集成Quartz1.5.2调度框架

    Quartz是个开放源码项目,提供了丰富的作业调度集.希望您在阅读完本文并看过代码演示后,可以把Quartz的基本特性应用到任何Java™应用程序中.现代的Web应用程序框架在范围和复杂性方面都有所发 ...

  6. Spring2.5与JDK8的集成问题

    Spring2.5不支持JDK8及其以上的版本,因为有一段校验JDK版本的代码,当JDK版本大于1.7之后,会识别成JDK1.4之前的.会报版本太低的错误. /* * Copyright 2002-2 ...

  7. 傅老师课堂:Java高级应用之Struts2+Spring2+Hibernate3大集成

    开篇一笑:一对情侣,非常恩爱,但男友喜欢说脏话,一天女友提出要带男友回家吃个饭,见见家长,千叮万嘱让男友别说脏话,男友在家憋了一晚上没说一句脏话,天气寒冷,到走的时候女友家长要出来送他们,男友客气的说 ...

  8. spring2.5

    1:IOC:控制反转,不再把依赖对象交给应用本身创建和维护,而是交给外部容器创建和维护.这样控制权由应用转移到外部容器.2:DI:依赖注入,在运行期,由外部容器动态的将依赖对象注入到组件中,可以通过构 ...

  9. ibatis集成Sqlite:小数据库也有大作用

    作者:Vinkn 来自http://www.cnblogs.com/Vinkn/ 一.简介 Ibatis简介: Ibatis是一个类似于Hibernate的数据库ORM(对象关系映射,通俗点就是将数据 ...

随机推荐

  1. jquery 添加和删除节点

    // 增加一个三和一节点 function addPanel() { // var newPanel = $('.my-panel').clone(true) var newPanel = $(&qu ...

  2. Android Studio项目中三种依赖的添加方式

    通常一个AS项目中的依赖关系有三种,一是本地依赖(主要是对本地的jar包),二是模块依赖,三是远程依赖:添加这些依赖的目的在于上我们想要在项目的某一个模块中使用其中的功能,比如okttp这个网络框架库 ...

  3. PNChart,简洁高效有动画效果的iOS图表库

    导入 pod导入相对简单,要手动导入这个库,先下载下来(https://github.com/kevinzhow/PNChart),解压后把PNChart文件夹拖入工程中 运行发现#import&qu ...

  4. iOS圆角view的Swift实现(利用Core Graphics绘制)

    iOS圆角view的Swift实现(利用Core Graphics绘制) 因为app的列表用用到了圆形图片的头像,所以去探究并思考了一下这个问题.首先这个问题有两个方向的解决方案: 把图片弄成圆形的. ...

  5. v-for的显示过滤/排序结果

    对于v-for列表渲染指令,项目中很常用的额,但是我们一般可能在从后端接口拿到数据的时候就把数据通过循环整理改造成自己想要的样子了.有时候可能对于不同的列表需求,还要在data里多造一份数据. 这种做 ...

  6. [优化]Steamroller-freecodecamp算法题目

    晚上在medium看到一篇关于找工作的文章,里面提到一个面试题目--flattening an array(扁平化数组).这我好像在哪看过!应该是freecodecamp里的算法某一题.翻了下博客记录 ...

  7. Docker自学纪实(二)Docker基本操作

    安装docker 以CentOS7为例: 安装:yum -y install docker 启动:systemctl start docker 设置开机自启:systemctl enable dock ...

  8. 汇编:实现C语言的 ||与&&运算

    ;C程序转汇编(或运算链接) DATAS SEGMENT a Dw b dw cc dw d dw m dw n dw string db dup(?) DATAS ends CODES SEGMEN ...

  9. php 删除指定扩展名文件

    <?php /** *@param $path文件夹绝对路径 $file_type待删除文件的后缀名 *return void */ function clearn_file($path, $f ...

  10. 详解 JavaScript 中 splice() 方法

    splice() 方法是一个比较少用的方法,但是功能确实很好,并且在我们 coding 的时候,经常有需要 splice() 方法,先介绍一下该方法. 在 JavaScript 中 splice() ...