Spring2集成iBatis2

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

1 编写sqlmaps与Domain对象

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE sqlMap
 3         PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
 4         "http://www.ibatis.com/dtd/sql-map-2.dtd">
 5 
 6 <!-- 设置命名空间 -->
 7 <sqlMap namespace="org.zln.domain.User">
 8 
 9     <typeAlias alias="User" type="org.zln.domain.User"/>
10 
11     <parameterMap id="User-Par-Map" class="User">
12         <parameter property="userId" jdbcType="int"/>
13         <parameter property="userName" jdbcType="VARCHAR"/>
14         <parameter property="credits" jdbcType="int"/>
15         <parameter property="password" jdbcType="VARCHAR"/>
16         <parameter property="lastVisit" jdbcType="Date"/>
17         <parameter property="lastIp" jdbcType="VARCHAR"/>
18     </parameterMap>
19     <resultMap id="User-Res-Map" class="User">
20         <result property="userId" column="user_id"/>
21         <result property="userName" column="user_name"/>
22         <result property="credits" column="credits"/>
23         <result property="password" column="password"/>
24         <result property="lastVisit" column="last_visit"/>
25         <result property="lastIp" column="last_ip"/>
26 
27     </resultMap>
28     <sql id="select-user-list">
29         SELECT
30         user_id
31         ,user_name
32         ,credits
33         ,password
34         ,last_visit
35         ,last_ip
36         FROM t_user
37     </sql>
38     <sql id="where-user-parameter">
39         <dynamic prepend="WHERE">
40             <isNotEmpty prepend="AND" property="userId">
41                 user_id = #userId#
42             </isNotEmpty>
43             <isNotEmpty prepend="AND" property="userName">
44                 user_name LIKE '%'||#userName#||'%'
45             </isNotEmpty>
46         </dynamic>
47     </sql>
48     <select id="getUserList" parameterMap="User-Par-Map" resultMap="User-Res-Map">
49         <include refid="select-user-list"/>
50         <include refid="where-user-parameter"/>
51     </select>
52 </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=1



/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

 

posted @ 2015-06-27 20:23  csnmd  阅读(286)  评论(0编辑  收藏  举报