1. 程式人生 > >一個很好的MyBatis入門示例程式

一個很好的MyBatis入門示例程式

說明:

1,本文采用的Mybatis框架版本為: mybatis-3.0.4.jar

2,以持久化一個簡單的User bean為例

User實體類的程式碼如下:
package bean; 
  
public class User { 
    private String name; 
    private Integer age; 
    
    public String getName() { 
       return name; 
    } 
    public void setName(String name) { 
       this.name = name; 
    } 
    public Integer getAge() { 
       return age; 
    } 
    public void setAge(Integer age) { 
       this.age = age; 
    } 
    public User(String name, Integer age) { 
       super(); 
       this.name = name; 
       this.age = age; 
    } 
    
    public User() { 
       super(); 
    }  //必須要有這個無參構造方法,不然根據UserMapper.xml中的配置,在查詢資料庫時,將不能反射構造出User例項 

User實體的對映器取名為UserMapper(介面),其程式碼如下

package Mapper; 
import bean.User; 
  
public interface UserMapper { 
    public void insertUser(User user); 
    public User getUser(String name); 
} 

注意,該介面類似於Hibernate中的DAO層介面,唯一不同的是,MyBatis中,只宣告該介面就可以,不需要去實現.

UserMapper對映器對應的配置檔案如下(相當於Hibernate中的User.hbm.xml,當然這裡面不是屬性對映欄位,而是直接是對映器中各種方法對應的sql語句):

<?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="Mapper.UserMapper"> 
<!-- 這裡namespace必須是UserMapper介面的路徑,不然要執行的時候要報錯 “is not known to the MapperRegistry”--> 
    <insert id="insertUser" parameterType="User"> 
       insert into vincent_user(name,age) values(#{name},#{age}) 
       <!-- 這裡sql結尾不能加分號,否則報“ORA-00911”的錯誤 --> 
    </insert> 
 
    <!-- 這裡的id必須和UserMapper介面中的介面方法名相同,不然執行的時候也要報錯 --> 
    <select id="getUser" resultType="User" parameterType="java.lang.String"> 
        select * from vincent_user where name=#{name} 
    </select> 
</mapper> 
MyBatis的配置檔案這裡取名為mybatis-config.xml其配置程式碼如下(相當與Hibernatehibernate.cfg.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> 
    <settings> 
        <!-- changes from the defaults for testing --> 
        <setting name="cacheEnabled" value="false" /> 
        <setting name="useGeneratedKeys" value="true" /> 
        <setting name="defaultExecutorType" value="REUSE" /> 
    </settings> 
    <typeAliases> 
       <typeAlias alias="User" type="bean.User"/> 
    </typeAliases> 
    <environments default="development"> 
       <environment id="development"> 
           <transactionManager type="jdbc"/> 
           <dataSource type="POOLED"> 
              <property name="driver" value="oracle.jdbc.driver.OracleDriver"/> 
              <property name="url" value="jdbc:oracle:thin:@192.168.56.201:1521:system"/> 
              <property name="username" value="vincent"/> 
              <property name="password" value="1234"/> 
           </dataSource> 
       </environment> 
    </environments> 
    <mappers> 
        <mapper resource="resource/UserMapper.xml" /> 
    </mappers> 
</configuration> 
載入配置檔案得到sqlSessionFactory的工具類
package Util; 
  
import java.io.IOException; 
import java.io.Reader; 
  
import org.apache.ibatis.io.Resources; 
import org.apache.ibatis.session.SqlSessionFactory; 
import org.apache.ibatis.session.SqlSessionFactoryBuilder; 
  
public class MyBatisUtil  { 
    private  final static SqlSessionFactory sqlSessionFactory; 
    static { 
       String resource = "resource/mybatis-config.xml"; 
       Reader reader = null; 
       try { 
           reader = Resources.getResourceAsReader(resource); 
       } catch (IOException e) { 
           System.out.println(e.getMessage()); 
           
       } 
       sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); 
    } 
    
    public static SqlSessionFactory getSqlSessionFactory() { 
       return sqlSessionFactory; 
    } 
} 
測試程式碼如下:
package TestMapper; 
import org.apache.ibatis.session.SqlSession; 
import org.apache.ibatis.session.SqlSessionFactory; 
import org.junit.Test; 
  
public class TestMapper { 
    static SqlSessionFactory sqlSessionFactory = null; 
    static { 
       sqlSessionFactory = MyBatisUtil.getSqlSessionFactory(); 
    } 
    
    @Test 
    public void testAdd() { 
       SqlSession sqlSession = sqlSessionFactory.openSession(); 
       try { 
           UserMapper userMapper = sqlSession.getMapper(UserMapper.class); 
           User user = new User("tom",new Integer(5)); 
           userMapper.insertUser(user); 
           sqlSession.commit();//這裡一定要提交,不然資料進不去資料庫中 
       } finally { 
           sqlSession.close(); 
       } 
    } 
    
    @Test 
    public void getUser() { 
       SqlSession sqlSession = sqlSessionFactory.openSession(); 
       try { 
           UserMapper userMapper = sqlSession.getMapper(UserMapper.class); 
           User user = userMapper.getUser("jun"); 
           System.out.println("name: "+user.getName()+"|age: "+user.getAge()); 
       } finally { 
           sqlSession.close(); 
       } 
    } 
  
}