Ibatis3.x实例
说明:此文档和之前发布的Ibatis2.x实例时我学习时做的实例,测试都已通过,将实例拿出来与大家分享,共同学习。浏览实例的时候注意他们之间的异同,希望对你有所帮助。
一、SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-config.dtd"> <configuration> <!-- 配置资源文件 --> <properties resource="dbconfig.properties"> <property name="username" value="root"/><!-- 此处并配置的属性将替换dbconfig.properties中的属性 --> <property name="password" value="wuzhengfei"/> </properties> <!-- 改变Ibatis运行时的行为 --> <settings> <setting name="cacheEnabled" value="true" /><!-- 是否使用全局缓存 true|false true --> <setting name="lazyLoadingEnabled" value="true" /> <!-- 是否使用全局懒加载 true|false true --> <setting name="multipleResultSetsEnabled" value="true" /><!-- 是否允许返回多个结果集合(需要兼容的驱动) true|false true --> <setting name="useColumnLabel" value="true" /><!-- 使用列标签取代列名(不同驱动表现不同) true|false true --> <setting name="useGeneratedKeys" value="false" /><!-- 允许jdbc自动生成主键 true|false false --> <setting name="defaultExecutorType" value="SIMPLE" /><!-- 配置默认执行方式 SIMPLE|REUSE|BATCH --> <setting name="defaultStatementTimeout" value="25000" /><!-- 数据库超时时间 Any positive --> </settings> <typeAliases> <typeAlias type="com.beans.User" alias="user"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost/ibatis?useUnicode=true&characterEncoding=UTF-8" /> <property name="username" value="root"/> <property name="password" value="wuzhengfei"/> <property name="poolMaximumActiveConnections" value="10"/> <!-- 同一时间内最大连接数 默认10 --> <property name="poolMaximumIdleConnections" value="5"/><!--连接最大空闲数目 --> <property name="poolMaximumCheckoutTime" value="20000"/><!-- 连接被每个任务占用的最大时间 默认20000ms --> <property name="poolTimeToWait" value="20000"/><!-- 连接池中无可用连接时,线程的等待时间 默认20000ms --> <property name="poolPingQuery" value="NO"/><!-- 数据库连接状态检测语句,类似于ping的功能 默认NO PING QUERY SET --> <property name="poolPingEnabled" value="true"/><!-- 是否允许ping检测 默认false --> <property name="poolPingConnectionsNotUsedFor" value="0"/><!-- 对超过指定空闲时间的数据库连接进行状态监测 默认0 (必须在poolPingEnabled设置true情况下) --> </dataSource> </environment> <environment id="test"> <transactionManager type="JDBC" /> <dataSource type="JNDI"> <property name="driver" value=""/> <property name="url" value=""/> <property name="username" value=""/> <property name="password" value=""/> <property name="env.encoding" value="UTF8"/> <property name="initial_context" value=""/> <property name="data_source" value=""/><!-- JNDI数据库名称 --> </dataSource> </environment> </environments> <mappers> <mapper resource="com/beans/User.xml"/> <!-- 使用绝对路径 --> <!-- <mapper url="file:///.../AuthorMapper.xml"/> --> </mappers> </configuration>
二、实体:
2.1、User.java
package com.beans ; public class User { private long id ; private String username ; private String password ; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String toString(){ return "id: "+id+" username: "+username + " password: "+password ; } }
2.2、映射文件
User.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> <mapper namespace="user"> <insert id="addUser" parameterType="User"> insert into User(id, username, password) values(#{id}, #{username}, #{password}) </insert> <delete id="deleteUserById" parameterType="int" statementType="PREPARED"> delete from User where id = #{id} </delete> <sql id="userColumn">id, username, password</sql> <select id="findAllUsers" resultType="User"> select <include refid="userColumn"/> from User </select> <select id="findUserById" statementType="PREPARED" useCache="true" resultType="user"> select <include refid="userColumn"/> from User where id = #{id, javaType=long, jdbcType=BIGINT} </select> <select id="findUserByName" parameterType="string" resultType="User"> select * from User as u where u.username like CONCAT('%',#{username},'%') </select> <update id="updateUser" parameterType="User"> update User set username = #{username}, password = #{password} where id = #{id} </update> </mapper>
3、接口
UserDao.java
package com.dao; import java.util.List; import com.beans.User; public interface UserDao { /** * 插入User对象 * @param user * @return 插入成功的记录数 */ public int addUser(User user); /** * 根据Id删除User * @param id * @return 删除成功的记录数 */ public int deleteUserById(long id); /** * 查出所有的User对象 * @return */ public List<User> findAllUsers(); /** * 根据Id查找用户 * @param id * @return */ public User findUserById(long id); /** * 更新用户信息 * @param user * @return 更新的数据数目 */ public int update(User user); /** * 根据用户名查找User 模糊查询 * @param username * @return */ public List<User> findUserByName(String username); }
四、实现
UserDaoImpl.java
package com.dao.impl; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.beans.User; import com.dao.UserDao; public class UserDaoImpl implements UserDao { private static SqlSessionFactory sqlSessionFactory; static { try { // Properties props = Resources.getResourceAsProperties("dbConfig.properties"); Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); // sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader,"development"); //如果sqlMapCofig中没有引入dbConfig.properties文件时,可以使用这种方式引入 //sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader,props); reader.close(); } catch (IOException e) { e.printStackTrace(); } } public SqlSession getSqlSession(){ return sqlSessionFactory.openSession() ; } @Override public int addUser(User user) { int successNum =0 ; SqlSession sqlSession = getSqlSession(); try { successNum = sqlSession.insert("addUser", user); sqlSession.commit() ; }finally{ sqlSession.close() ; } return successNum ; } @Override public int deleteUserById(long id) { int successNum =0 ; SqlSession sqlSession = getSqlSession(); try { successNum = sqlSession.delete("deleteUserById", id); sqlSession.commit() ; }finally{ sqlSession.close() ; } return successNum; } @SuppressWarnings("unchecked") @Override public List<User> findAllUsers() { List<User> users = new ArrayList<User>(); SqlSession sqlSession = getSqlSession(); try { users = sqlSession.selectList("findAllUsers"); sqlSession.commit() ; } finally{ sqlSession.close() ; } return users; } @Override public User findUserById(long id) { User user = new User(); SqlSession sqlSession = getSqlSession(); try { user = (User) sqlSession.selectOne("findUserById", id); sqlSession.commit() ; }finally{ sqlSession.close() ; } return user; } @Override public List<User> findUserByName(String name) { List<User> users = new ArrayList<User>(); SqlSession sqlSession = getSqlSession(); try { users = sqlSession.selectList("findUserByName", name); sqlSession.commit() ; } finally{ sqlSession.close() ; } return users; } @Override public int update(User user) { int updateNumber = 0 ; SqlSession sqlSession = getSqlSession(); try { updateNumber = sqlSession.update("updateUser", user); sqlSession.commit() ; } finally{ sqlSession.close() ; } return updateNumber; } }
五、测试类:
UserDaoImplTester.java
package com.dao.impl; import java.util.List; import org.junit.Before; import org.junit.Test; import com.beans.User; import com.dao.UserDao; public class UserDaoImplTester { private UserDao userDao ; @Before public void setUp() throws Exception { userDao = new UserDaoImpl() ; } @Test public void testAddUser() { User user = new User(); user.setId(12); user.setPassword("XXXX"); user.setUsername("XXXX"); userDao.addUser(user); } @Test public void testDeleteUserById() { userDao.deleteUserById(10); } @Test public void testFindAllUsers() { List<User> users = userDao.findAllUsers(); for(User user : users){ System.out.println(user); } } @Test public void testFindUserById() { User user = userDao.findUserById(1); System.out.println(user); } @Test public void testFindUserByName() { List<User> users = userDao.findUserByName("w"); for(User user : users){ System.out.println(user); } } @Test public void testUpdate() { User user = userDao.findUserById(4); System.out.println(user); user.setUsername("海贼王"); user.setPassword("路飞"); userDao.update(user); user = userDao.findUserById(4); System.out.println(user); } }
六、日志文件:
为了方便大家查看sqlMap运行时到底使用的是什么Sql语句,此处将log4j.properties发出来,将此文件放在calsspath下后,运行时,控制台中将会打印出sql语句和出入的参数。
log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n 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,stdout
七、其他:
附件中是我找的的Ibatis3.x的资料,Ibatis3.x-reference-EN.pdf虽然是英文的,但是还是很好理解的,另外的是在网上看到的,也一起发出来,和大家分享。。。