1.mybaties 简单案例搭建

2019-08-29  本文已影响0人  进击的水瓶

目的

学习源码提升自己

目标

让家里的那个傻子也可以看懂 !!! 这很重要.

一. Mybaties 环境搭建及简单实例

1. 创建一个简单的项目

创建简单项目

2. 引入mybaties 依赖

<dependencies>
        <!-- 添加junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <!-- 添加log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>

        <!-- 添加mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.6</version>
        </dependency>

        <!-- 添加mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.12</version>
        </dependency>
    </dependencies>

3. 配置-配置文件

3.1.1 log4j.properties 配置文件及详解
  ```
#配置根Logger
  log4j.rootLogger  =   [ level ]   ,  appenderName ,  appenderName1 ,
#配置日志信息输出目的地Appender及Appender选项
  log4j.appender.appenderName = fully.qualified.name.of.appender.class     
  log4j.appender.appenderName.option = value1
  ...
  log4j.appender.appenderName.optionN = valueN 
#配置日志信息的格式(布局)及格式布局选项
    appender.appenderName.layout = fully.log4j.qualified.name.of.layout.class
    log4j.appender.appenderName.layout.option1 = value1
    ...
    log4j.appender.appenderName.layout.optionN = valueN
```
3.1.2 一个配置实例
```

配置根

log4j.rootLogger = debug,console ,fileAppender,dailyRollingFile,ROLLING_FILE,MAIL,DATABASE

### 设置输出sql的级别,其中logger后面的内容全部为jar包中所包含的包名 ###
log4j.logger.org.apache=dubug
log4j.logger.java.sql.Connection=dubug
log4j.logger.java.sql.Statement=dubug
log4j.logger.java.sql.PreparedStatement=dubug
log4j.logger.java.sql.ResultSet=dubug

### 配置输出到控制台 ###
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern =  %d{ABSOLUTE} %5p %c{1}:%L - %m%n

### 配置输出到文件 ###
log4j.appender.fileAppender = org.apache.log4j.FileAppender
log4j.appender.fileAppender.File = logs/log.log
log4j.appender.fileAppender.Append = true
log4j.appender.fileAppender.Threshold = DEBUG
log4j.appender.fileAppender.layout = org.apache.log4j.PatternLayout
log4j.appender.fileAppender.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 配置输出到文件,并且每天都创建一个文件 ###
log4j.appender.dailyRollingFile = org.apache.log4j.DailyRollingFileAppender
log4j.appender.dailyRollingFile.File = logs/log.log
log4j.appender.dailyRollingFile.Append = true
log4j.appender.dailyRollingFile.Threshold = DEBUG
log4j.appender.dailyRollingFile.layout = org.apache.log4j.PatternLayout
log4j.appender.dailyRollingFile.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 配置输出到文件,且大小到达指定尺寸的时候产生一个新的文件 ###
log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender 
log4j.appender.ROLLING_FILE.Threshold=ERROR 
log4j.appender.ROLLING_FILE.File=rolling.log 
log4j.appender.ROLLING_FILE.Append=true 
log4j.appender.ROLLING_FILE.MaxFileSize=10KB 
log4j.appender.ROLLING_FILE.MaxBackupIndex=1 
log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout 
log4j.appender.ROLLING_FILE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n

### 配置输出到邮件 ###
log4j.appender.MAIL=org.apache.log4j.net.SMTPAppender
log4j.appender.MAIL.Threshold=FATAL
log4j.appender.MAIL.BufferSize=10
log4j.appender.MAIL.From=chenyl@yeqiangwei.com
log4j.appender.MAIL.SMTPHost=mail.hollycrm.com
log4j.appender.MAIL.Subject=Log4J Message
log4j.appender.MAIL.To=chenyl@yeqiangwei.com
log4j.appender.MAIL.layout=org.apache.log4j.PatternLayout
log4j.appender.MAIL.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n

### 配置输出到数据库 ###
log4j.appender.DATABASE=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.DATABASE.URL=jdbc:mysql://localhost:3306/test
log4j.appender.DATABASE.driver=com.mysql.jdbc.Driver
log4j.appender.DATABASE.user=root
log4j.appender.DATABASE.password=
log4j.appender.DATABASE.sql=INSERT INTO LOG4J (Message) VALUES ('[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n')
log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout
log4j.appender.DATABASE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
log4j.appender.A1=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A1.File=SampleMessages.log4j
log4j.appender.A1.DatePattern=yyyyMMdd-HH'.log4j'
log4j.appender.A1.layout=org.apache.log4j.xml.XMLLayout
```
3.2 mybaties 配置文件 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配置文件, 我这里面配置的是数据库相关 -->
      <properties resource="dbConfig.properties"></properties>
  
      <!-- 指定Mybatis使用log4j -->
      <settings>
          <setting name="logImpl" value="LOG4J"/>
      </settings>
  
      <environments default="development">
          <environment id="development">
              <transactionManager type="JDBC"/>
              <dataSource type="POOLED">
                  <!--
                  如果上面没有指定数据库配置的properties文件,那么此处可以这样直接配置
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test1"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
                 -->
  
                  <!-- 上面指定了数据库配置文件, 配置文件里面也是对应的这四个属性 -->
                  <property name="driver" value="${ide.mybaties.driver}"/>
                  <property name="url" value="${ide.mybaties.url}"/>
                  <property name="username" value="${ide.mybaties.username}"/>
                  <property name="password" value="${ide.mybaties.password}"/>
  
              </dataSource>
          </environment>
      </environments>
  
      <!-- 映射文件,mybatis精髓, 后面才会细讲 -->
      <mappers>
          <mapper resource="com/ide/mybaties/dao/mapper/UserDaoMapping.xml"/>
      </mappers>
  
  </configuration>

