MyBatis是一个支持普通SQL查询存储过程高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装。MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。

框架整体结构图:

关键代码介绍

  1.ICatagoryOperation接口                   

public interface ICatagoryOperation { 
    void inserteCatagory(Catagory catagory); 
 
    Catagory getCatagorybyID(int id); 
}

 2.Catagory类

public class Catagory { 
    private int id; 
    private String name; 
 
    private String description; 
 
    public int getId() { 
        return id; 
    } 
 
    public void setId(int id) { 
        this.id = id; 
    } 
 
    public String getName() { 
        return name; 
    } 
 
    public void setName(String name) { 
        this.name = name; 
    } 
 
    public String getDescription() { 
        return description; 
    } 
 
    public void setDescription(String description) { 
        this.description = description; 
    } 
 
    @Override 
    public String toString() { 
        return String.format("id:%d,name:%s,description:%s", id, name, description); 
    } 
}

3.MyBatisUtils类

public class MyBatisUtils { 
    private static final String CONFIG_PATH = "config/mybatis_config.xml"; 
 
    /* 
     * 获取数据库访问链接 
     */ 
    public static SqlSession getSqlSession() { 
        SqlSession session = null; 
        try { 
            InputStream stream = Resources.getResourceAsStream(CONFIG_PATH); 
            // 可以根据配置的相应环境读取相应的数据库环境 
            // SqlSessionFactory factory = new SqlSessionFactoryBuilder().build( 
            // stream, "development"); 
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(stream); 
            session = factory.openSession(); 
        } catch (Exception e) { 
            // TODO: handle exception 
            e.printStackTrace(); 
        } 
        return session; 
    } 
 
    /* 
     * 获取数据库访问链接 
     */ 
    public static void closeSession(SqlSession session) { 
        session.close(); 
    }     
}

4.CatagoryMapper.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.franson.study.interfaces.ICatagoryOperation"> 
<!-- 此处的resultType就是对应刚刚你在typeAlias节点里面规定的别名 --> 
    <select id="inserteCatagory" parameterType="Catagory"> 
       insert into tb_catagories(name,description) values(#{name},#{description}) 
    </select> 
    <select id="getCatagorybyID" resultType="Catagory" parameterType="java.lang.Integer"> 
    select * from tb_catagories where id=#{id} 
    </select> 
</mapper>

5.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> 
    <typeAliases> 
        <typeAlias type="com.franson.study.model.Catagory" alias="Catagory" /> 
    </typeAliases> 
    <environments default="development"> 
        <environment id="development"> 
            <transactionManager type="JDBC"></transactionManager> 
            <dataSource type="POOLED"> 
                <property name="driver" value="com.mysql.jdbc.Driver" /> 
                <!-- ?useUnicode=true&amp;characterEncoding=utf8为了支持中文数据的写入 --> 
                <property name="url" 
                    value="jdbc:mysql://127.0.0.1:3306/db_catagory?useUnicode=true&amp;characterEncoding=utf8" /> 
                <property name="username" value="root" /> 
                <property name="password" value="123456" /> 
            </dataSource> 
        </environment> 
    </environments> 
    <mappers> 
        <mapper resource="mapper/CatagoryMapper.xml" /> 
    </mappers> 
</configuration>

6.TestMybatis测试入口类 

public class TestMybatis { 
 
    public static void main(String[] args) { 
        addTest(); 
        getTest(); 
    } 
 
    /* 
     * 添加Catagory 
     */ 
    static void addTest() { 
        SqlSession sqlSession = MyBatisUtils.getSqlSession(); 
        ICatagoryOperation catagoryOperation = sqlSession.getMapper(ICatagoryOperation.class); 
        Catagory item = new Catagory(); 
        item.setName("sql server"); 
        item.setDescription("sql server类"); 
        int result = catagoryOperation.inserteCatagory(item); 
        if (result > 0) { 
            sqlSession.commit(); 
            System.out.println("添加成功"); 
        } else 
            sqlSession.rollback(); 
        MyBatisUtils.closeSession(sqlSession); 
    } 
 
    /* 
     * 根据ID获取Catagory 
     */ 
    static void getTest() { 
        SqlSession sqlSession = MyBatisUtils.getSqlSession(); 
        ICatagoryOperation catagoryOperation = sqlSession.getMapper(ICatagoryOperation.class); 
        System.out.println(catagoryOperation.getCatagorybyID(3).toString()); 
        MyBatisUtils.closeSession(sqlSession); 
    } 
}

7.测试运行结果


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

Java并发编程:Thread类的使用介绍