MyBatis配置记不住,看这里快速上手

准备工作

在学习Mybatis之前,先需要做一些准备工作,以方便后面测试。

  • 使用Maven依赖相关jar包
  • 配置Log4j日志文件
  • 准备好用于测试的数据库
  • 创建实体类

MyBatis相关Jar包

<dependencies>
    
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatisartifactId>
        <version>3.4.6version>
    dependency>

    
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.12version>
    dependency>

    
    <dependency>
        <groupId>log4jgroupId>
        <artifactId>log4jartifactId>
        <version>1.2.17version>
    dependency>

    
   <dependency>
       <groupId>mysqlgroupId>
       <artifactId>mysql-connector-javaartifactId>
       <version>5.1.46version>
    dependency>
dependencies>

Log4j日志文件

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

创建数据库

-- 创建数据库
CREATE DATABASE mybatistest;

-- 使用数据库
USE mybatistest;

-- 创建数据库表
CREATE TABLE user(
	id INT PRIMARY KEY AUTO_INCREMENT,
	uname VARCHAR(20),
	usex VARCHAR(20)
);

-- 添加数据
INSERT INTO user(uname,usex) VALUES('张三','男');
INSERT INTO user(uname,usex) VALUES('李四','女');

-- 查询user表
SELECT * FROM user;

创建User类

public class User {
    private Integer id;
    private String uname;
    private String usex;

    public Integer getId() {
        return id;
    }

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

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getUsex() {
        return usex;
    }

    public void setUsex(String usex) {
        this.usex = usex;
    }
}

MyBatis相关配置文件

创建jdbc.properties文件

# 驱动类
driver=com.mysql.jdbc.Driver
# mysql数据库url地址
url=jdbc:mysql://localhost:3306/mybatistest
# 用户名
username=root
# 密码
password=root

创建UserMapper映射文件



