MyBatis源码分析-IDEA新建MyBatis源码工程

  MyBatis 是支持定制化
SQL、存储过程和高档映射的佳绩之持久层框架。MyBatis 避免了几乎有的
JDBC 代码和手动设置参数与获得结果集。MyBatis
可以本着部署以及原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain
Old Java Objects,普通的
Java对象)映射成数据库中之记录。项目GitHub地址

  下载MyBatis源码,导入到IDEA工程(Maven工程)中,工程结构如下:

图片 1

每当pom.xml中新增如下依赖:

<!-- MySQL相关 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.38</version>
</dependency>

<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.6.2</version>
</dependency>

<dependency>
    <groupId>ognl</groupId>
    <artifactId>ognl</artifactId>
    <version>3.1.6</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.21</version>
</dependency>

<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>2.2.2</version>
</dependency>

  等待依赖更新了后,如果出现了@Override覆盖接口方法报错问题,请参考IDEA中
@override报错的缓解方式。

 

MyBatis配置conf.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="lazyLoadingEnabled" value="false"/>
        <!--setting name="logImpl" value="STDOUT_LOGGING"/--> <!-- 日志 -->
    </settings>

    <typeAliases>
        <typeAlias type="com.luoxn28.dao.User" alias="User"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" /> <!-- 声明使用那种事务管理机制 JDBC/MANAGED -->
            <!-- 配置数据库连接信息 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://192.168.1.150:3306/xxx" />
                <property name="username" value="xxx" />
                <property name="password" value="xxx" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="userMapper.xml"/>
    </mappers>

</configuration>

User类的投射文件userMapper.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.luoxn28.dao.UserDao">

    <select id="getById" parameterType="int" resultType="User">
        SELECT * FROM user WHERE id=#{id}; <!-- #{xxx} xxx为类中的数据域名称 -->
    </select>

    <select id="getAll" resultType="com.luoxn28.dao.User">
        SELECT * FROM user;
    </select>
</mapper>

测试代码:

/**
 * MyBatis测试类
 */
public class TestMain {

    public static void main(String[] args) throws IOException {
        String resouce = "conf.xml";
        //InputStream is = TestMain.class.getClassLoader().getResourceAsStream(resouce);
        InputStream is = Resources.getResourceAsStream(resouce);

        // 构建sqlSession工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession session = sqlSessionFactory.openSession();

        /**
         * 第一种方式: 直接执行已映射的 SQL 语句
         */
        String statement = "com.luoxn28.dao.UserDao.getById";
        User user = session.selectOne(statement, 1);
        System.out.println(user);

        System.out.println("---------------------");

        /**
         * 第二种方式: 执行更清晰和类型安全的代码
         */
        UserDao userDao = session.getMapper(UserDao.class);
        user = userDao.getById(1);
        System.out.println(user);
    }

}

User用户类:

图片 2图片 3

/**
 * User - 用户类
 */
public class User {

    public static final int MAN  = 0;   // 男生
    public static final int WOMAN = 1;  // 女生
    public static final int OTHER = 2;  // 其他

    private int id;             // 用户id
    private String name;        // 用户名
    private String password;    // 用户密码
    private int sex;            // 用户性别
    private String email;       // 用户邮箱
    private String phone;       // 用户手机
    private String admin;       // 用户是否是管理员,"admin"表示是管理员,其他为普通用户

    public User() { }

    public User(String name, String password, int sex, String email, String phone) {
        this.name = name;
        this.password = password;
        this.sex = sex;
        this.email = email;
        this.phone = phone;
        this.admin = "";
    }
    public User(String name, String password, String sex, String email, String phone) {
        this.name = name;
        this.password = password;
        setSex(sex); // this.sex = sex;
        this.email = email;
        this.phone = phone;
        this.admin = "";
    }

    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 getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    public void setSex(String sexStr) {
        int sex = Integer.valueOf(sexStr);
        switch (Integer.valueOf(sexStr)) {
            case 0: {
                this.sex = MAN;
                break;
            }
            case 1: {
                this.sex = WOMAN;
                break;
            }
            default: {
                this.sex = OTHER;
                break;
            }
        }
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAdmin() {
        return admin;
    }

    public void setAdmin(String admin) {
        this.admin = admin;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", sex=" + sex +
                ", email='" + email + '\'' +
                ", phone='" + phone + '\'' +
                ", admin='" + admin + '\'' +
                '}';
    }

}

User

UserDao用户操作类

/**
 * UserDao - User操作类
 */
public interface UserDao {

    public User getById(int id);
    public List<User> getAll();

}

  以上示例代码是因此XML来设置映射语句之,当然,也足以用Java注解来做。比如,上面的
XML 示例可为轮换如下:

/**
 * UserDao - User操作类
 */
public interface UserDao {

    @Select("SELECT * FROM user WHERE id=#{id}")
    public User getById(int id);

    @Select("SELECT * FROM user")
    public List<User> getAll();

}

  使用注解时调用实例:

UserDao userDao = session.getMapper(UserDao.class);
user = userDao.getById(1);
System.out.println(user);

  对于简易语句来说,注解使代码显得更加简洁,然而 Java
注解对于小复杂的言语就会无法并且会来得愈加混乱。因此,如果您得开老复杂的业务,那么最好好下
XML
来照语句。选择何种方法和映射语词的定义之一致性对君吧出差不多要这些统统取决于你跟汝的社。换句话说,永远不要拘泥于一致种艺术,你可好自在的以冲注解和
XML
的讲话映射方式里随意移植和切换。注意:UserDao接口的getById方法配置了诠释,那么就是毫无XML中布局<select
id=”getById”>xxx</select>了,否则程序会报异常。

 

参考:

  1、IDEA中
@override报错的解决措施

  2、MyBatis3中文文档

网站地图xml地图