mybatis 入門例子

單純mybatis例子

環境:myeclipse+tomcat+mysql

需要包:mysql-connector-java-5.0.8-bin.jar,mybatis-3.1.1.jar

主要類目錄結構:


需要建立類:

User.java:bean類,用於存儲數據,作爲持久性數據結構

UserMapper.java:接口類,注射方式,從數據庫讀取數據到相應接口

MyBatisUtil.java:工具類,主要通過session工程獲取session

TestMybatis:測試類,通過調用配置方式,獲取數據庫數據

需要建立xml配置文件:

mybatis-config.xml:總配置mybatis文件

User.xml:bean類對應xml文件,書寫各種sql語句來獲取數據


各文件內容:

1 mybatis-config.xml內容:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC   
    "-//mybatis.org//DTD Config 3.0//EN"  
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<!-- 定義的類的別名,同樣作爲引用,相當於一個持久化數據bean類 -->
	<typeAliases>
		<typeAlias alias="User" type="com.taikang.mybatis.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://10.136.16.161:3306/test"/>
				<property name="username" value="root"/>
				<property name="password" value="admin"/>
			</dataSource>
		</environment>
	</environments>
	
	<!-- bean數據實體類對應需要操作的xml配置文件 -->
	<mappers>
		<mapper resource="resources/mappers/User.xml"/>
	</mappers>
</configuration>

若服務器中有數據源配置,environments部分可以爲:

<environments default="development">
	<environment id="development">
		<transactionManager type="JDBC"/>
		<dataSource type="JNDI">
		    <property name="initial_context" value="java:/comp/env"/>
			<property name="data_source" value="jdbc/InsureDB"/>
		</dataSource>
	</environment>
</environments>
2 User.xml配置:

<?xml version="1.0" encoding="UTF-8" ?> 
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.taikang.mybatis.UserMapper">
	<!-- namespace必須是接口的路徑, username 爲User對象中 -->
	<select id="getUser" parameterType="String" resultType="User">
		select * from table1 where username = #{username}
	</select>
</mapper>

3 User的Bean類部分:
public class User
{
	private int id;
	private String username;
	private int age;
	private String addr;
	
	public User(){
		super();
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
。。。
}
4 UserMapper.java類:
//mybatis使用到的接口
public interface UserMapper {
//	public void insertUser(User user);
	public User getUser(String name);
	public String getAddr(String name);
}
5 MyBatisUtil:工具類
import java.io.IOException;
import java.io.Reader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.io.Resources;

public class MyBatisUtil 
{
	private static Log logger = LogFactory.getLog(MyBatisUtil.class);
	
	private static SqlSessionFactory factory;  
	//用於單個提交的session
	private static SqlSession sqlSession = null;
	/*
     *  讀取MyBatis配置文件,創建SqlSessionFactory  
     */
    public static SqlSessionFactory getFactory() throws Exception{
    	String resource = "mybatis-config.xml";  
    	Reader reader = null;
        try {  
        	//FileInputStream is = new FileInputStream(path);
        	//MyBatisTemplate temp = new MyBatisTemplate();
        	//String cl = temp.getPath();
            reader = Resources.getResourceAsReader(resource);  
            if(factory == null)
            	factory = new SqlSessionFactoryBuilder().build(reader);
            return factory;
        } catch (Exception e) {  
            logger.error("初始化MyBatis環境出錯:" + e.getMessage());
            throw e;
        }finally{  
        	try {  
        		if(reader != null)
        			reader.close();  
           	} catch (IOException e) {
           		logger.error("關閉MyBatis reader 出錯:" + e.getMessage());
           	}  
        } 
    }  
    /** 
     * 獲取SqlSession 
     * @return 
	 * @throws Exception 
     */  
    public static SqlSession getSqlSession() throws Exception{  
        if(sqlSession == null){  
        	//getFactory().getConfiguration().addMapper(FunctionDAO.class);
            sqlSession = getFactory().openSession();  
        }  
        //clearCache();
        return sqlSession;  
    }  
}
6 TestMybatis:應用類
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class TestMybatis {
//	static SqlSessionFactory sqlSessionFactory = null;
//	static{
//		sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();
//	}
	public static void getUser()
	{
		SqlSession sqlSession = null;
//		SqlSession sqlSession = sqlSessionFactory.openSession();
		try
		{
			sqlSession = MyBatisUtil.getSqlSession();
			UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
			User user = userMapper.getUser("feng");
			System.out.println("info:" + user.getUsername() + " " + user.getAge() + " " + user.getAddr());
		}catch(Exception e)
		{
			e.printStackTrace();
		}finally
		{
			sqlSession.close();
		}
	}
}
7 寫個main函數:MainTest
public class MainTest
{
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("start mybatis ...");
		TestMybatis.getUser();
		System.out.println("end mybatis ...");
	}
}
8 數據庫設計:



9 注意:
mybatis-config.xml文件和User.xml文件放在src的目錄下邊,在編譯的時候將文件拷貝到web/web-inf/classes文件夾下,程序讀取相對文件位置,
若放在文件目錄其他位置,可能因找不到文件而報錯




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章