MyBatis3.x Idea搭建

  1. 云栖社区>
  2. 博客>
  3. 正文

MyBatis3.x Idea搭建

gabriel丶 2018-10-31 17:01:00 浏览616
展开阅读全文

MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。

MyBatis作为一款优秀的orm框架,经常与Hibernate拿来比较,身为目前较流行的MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。接下来我们来看看如何搭建一个MyBaits项目。
因为idea并不支持mybatis的自动搭建,所以我们需要手动的导入一些jar包

需要准备的Jar包

mybatis-3.4.6.jar mybatis的主体
mysql-connector-java-5.1.46.jar 链接数据的
log4j-1.2.17 用于打印日志的

关于Mybatis的构建分为两种,我们先看XML方式

XML方式

1. Mybatis-configuration.xml

mybatis-configuration.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>
    <!-- 引入配置文件 -->
    <properties resource="db.properties"/>
    <!-- 设置打印使用log4j -->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <!-- 设置运行时环境 -->
    <!-- mybatis 允许存在多个运行时环境 -->
    <environments default="development">
        <environment id="development">
            <!-- transactionManager 事务管理者 -->
            <!-- 设置本次事务管理方式为JDBC -->
            <transactionManager type="JDBC"/>
            <!-- 数据源 连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${user}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 引入映射文件 -->
    <mappers>
        <mapper resource="model/UserMapper.xml"/>
    </mappers>
</configuration>

2.User.java以及UserMapper.xml

User.java

package model;

/**
 * Created by Administrator on 2018/10/31.
 */
public class User {

    private int id;

    private String username;

    private String nickname;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", nickname='" + nickname + '\'' +
                '}';
    }
}

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="model.UserMapper">
    <!-- id sql语句的id 调用时使用命名空间+sqlid方式进行调用 -->
    <!-- parameterType 参数类型 -->
    <!-- resultType 返回值类型 -->
    <select id="selectUserById" parameterType="int" resultType="model.User">
        <!-- 参数注入时使用#或$ -->
        <!-- #是占位符,在预编译时使用?占位,可以预防sql注入的问题 -->
        <!-- $是连接符,解析sql时直接使用变量替换,可能会引起sql注入的问题 -->
        <!-- #和$ 相当于 preparedStatement和statement的区别 -->
        <!-- 总的来说,能用#就别用$ -->
        select id,username,nickname from user where id = #{id}
    </select>

</mapper>

3.db.properties以及log4j.properties

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///test
user=root
password=root

log4j.properties

log4j.rootLogger=DEBUG, stdout    

log4j.appender.stdout=org.apache.log4j.ConsoleAppender    
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout    
log4j.appender.stdout.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n    

#log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.R.File=../logs/service.log
#log4j.appender.R.layout=org.apache.log4j.PatternLayout
#log4j.appender.R.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n

#log4j.logger.com.ibatis = debug
#log4j.logger.com.ibatis.common.jdbc.SimpleDataSource = debug
#log4j.logger.com.ibatis.common.jdbc.ScriptRunner = debug
#log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate = debug
#log4j.logger.java.sql.Connection = debug
log4j.logger.java.sql.Statement = debug    
log4j.logger.java.sql.PreparedStatement = debug    
log4j.logger.java.sql.ResultSet =debug   

4. 测试一下

Main.java

import model.User;
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 java.io.IOException;
import java.io.Reader;

public class Main {

    public static void main(String[] args) throws IOException {
        //xml方式
        //定义mybatis的配置文件的路径
        String resource = "mybatis_config.xml";
        //将配置文件转换为reader
        Reader reader = Resources.getResourceAsReader(resource);
        //使用sqlsessionfactorybuilder对配置文件进行加载
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //获取sqlsession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = sqlSession.selectOne("model.UserMapper.selectUserById",1);
        System.out.println(user);
    }
}

最后看一下控制台的输出内容

[service] 2018-10-31 16:59:55,875 - org.apache.ibatis.logging.LogFactory -0    [main] DEBUG org.apache.ibatis.logging.LogFactory  - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
    [service] 2018-10-31 16:59:56,047 - org.apache.ibatis.logging.LogFactory -172  [main] DEBUG org.apache.ibatis.logging.LogFactory  - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
    [service] 2018-10-31 16:59:56,075 - org.apache.ibatis.datasource.pooled.PooledDataSource -200  [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
    [service] 2018-10-31 16:59:56,075 - org.apache.ibatis.datasource.pooled.PooledDataSource -200  [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
    [service] 2018-10-31 16:59:56,075 - org.apache.ibatis.datasource.pooled.PooledDataSource -200  [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
    [service] 2018-10-31 16:59:56,075 - org.apache.ibatis.datasource.pooled.PooledDataSource -200  [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
    [service] 2018-10-31 16:59:56,207 - org.apache.ibatis.transaction.jdbc.JdbcTransaction -332  [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction  - Opening JDBC Connection
    [service] 2018-10-31 16:59:56,541 - org.apache.ibatis.datasource.pooled.PooledDataSource -666  [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource  - Created connection 836514715.
    [service] 2018-10-31 16:59:56,541 - org.apache.ibatis.transaction.jdbc.JdbcTransaction -666  [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction  - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@31dc339b]
    [service] 2018-10-31 16:59:56,543 - model.UserMapper.selectUserById -668  [main] DEBUG model.UserMapper.selectUserById  - ==>  Preparing: select id,username,nickname from user where id = ? 
    [service] 2018-10-31 16:59:56,607 - model.UserMapper.selectUserById -732  [main] DEBUG model.UserMapper.selectUserById  - ==> Parameters: 1(Integer)
    [service] 2018-10-31 16:59:56,640 - model.UserMapper.selectUserById -765  [main] DEBUG model.UserMapper.selectUserById  - <==      Total: 1
    User{id=1, username='赵大鹏', nickname='死亡列车'}

可以看到sql语句以及查询的结果都出来了,mybatis使用xml方式搭建完毕。

网友评论

登录后评论
0/500
评论
gabriel丶
+ 关注