`
bluemusic
  • 浏览: 48187 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

iBatis3 Note(三) : 初识Hello World (补充)

阅读更多

在上一篇的日志中讲到了iBatis HelloWorld。自己在写完以后发现有些问题

在FirstTest 类中的两个size的确是能显示出正确的记录数,但问题在于两个对象的属性无法取得

其实问题在于一个叫helloworld.map.xml的文件里需要做些修改

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD iBatis Mapper 3.0 //EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="basic.HelloWorld">
	<select id="getHelloworlds" 
			resultType="java.util.List" 
			resultMap="helloWorldMap">
		select hw_id, name, age from t_helloworld
	</select>
	<select id="getHelloworldsMapByHwId" 
			resultType="HelloWorld"
			resultMap="helloWorldMap"
			parameterType="int"
			statementType="PREPARED">
		select hw_id, name, age from t_helloworld where hw_id = #{hw_id}
	</select>
	<resultMap id="helloWorldMap" type="HelloWorld">
		<id property="hwId" column="hw_id"/>
		<result property="name" column="name"/>
		<result property="age" column="age"/>
	</resultMap>
</mapper>

 

 

在这里添加了个很重要的resultMap ,在这个之后我就能获得正确的值了

 

好了下面重新看下代码,为了节约时间写了个工具类

IBatisUtil.java

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;

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 org.apache.ibatis.transaction.Transaction;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

/**
 * ibatis工具类,仅用做测试
 * @author Charles King
 * IBatisUtil.class
 */
public class IBatisUtil {
	
	private static final String IBATIS_CONFIG_XML = "/ibatis-config.xml";
	private final static ThreadLocal<SqlSession> sessionThread = new ThreadLocal<SqlSession>();
	private final static ThreadLocal<Transaction> transactionThread = new ThreadLocal<Transaction>();
	private IBatisUtil(){
		
	}
	
	/**
	 * 获得已有sqlSession没有就创建
	 * @return
	 */
	public static SqlSession openSessionIfNotExist(){
		if(isSessionNotNull())
			return getSqlSession();
		return createNewSqlSession();
	}
	
	/**
	 * 关闭sqlSession
	 */
	public static void closeSqlSession(){
		if(isSessionNotNull()){
			getSqlSession().close();
		}
	}
	
	/**
	 * 创建新的sqlSession
	 * @return
	 */
	private static SqlSession createNewSqlSession(){
		String configXml = "basic" + IBATIS_CONFIG_XML;
		SqlSessionFactoryBuilder builder = null;
		SqlSessionFactory factory = null;
		SqlSession session = null;
		Reader config;
		try {
			builder = new SqlSessionFactoryBuilder();
			config = Resources.getResourceAsReader(configXml);
			factory = builder.build(config);
			session = factory.openSession();
			setSessionInThread(session);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return session;
	}
	
	public static Transaction getCurrentTransactionNotAutoCommit(){
		return getCurrentTransaction(false);
	}
	
	public static Transaction getCurrentTransaction(boolean autoCommit){
		//session为空,不需要transaction
		if(!isSessionNotNull()) return null;
		//session不为空
		Transaction t = getCurrentTransaction();
		//1. 已经有transaction
		if(t!=null) return t;
		//2. 没有transaction
		TransactionFactory factory = new JdbcTransactionFactory();
		t = factory.newTransaction(getSqlSession().getConnection(), autoCommit);
		setTxInThread(t);
		return t;
	}
	
	public static Transaction getCurrentTransactionWithNewSession(boolean autoCommit){
		openSessionIfNotExist();
		return getCurrentTransaction(autoCommit);
	}
	
	public static void rollback() throws SQLException{
		if(isTransactionNotNull()){
			getCurrentTransaction().rollback();
		}
	}
	
	public static void commit() throws IBatisException{
		if(isTransactionNotNull()){
			try {
				getCurrentTransaction().commit();
			} catch (SQLException e) {
				throw new IBatisException(e.getNextException());
			}
		}
	}
	
	public static void commitAndClose() throws IBatisException{
		try {
			commit();
			getCurrentTransaction().close();
		} catch (SQLException e) {
			throw new IBatisException(e.getNextException());
		}
		sessionThread.remove();
		transactionThread.remove();
	}
	
	/**
	 * 存入LocalThread
	 * @param session
	 */
	private static void setSessionInThread(SqlSession session){
		sessionThread.set(session);
	}
	
	/**
	 * 从LocalThread中获得sqlSession
	 * @return
	 */
	private static SqlSession getSqlSession() {
		return sessionThread.get();
	}
	
	/**
	 * 判断LocalThread中sqlSession是否为空
	 * @return
	 */
	private static boolean isSessionNotNull(){
		if(getSqlSession()==null) 
			return false;
		return true;
	}
	
	private static void setTxInThread(Transaction tx){
		transactionThread.set(tx);
	}
	
	private static Transaction getCurrentTransaction(){
		Transaction transaction = transactionThread.get();
		return transaction;
	}
	
	private static boolean isTransactionNotNull(){
		if(getCurrentTransaction() != null) return true;
		return false;
	}
	
	public static int insert(String statement, Object parameter) throws IBatisException{
		IBatisAssert.assertSqlSessionNotNull(getSqlSession());
		return getSqlSession().insert(statement, parameter);
	}
	
	public static int insert(String statement) throws IBatisException{
		IBatisAssert.assertSqlSessionNotNull(getSqlSession());
		return getSqlSession().insert(statement);
	}

	public static int update(String statement, Object parameter) throws IBatisException{
		IBatisAssert.assertSqlSessionNotNull(getSqlSession());
		return getSqlSession().update(statement, parameter);
	}
	
	public static int update(String statement) throws IBatisException{
		IBatisAssert.assertSqlSessionNotNull(getSqlSession());
		return getSqlSession().update(statement);
	}
	
}

 

 

引入自定义异常类

IBatisException.java

 

public class IBatisException extends Exception {
	
	private static final long serialVersionUID = -8341903249485894181L;

	public IBatisException(String errorMsg){
		super(errorMsg);
	}
	
	public IBatisException(Exception e) {
		super(e);
	}
	
	public IBatisException(Throwable t) {
		super(t);
	}
	
}

 

 

之后看下重新改过的测试类吧

FirstTest.java

 

import java.util.List;

import util.IBatisException;
import util.IBatisManager;
import util.IBatisUtil;

public class FirstTest {
	
	public static void main(String[] args) throws IBatisException {
		IBatisUtil.getCurrentTransactionWithNewSession(false);
		IBatisManager<HelloWorld> manager = null;
		
		List<HelloWorld> list = null;
		HelloWorld helloworld = null;
		try {
			manager = new IBatisManager<HelloWorld>();
			
			
			list = manager.selectList("getHelloworlds");
			System.out.println(list.size());
			System.out.println(manager.selectList("getHelloworlds").get(0));
			
			helloworld = manager.selectOne("getHelloworldsMapByHwId", 1);
			System.out.println(helloworld.toString());
			
			
		} finally {
			IBatisUtil.commitAndClose();
		}
	}
	
}

 

 

同样复下HelloWorld.java

 

import java.io.Serializable;

@SuppressWarnings("serial")
public class HelloWorld implements Serializable {
	
	private Integer hwId;
	private String name;
	private Integer age;
	//setters & getters...
	
	@Override
	public String toString() {
		String str = "hw_id:" + hwId + "\n"
		           + "name: " + name + "\n"
		           + "age:  " + age +"\n";
		return str;
	}
}

 

 

 

0
0
分享到:
评论
2 楼 zhou_1985_liang 2011-11-30  
IBatisAssert是什么类?发出来看看
1 楼 qq123zhz 2010-08-17  
不错,最近也在用ibatis3

相关推荐

Global site tag (gtag.js) - Google Analytics