Spring2集成iBatis2
从数据库中查询一条记录,演示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&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的更多相关文章
- spring帝国-开篇
spring简介: spring是一个开源框架,spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Dev ...
- 多数据源问题--Spring+Ibatis 访问多个数据源(非分布式事务)
有的时候,我在一个工程中需要访问两个以上的数据源,尤其是在系统集成的时候,以下是我在系统集成的时候遇到的情况,我的工程的架构是:spring2.0+ibatis2.0+struts1.2. 数据库是o ...
- spring开篇
本文引用http://www.cnblogs.com/ityouknow/p/5292559.html spring简介: spring是一个开源框架,spring是于2003 年兴起的一个轻量级的J ...
- Struts1 Spring2 iBatis2 框架的集成
这个是属于比较老的框架了,奈何现在公司用的产品就是如此,闲来就搭一个集成框架吧 依赖jar包 antlr-.jar aspectj-.jar aspectjrt.jar aspectjweaver-. ...
- Spring2.0集成Quartz1.5.2调度框架
Quartz是个开放源码项目,提供了丰富的作业调度集.希望您在阅读完本文并看过代码演示后,可以把Quartz的基本特性应用到任何Java™应用程序中.现代的Web应用程序框架在范围和复杂性方面都有所发 ...
- Spring2.5与JDK8的集成问题
Spring2.5不支持JDK8及其以上的版本,因为有一段校验JDK版本的代码,当JDK版本大于1.7之后,会识别成JDK1.4之前的.会报版本太低的错误. /* * Copyright 2002-2 ...
- 傅老师课堂:Java高级应用之Struts2+Spring2+Hibernate3大集成
开篇一笑:一对情侣,非常恩爱,但男友喜欢说脏话,一天女友提出要带男友回家吃个饭,见见家长,千叮万嘱让男友别说脏话,男友在家憋了一晚上没说一句脏话,天气寒冷,到走的时候女友家长要出来送他们,男友客气的说 ...
- spring2.5
1:IOC:控制反转,不再把依赖对象交给应用本身创建和维护,而是交给外部容器创建和维护.这样控制权由应用转移到外部容器.2:DI:依赖注入,在运行期,由外部容器动态的将依赖对象注入到组件中,可以通过构 ...
- ibatis集成Sqlite:小数据库也有大作用
作者:Vinkn 来自http://www.cnblogs.com/Vinkn/ 一.简介 Ibatis简介: Ibatis是一个类似于Hibernate的数据库ORM(对象关系映射,通俗点就是将数据 ...
随机推荐
- 前端JavaScript之ECMA
1.JavaScript基础 2.语法规则 3 常用内置对象 4 函数 5 伪数组 6.异常处理 1.1 web前端分为三层 HTML:从语义的角度,描述页面结构 CSS:从审美的角度,描述样式(美化 ...
- 用纯css改变默认的radio和checkbox的样式
利用css的label的伪类(::before)代替checkbox和radio效果: 优点:需要图片来调整选中前和选中后的样式,纯css搞定 缺点:兼容性,IE8以下不支持 在线例子: css改变默 ...
- .net core自定义特性操作
最近移植之前写的几个类,发现特性操作发生了一些改变. 直接看代码,建立表和字段特性类,添加一个用户表,设置好特性. using System; namespace TestDemo { /// < ...
- java 基础词汇 必须 第九天
Collection 集合 List 列表集合 Set 不重复集合 Linked 链表 Vector 线程安全集合 Hash 哈希值 tree 树型结构 Map 键值对集合 add 增加 remove ...
- HDU.2561 第二小整数(water)
题目来源:2561 题意分析:找出一堆数中第二小的整数,和题目说的一样 我的思路:冒泡或者sort()一下就ok了,但是我因为没看到多个测试用例还是吃了几记WA . ┭┮﹏┭┮ 完整代码: #incl ...
- Ubuntu安装MySQL及使用Xshell连接MySQL出现的问题(2003-Can't connect to MySql server及1045错误)
不管在什么地方,什么时候,学习是快速提升自己的能力的一种体现!!!!!!!!!!! 以下所有的命令都是在root用户下操作(如果还没有设置root密码)如下: 安装好Ubuntu系统之后,打开终端先设 ...
- Windows下MySQL数据库的安装与关闭开机自启动
我在学习java,安装数据库时找了很多教程,现在在这里总结一下我安装数据库的过程,我安装的是mysql-5.6.42-winx64版本的. 数据官方下载地址:https://dev.mysql.com ...
- 如何设置 html 中 select 标签不可编辑、只读
转载自: https://blog.csdn.net/hjm4702192/article/details/33729767 1. <select style="width:195px ...
- http协议组成(请求状态码)
http请求由:请求行:消息报头:请求正文组成 //请求行 Request URL: http://172.32.4.33:8080/operation/v2/autoServer/queryAuto ...
- php 微信公众号图文消息回复的实现 与access_token
//代码如下 <?phpclass IndexAction extends Action { public function __construct(){ } public function i ...