mybatis 使用教程

阅读更多
  Myeclispe下mybatis generator的使用: http://donald-draper.iteye.com/blog/2309387
  MyBatis缓存介绍: http://www.cnblogs.com/xdp-gacl/p/4270403.html
  MyBatis 缓存机制深度解剖 / 自定义二级缓存: http://www.iteye.com/topic/1112327
深入浅出MyBatis-Configuration : http://blog.csdn.net/hupanfeng/article/details/9080545/
SqlSessionFactory初始化: http://donald-draper.iteye.com/admin/blogs/2331917
Mybatis加载解析Mapper(xml)文件第一讲: http://donald-draper.iteye.com/blog/2333125
Mybatis加载解析Mapper(xml)文件第二讲: http://donald-draper.iteye.com/admin/blogs/2333191
创建User表:
 
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) default NULL,
  `age` int(11) default NULL,
  `registerTime` timestamp NULL default NULL on update CURRENT_TIMESTAMP,
  PRIMARY KEY  (`id`),
  KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

创建testMybatis工程,根据Myeclispe下mybatis generator的使用这篇文章,自动生成,
实体类,Mapper接口与xml文件,我的generatorConfig.xml文件如下



	
	  
		    
		    
		    
		    
		    

生成的实体类:
package test.entity;

import java.util.Date;

public class User {
	private Integer id;
	private String name;
	private Integer age;
	private Date registertime;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	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 Date getRegistertime() {
		return registertime;
	}
	public void setRegistertime(Date registertime) {
		this.registertime = registertime;
	}
}

生成的xml:



	
		
		
		
		
	
	
		id, name, age, registerTime
	
	
	
		delete from user
		where id = #{id,jdbcType=INTEGER}
	
	
		insert into user (id, name, age,
		registerTime)
		values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR},
		#{age,jdbcType=INTEGER},
		#{registertime,jdbcType=TIMESTAMP})
	
	
		insert into user
		
			
				id,
			
			
				name,
			
			
				age,
			
			
				registerTime,
			
		
		
			
				#{id,jdbcType=INTEGER},
			
			
				#{name,jdbcType=VARCHAR},
			
			
				#{age,jdbcType=INTEGER},
			
			
				#{registertime,jdbcType=TIMESTAMP},
			
		
	
	
		update user
		
			
				name = #{name,jdbcType=VARCHAR},
			
			
				age = #{age,jdbcType=INTEGER},
			
			
				registerTime = #{registertime,jdbcType=TIMESTAMP},
			
		
		where id = #{id,jdbcType=INTEGER}
	
	
		update user
		set name = #{name,jdbcType=VARCHAR},
		age = #{age,jdbcType=INTEGER},
		registerTime = #{registertime,jdbcType=TIMESTAMP}
		where id = #{id,jdbcType=INTEGER}
	

生成的Mapper接口:
package test.Dao;

import test.entity.User;

public interface UserMapper {

    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

新建mybatisConfig.xml文件



	 
           
         
         
    
    
        
    
    
        
        	
            
	            
	            
	            
	            
            
        
    
    
        
    

Session测试主类:
package test.main;

import java.io.Reader;
import java.util.Date;

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 test.entity.User;
import test.util.JsonUtil;

public class testSqlSession {
	private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;
    static{
        try{
            reader    = Resources.getResourceAsReader("mybatisConfig.xml");
        /*    System.out.println("========path:"+Thread.currentThread().getContextClassLoader().getResource("mybatisConfig.xml"));
            Thread.currentThread().getContextClassLoader();
			System.out.println("========systemPath:"+ClassLoader.getSystemResource("mybatisConfig.xml"));*/
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    public static SqlSessionFactory getSession(){
        return sqlSessionFactory;
    }
    
    public static void main(String[] args) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
        	User u1 = new User();
        	u1.setAge(12);
        	u1.setName("donald");
	        session.insert("test.Dao.UserMapper.insert", u1);
	        User u2 = session.selectOne("test.Dao.UserMapper.selectByPrimaryKey", u1.getId());
	        System.out.println("======u1:"+JsonUtil.toJson(u2));
	        User u3 = new User();
	        u3.setAge(30);
	        u3.setName("jamel");
	        session.insert("test.Dao.UserMapper.insert", u3);
	        User u4 = session.selectOne("test.Dao.UserMapper.selectByPrimaryKey", u3.getId());
	        System.out.println("======u3:"+JsonUtil.toJson(u4));
//	        session.flushStatements();
                //提交插入的数据
	        session.commit();
	        u3.setName("rain");
		//update过后,清除一二级缓存
	        session.update("test.Dao.UserMapper.updateByPrimaryKeySelective", u3);
	        session.commit();
	        User u5 = session.selectOne("test.Dao.UserMapper.selectByPrimaryKey", u3.getId());
	        System.out.println("======cache-u3-name:"+u5.getName());
        } 
        catch(Exception e){
        	e.printStackTrace();
        }
        finally {
        	session.close();
        }
    }
}

控制台输出:
======u1:{"id":1,"registertime":null,"name":"donald","age":12}
======u3:{"id":2,"registertime":null,"name":"jamel","age":30}
======cache-u3-name:rain

接口测试主类:
package test.main;

import java.io.Reader;
import java.util.Date;

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 test.Dao.UserMapper;
import test.entity.User;
import test.util.JsonUtil;

public class testMapperInterface {
	private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;
    static{
        try{
            reader    = Resources.getResourceAsReader("mybatisConfig.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    public static SqlSessionFactory getSession(){
        return sqlSessionFactory;
    }
	public static void main(String[] args) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
        	User u1 = new User();
        	u1.setAge(20);
        	u1.setName("jamel");
        	UserMapper userOperation=session.getMapper(UserMapper.class);
        	userOperation.insert(u1);
        	session.flushStatements();
	        session.commit();
	        User u2 = userOperation.selectByPrimaryKey(u1.getId());
	        System.out.println("======u1:"+JsonUtil.toJson(u2));
        	
        } 
        catch(Exception e){
        	e.printStackTrace();
        }
        finally {
            session.close();
        }
    }
}

控制台输出:
======u1:{"id":1,"registertime":null,"name":"jamel","age":20}
我的工程目录:

mybatis 使用教程_第1张图片
  • mybatis 使用教程_第2张图片
  • 大小: 25.2 KB
  • 查看图片附件

你可能感兴趣的:(Mybatis)