Java工程中使用Mybatis

2011年6月iBatis 更名为 MyBatis,从 iBatis 到 MyBatis,不只是名称上的变化,MyBatis 提供了更为强大的功能,同时并没有损失其易用性,相反,在很多地方都借助于 JDK 的泛型和注解特性进行了简化。所以你懂的,开始学习就从MyBatis吧.
 
例子使用MyBatis+MySQL实现一个用户表的查询,如下:
① 数据库 在MySQL中,test数据库下,简历user表,字段:id,name,password,建表语句略。 
②需导入的包 只有两个: mybatis-3.0.3.jar mysql-connector-java-5.1.16-bin.jar(JDBC包) 
③目录结构 采用最简单的结构,com.mybatis包下有且仅有四个文件 configuration.xml user.xml User.java Test.java 
④mybatis配置文件configuration.xml,
[html] 
  
  
  
      
          
      
      
      
          
              
              
                  
                  
                  
                  
              
          
      
      
      
          
      
  
  


 
⑤User表sql文件User.xml,
[html]  
  
  
  
  
      
      
      
      

  
 
⑥表结构文件User.java,
[java]  
package com.mybatis;  
public class User {  
    private int id;  
    private String name;  
    private String password;  
      
    public User(){}  
    public User(int id, String name) {  
        this.id = id;  
        this.name = name;  
    }  
      
    public int getId() {  
        return this.id;  
    }  
      
    public void setId(int id) {  
        this.id = id;  
    }  
      
    public String getName() {  
        return this.name;  
    }  
      
    public void setName(String name) {  
        this.name = name;  
    }  
      
    public String getPassword() {  
        return this.password;  
    }  
      
    public void setPassword(String password) {  
        this.password = password;  
    }  
      
    @Override  
    public String toString() {  
        return "User [id=" + this.id + ", name=" + this.name + ", password=" + this.password + "]";  
    }  
      
}  


 
⑦测试用例Test.java
[java]  
package com.mybatis;  
  
import java.io.IOException;  
import java.io.Reader;  
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;  
  
public class Test {  
    public static void main(String[] args) throws IOException {  
        String resource = "configuration.xml";  
        Reader reader = Resources.getResourceAsReader(resource);  
        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader);  
        SqlSession session = ssf.openSession();  
        try{  
            User user = session.selectOne("selectUser", "1");  
            System.out.println(user.getName());  
            System.out.println(user);  
            System.out.println("--------------分隔线---------------");  
          
            List users = session.selectList("selectUsers");  
            for(int i=0; i


你可能感兴趣的:(Mybatis)