<mapper namespace="com.itheima.dao.UserDao">
    
    <select id="selectUserById" resultType="com.itheima.domain.User" parameterType="Integer">
        select * from user where id=#{id}
    select>

    
    <select id="selectAllUser" resultType="com.itheima.domain.User">
        select * from user
    select>

    
    <select id="addUser" parameterType="com.itheima.domain.User">
        insert into User(uname,usex) values(#{uname},#{usex})
    select>

    
    <delete id="deleteUser" parameterType="Integer">
        delete from user where id=#{id}
    delete>

    
    <update id="updateUser" parameterType="com.itheima.domain.User">
        update user set uname=#{uname},usex=#{usex} where id=#{id}
    update>
mapper>

创建MyBatis-config.xml文件



<configuration>
	
    <properties resource="com/mybatis/jdbc.properties"/>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            dataSource>
        environment>
    environments>
    
    <mappers>
       <mapper resource="com/itheima/mybatis/UserMapper.xml"/>
    mappers>
configuration>

旧版本MyBatis执行sql映射

读取配置文件

//读取配置文件
InputStream in = Resources.getResourceAsStream("com/itheima/mybatis/mybatis-config.xml");
//根据配置文件构建SqlSessionFactory
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
//通过SqlSessionFactory创建SqlSession
SqlSession ss = ssf.openSession();

执行sql映射

创建一个测试类,分别对增加、删除、修改、查询等方法进行测试

public class UserDaoTest {
    private SqlSession ss = null;
    /*执行在每次@Test运行之前,用于加载MyBatis-config配置文件*/
    @Before
    public void init() {
        try {
            //读取配置文件
            InputStream in = Resources.getResourceAsStream("com/itheima/mybatis/mybatis-config.xml");
            //根据配置文件构建SqlSessionFactory
            SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
            //通过SqlSessionFactory创建SqlSession
            ss = ssf.openSession();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /*测试添加*/
    @Test
    public void testAdd() {
        //添加一个用户
        User user = new User();
        user.setUname("王五");
        user.setUsex("女");
        int count = ss.insert("com.itheima.dao.UserDao.addUser", user);
        System.out.println(count+":"+(count > 0 ? "添加成功" : "添加失败"));
        ss.commit();
    }

    /*测试查询*/
    @Test
    public void testSelect() {
        //查询多个用户
        List<User> list = ss.selectList("com.itheima.dao.UserDao.selectAllUser");
        for (User o : list) {
            System.out.println(o);
        }
        ss.commit();
        System.out.println("-----------------------");
        User o = ss.selectOne("com.itheima.dao.UserDao.selectUserById", 1);
        System.out.println(o);
    }

    /*测试修改*/
    @Test
    public void testUpdate(){
        User user=new User();
        user.setId(1);
        user.setUname("柳岩");
        user.setUsex("女");
        int count = ss.update("com.itheima.dao.UserDao.updateUser", user);
        System.out.println(count+":"+(count>0?"修改成功":"修改失败"));
        ss.commit();
    }

    /*删除修改*/
    @Test
    public void testDelete(){
        int count = ss.update("com.itheima.dao.UserDao.deleteUser", 3);
        System.out.println(count+":"+(count>0?"删除成功":"删除失败"));
        ss.commit();
    }
}

新版本MyBatis执行sql映射

在老版的MayBatis中执行sql映射的代码写起来比较麻烦,如添加用户代码如下

/*添加用户*/
@Test
public void testAdd() {
    User user = new User();
    user.setUname("王五");
    user.setUsex("女");
  	//添加用户
    int count = ss.insert("com.itheima.mapper.UserMapper.addUser", user);
    System.out.println(count+":"+(count > 0 ? "添加成功" : "添加失败"));
    ss.commit();
}

不过现在有了一种更简洁的方式 ——使用正确描述每个语句的参数和返回值的接口(比如 UserMapper.class),你现在不仅可以执行更清晰和类型安全的代码,而且还不用担心易错的字符串字面值以及强制类型转换。

定义UserMapper接口

public interface UserMapper {
    /*查询所有的User*/
    public List<User> selectAllUser();
    /*通过id查询一个User*/
    public User selectUserById(Integer id);
    /*添加一个User*/
    public int addUser(User user);
    /*通过id删除一个User*/
    public int deleteUser(Integer id);
    /*修改一个User*/
    public int updateUser(User user);
}

注意UserMapper接口中的方法的参数和返回值要和UserMapper.xml映射文件中配置的参数和返回值保持一致

定义UserMapper.xml映射文件



<mapper namespace="com.itheima.dao.UserDao">
    
    <select id="selectUserById" resultType="com.itheima.domain.User" parameterType="Integer">
        select * from user where id=#{id}
    select>

    
    <select id="selectAllUser" resultType="com.itheima.domain.User">
        select * from user
    select>

    
    <insert id="addUser" parameterType="com.itheima.domain.User">
        insert into User(uname,usex) values(#{uname},#{usex})
    insert>

    
    <delete id="deleteUser" parameterType="Integer">
        delete from user where id=#{id}
    delete>

    
    <update id="updateUser" parameterType="com.itheima.domain.User">
        update user set uname=#{uname},usex=#{usex} where id=#{d}
    update>
mapper>

创建测试类并执行

public class UserDaoTest2 {
    /*测试添加*/
    @Test
    public void testAdd() {
        //读取配置文件
        SqlSession ss =null;
        try {
            InputStream in = Resources.getResourceAsStream("com/itheima/mybatis/mybatis-config.xml");
            SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
            ss= ssf.openSession();
            UserDao mapper = ss.getMapper(UserDao.class);
            //创建一个用户
            User user = new User();
            user.setUname("赵六");
            user.setUsex("男");
            //添加一个用户
            Integer i = mapper.addUser(user);
        } catch (IOException e) {
            e.printStackTrace();
            ss.rollback();
            System.out.println("添加失败,事务已经回滚");
        }finally {
            ss.commit();
            System.out.println("事务已经提交,添加成功");
        }
    }

    /*测试查询*/
    @Test
    public void testSelect() {
        //读取配置文件
        try {
            InputStream in = Resources.getResourceAsStream("com/itheima/mybatis/mybatis-config.xml");
            SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
            SqlSession ss = ssf.openSession();
            UserDao mapper = ss.getMapper(UserDao.class);

            //查询所有用户
            List<User> users = mapper.selectAllUser();
            for (User user : users) {
                System.out.println(user);
            }
            System.out.println("---------------");

            //查询一个用户
            User user = mapper.selectUserById(1);
            System.out.println(user);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*测试修改*/
    @Test
    public void testUpdate(){
        //读取配置文件
        SqlSession ss=null;
        try {
            InputStream in = Resources.getResourceAsStream("com/itheima/mybatis/mybatis-config.xml");
            SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
            ss=ssf.openSession();
            UserDao mapper = ss.getMapper(UserDao.class);

            //修改用户
            User user=new User();
            user.setId(1);
            user.setUname("大鹏");
            user.setUsex("男");

            //修改用户
            mapper.updateUser(user);
        } catch (IOException e) {
            e.printStackTrace();
            ss.rollback();//回滚事务
            System.out.println("出现异常,回滚事务");
        }finally {
            ss.commit(); //提交事务
            System.out.println("正常执行,事务已经提交");
        }
    }

    /*删除修改*/
    @Test
    public void testDelete(){
        //读取配置文件
        SqlSession ss=null;
        try {
            InputStream in = Resources.getResourceAsStream("com/itheima/mybatis/mybatis-config.xml");
            SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
            ss=ssf.openSession();
            UserDao mapper = ss.getMapper(UserDao.class);

            //修改用户
            mapper.deleteUser(2);
        } catch (IOException e) {
            e.printStackTrace();
            ss.rollback();//回滚事务
            System.out.println("出现异常,回滚事务");
        }finally {
            ss.commit(); //提交事务
            System.out.println("正常执行,事务已经提交");
        }
    }
}

MyBatis核心配置小结

MyBatis的核心配置文件的文档的顶层结构如下:

configuration(配置)
    properties(属性)
    settings(设置)
    typeAliases(类型别名)
    typeHandlers(类型处理器)
    objectFactory(对象工厂)
    plugins(插件)
    environments(环境配置)
    	environment(环境变量)
    		transactionManager(事务管理器)
    		dataSource(数据源)
    databaseIdProvider(数据库厂商标识)
    mappers(映射器)

properties(属性)

jdbc.properties文件

# 驱动类
driver=com.mysql.jdbc.Driver
# mysql数据库url地址
url=jdbc:mysql://localhost:3306/mybatistest
# 用户名
username=root
# 密码
password=root

mybatis-config.xml中引入jdbc.properties文件

<configuration>
	
    <properties resource="com/mybatis/jdbc.properties"/>
configuration>

typeAliases(类型别名)

类型别名是为 Java 类型设置一个短的名字,存在的意义仅在于用来减少类完全限定名的冗余

<typeAliases>
  <typeAlias alias="user" type="com.itheima.User"/>
typeAliases>

在使用com.itheima.User的地方都可以使用user代替

<mapper namespace="com.itheima.dao.UserDao">
    
    <select id="selectUserById" resultType="user" parameterType="Integer">
        select * from user where id=#{id}
    select>
mapper>

environments(环境配置)

<environments default="development">
  <environment id="development">
    <transactionManager type="JDBC">
      <property name="..." value="..."/>
    transactionManager>
    <dataSource type="POOLED">
      <property name="driver" value="${driver}"/>
      <property name="url" value="${url}"/>
      <property name="username" value="${username}"/>
      <property name="password" value="${password}"/>
    dataSource>
  environment>
environments>
注意这里的关键点:
    默认使用的环境 ID(比如:default="development")。
    每个 environment 元素定义的环境 ID(比如:id="development")。
    事务管理器的配置(比如:type="JDBC")。
    数据源的配置(比如:type="POOLED")。
    默认的环境和环境 ID 是自解释的,因此一目了然。 你可以对环境随意命名,但一定要保证默认的环境 ID 要匹配其中一个环境 ID。

mappers(映射器)

使用相对于类路径的资源引用


<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
  <mapper resource="org/mybatis/builder/PostMapper.xml"/>
mappers>

使用映射器接口实现类的完全限定类名


<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
  <mapper class="org.mybatis.builder.BlogMapper"/>
  <mapper class="org.mybatis.builder.PostMapper"/>
mappers>

你可能感兴趣的:(mybatis,环境安装)