数据库配置文件

ide.mybaties.driver=com.mysql.jdbc.Driver
ide.mybaties.url=jdbc:mysql://47.98.217.42:3306/mybaties
ide.mybaties.username=root
ide.mybaties.password=123456

4. 编写一个小demo

4.1 创建数据库表
```
CREATE TABLE `user` (
`id` int(9) NOT NULL AUTO_INCREMENT,
`name` varchar(15) DEFAULT NULL,
`password` varchar(30) DEFAULT NULL,
`age` int(3) DEFAULT NULL,
`delete_falg` int(2) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `name` (`name`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
```
4.2 创建 实体类 pojo
```
  package com.ide.mybaties.pojo;
    
    /**
     * TODO
     *
     * @author dairh
     * @version V1.0
     * @since 2019-08-13 16:45
     */
    public class User {
    
        private int id;
        private String name;
        private String password;
        private int age;
        private int deleteFlag;
    
        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 getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public int getDeleteFlag() {
            return deleteFlag;
        }
        public void setDeleteFlag(int deleteFlag) {
            this.deleteFlag = deleteFlag;
        }
    
    }

```
4.3 Dao 编写

编写接口 UserDao

package com.ide.mybaties.dao;

import com.ide.mybaties.pojo.User;

import java.util.List;

/**
 * TODO
 *
 * @author dairh
 * @version V1.0
 * @since 2019-08-13 16:41
 */
public interface UserDao {

    public void insert(User user);

    public User findUserById (int userId);

    public List<User> findAllUsers();
}
4.4 重点: Mapping.xml 文件编写

这里有个小坑 注意简单demo要把mapping文件放在resource目录下,否则mybaties.xml文件找不到 mapping.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.ide.mybaties.dao.UserDao">

<select id="findUserById" resultType="com.ide.mybaties.pojo.User" >
      select * from user where id = #{id}
   </select>

</mapper>
4.5 测试demo 查看运行结果

测试代码

package com.ide.mybaties.dao;

import com.ide.mybaties.pojo.User;

import java.io.IOException;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Assert;
import org.junit.Test;

/**
 * TODO
 *
 * @author dairh
 * @version V1.0
 * @since 2019-08-13 16:55
 */
public class UserDaoTest {




    @Test
    public void select(){
        SqlSessionFactory sessionFactory = getSessionFactory();

        UserDao mapper = sessionFactory.openSession().getMapper(UserDao.class);

        User userById = mapper.findUserById(2);

        Assert.assertNotNull("没找到数据!", userById);

    }



    //Mybatis 通过SqlSessionFactory获取SqlSession, 然后才能通过SqlSession与数据库进行交互
    private static SqlSessionFactory getSessionFactory() {
        SqlSessionFactory sessionFactory = null;
        String resource = "mybaties.xml";
        try {
            sessionFactory = new SqlSessionFactoryBuilder().build(Resources
                .getResourceAsReader(resource));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sessionFactory;
    }

}

//Mybatis 通过SqlSessionFactory获取SqlSession, 然后才能通过SqlSession与数据库进行交互 直接获取sessionFactory的代码可以关注一下 这是在脱离spring的情况下的解决方案

运行结果
上一篇下一篇

猜你喜欢

热点阅读