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/
创建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文件如下
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration >
	<classPathEntry  location="E:\lib\mysql-connector-5.1.8.jar" />
	  <context id="contextMybatis" >
		    <jdbcConnection driverClass="com.mysql.jdbc.Driver" 
		    	connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8" 
		    	userId="root" 
		    	password="123456" />
		    <javaModelGenerator targetPackage="test.entity" targetProject="TestMybatis" />
		    <sqlMapGenerator targetPackage="test.Mapper" targetProject="TestMybatis" />
		    <javaClientGenerator targetPackage="test.Dao" targetProject="TestMybatis" type="XMLMAPPER" />
		    <table tableName="user"  
	            domainObjectName="User" enableInsert="true"  
	            enableSelectByPrimaryKey="true" enableUpdateByPrimaryKey="true"  
	            enableDeleteByPrimaryKey="true" enableSelectByExample="false"  
	            enableDeleteByExample="false" enableCountByExample="false"  
	            enableUpdateByExample="false">  
        	</table>  
  	 </context>
</generatorConfiguration>

生成的实体类:
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:
<?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="test.Dao.UserMapper">
	<resultMap id="BaseResultMap" type="test.entity.User">
		<id column="id" property="id" jdbcType="INTEGER" />
		<result column="name" property="name" jdbcType="VARCHAR" />
		<result column="age" property="age" jdbcType="INTEGER" />
		<result column="registerTime" property="registertime" jdbcType="TIMESTAMP" />
	</resultMap>
	<sql id="Base_Column_List">
		id, name, age, registerTime
	</sql>
	<select id="selectByPrimaryKey" resultMap="BaseResultMap"
		parameterType="java.lang.Integer">
		select
		<include refid="Base_Column_List" />
		from user
		where id = #{id,jdbcType=INTEGER}
	</select>
	<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
		delete from user
		where id = #{id,jdbcType=INTEGER}
	</delete>
	<insert id="insert" parameterType="test.entity.User" keyProperty="id">
		insert into user (id, name, age,
		registerTime)
		values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR},
		#{age,jdbcType=INTEGER},
		#{registertime,jdbcType=TIMESTAMP})
	</insert>
	<insert id="insertSelective" parameterType="test.entity.User">
		insert into user
		<trim prefix="(" suffix=")" suffixOverrides=",">
			<if test="id != null">
				id,
			</if>
			<if test="name != null">
				name,
			</if>
			<if test="age != null">
				age,
			</if>
			<if test="registertime != null">
				registerTime,
			</if>
		</trim>
		<trim prefix="values (" suffix=")" suffixOverrides=",">
			<if test="id != null">
				#{id,jdbcType=INTEGER},
			</if>
			<if test="name != null">
				#{name,jdbcType=VARCHAR},
			</if>
			<if test="age != null">
				#{age,jdbcType=INTEGER},
			</if>
			<if test="registertime != null">
				#{registertime,jdbcType=TIMESTAMP},
			</if>
		</trim>
	</insert>
	<update id="updateByPrimaryKeySelective" parameterType="test.entity.User">
		update user
		<set>
			<if test="name != null">
				name = #{name,jdbcType=VARCHAR},
			</if>
			<if test="age != null">
				age = #{age,jdbcType=INTEGER},
			</if>
			<if test="registertime != null">
				registerTime = #{registertime,jdbcType=TIMESTAMP},
			</if>
		</set>
		where id = #{id,jdbcType=INTEGER}
	</update>
	<update id="updateByPrimaryKey" parameterType="test.entity.User">
		update user
		set name = #{name,jdbcType=VARCHAR},
		age = #{age,jdbcType=INTEGER},
		registerTime = #{registertime,jdbcType=TIMESTAMP}
		where id = #{id,jdbcType=INTEGER}
	</update>
</mapper>

生成的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文件
<?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> 
        <setting name="cacheEnabled" value="true" /><!-- 全局映射器启用缓存 -->   
        <setting name="useGeneratedKeys" value="true" /> 
        <setting name="defaultExecutorType" value="REUSE" /> 
    </settings>
    <typeAliases>
        <typeAlias alias="User" type="test.entity.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://localhost:3306/test" />
	            <property name="username" value="root"/>
	            <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="test/Mapper/UserMapper.xml"/>
    </mappers>
</configuration>

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)