标签:
从数据库中查询一条记录,演示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"/> <select id="getUserList" parameterClass="User" resultClass="User"> SELECT user_id AS userId ,user_name AS userName ,credits AS credits ,password AS password ,last_visit AS lastVisit ,last_ip AS lastIp FROM t_user <dynamic prepend="WHERE"> <isNotEmpty prepend="AND" property="userId"> user_id = #userId# </isNotEmpty> <isNotEmpty prepend="AND" property="userName"> user_name LIKE ‘%‘||#userName#||‘%‘ </isNotEmpty> </dynamic> </select> </sqlMap>
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; } }
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>
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); }
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; } }
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); } }
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>
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/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=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
标签:
原文地址:http://www.cnblogs.com/sherrykid/p/4604607.html