文章目录

1.注解方式操作

文件目录

MyBatis(注解方式操作)-LMLPHP

1.快速入门(完整步骤)
1.pom.xml(完整)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.example</groupId>
  <artifactId>mybatis</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>pom</packaging>
  <name>Archetype - mybatis</name>
  <url>http://maven.apache.org</url>
  <modules>
    <module>mybatis_quickstart</module>
  </modules>
  <dependencies>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.49</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.7</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <!--如果设置scope为test,则只能在test包下使用-->
      <scope>test</scope>
    </dependency>
  </dependencies>
  <!--在父模块中的pom.xml文件中配置在build的时候要扫描的文件,解决某些类型文件拷贝到target目录失败的问题-->
  <build>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <!--在java文件夹下的多级目录下的xml文件-->
          <include>**/*.xml</include>
        </includes>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <!--在resources文件夹下的多级目录下的xml文件和properties文件-->
          <include>**/*.xml</include>
          <include>**/*.properties</include>
        </includes>
      </resource>
    </resources>
  </build>
</project>

2.resources/jdbc.properties外部配置文件(根据实际情况修改参数)
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root
3.在resources/mybatis-config.xml(完整)中配置含有注解的接口

MyBatis(注解方式操作)-LMLPHP

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--引入外部文件jdbc.properties-->
    <properties resource="jdbc.properties"/>

    <!--配置mybatis自带的日志,settings需要放到最前面-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <environments default="development">
        <environment id="development">
            <!--配置事务管理器-->
            <transactionManager type="JDBC"/>
            <!--配置数据源-->
            <dataSource type="POOLED">
                <!--配置驱动-->
                <property name="driver" value="${jdbc.driver}"/>
                <!--配置连接url-->
                <!--
                1.jdbc:mysql:协议
                2.127.0.0.1:3306:指定连接mysql的ip+端口
                3.mybatis:连接的db
                4.useSSL:使用安全连接
                5.&amp;:表示&
                6.useUnicode=true:使用unicode,防止编码错误
                7.characterEncoding=UTF-8:字符集使用utf-8
                -->
                <property name="url" value="${jdbc.url}"/>
                <!--用户名-->
                <property name="username" value="${jdbc.username}"/>
                <!--密码-->
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--包的方式引入含有注解的类-->
        <package name="com.sun.mapper"/>
    </mappers>

</configuration>

4.映射类Monster.java
package com.sun.entity;

import java.util.Date;

/**
 * @author 孙显圣
 * @version 1.0
 */
public class Monster {
    private Integer id;
    private Integer age;
    private Date birthday;
    private String email;
    private Integer gender;
    private String name;
    private Double salary;

    //无参构造器
    public Monster() {
    }

    public Monster(Integer id, Integer age, Date birthday, String email, Integer gender, String name, Double salary) {
        this.id = id;
        this.age = age;
        this.birthday = birthday;
        this.email = email;
        this.gender = gender;
        this.name = name;
        this.salary = salary;
    }

    public Integer getId() {
        return id;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getEmail() {
        return email;
    }

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

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Monster{" +
                "id=" + id +
                ", age=" + age +
                ", birthday=" + birthday +
                ", email='" + email + '\'' +
                ", gender=" + gender +
                ", name='" + name + '\'' +
                ", salary=" + salary +
                '}';
    }
}

5.编写MonsterAnnotation.java接口
package com.sun.mapper;

import com.sun.entity.Monster;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * @author 孙显圣
 * @version 1.0
 */
public interface MonsterAnnotation {
    @Insert("INSERT INTO `monster`(`id`,`age`,`birthday`,`email`,`gender`,`name`,`salaary`) " +
            "VALUES(NULL, #{age}, #{birthday}, #{email}, #{gender}, #{name}, #{salary})")
    public void addMonster(Monster monster);
    @Delete("DELETE FROM `monster` where id = #{id}")
    public void delMonster(Integer id);
    @Update("UPDATE `monster` SET " +
            "`age` = #{age}, `birthday` = #{birthday}, " +
            "`email` = #{email}, `name` = #{name}, `salary` = #{salary} " +
            "WHERE `id` = #{id}")
    public void updateMonster(Monster monster);
    @Select("SELECT * FROM `monster` WHERE id = #{id}")
    public Monster getMonsterById(Integer id);
    @Select("SELECT * FROM `monster`")
    public List<Monster> findAllMonster();

}

6.MyBatisUtils.java
package com.util;

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.InputStream;

/**
 * @author 孙显圣
 * @version 1.0
 */
public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    //使用静态代码块初始化SqlSessionFactory
    static {
        try {
            //获取Mybatis配置文件的输入流
            String resource = "mybatis-config.xml";
            //默认是从类路径下获取资源,在maven中指的就是resources文件夹下,会映射到实际的工作目录
            InputStream resourceAsStream = Resources.getResourceAsStream(resource);
            //读取资源获取SessionFactory,可以理解为连接池
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //编写方法返回SqlSession
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}

7.测试
import com.sun.entity.Monster;
import com.sun.mapper.MonsterAnnotation;
import com.sun.mapper.MonsterMapper;
import com.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;

import java.util.Date;
import java.util.List;

/**
 * @author 孙显圣
 * @version 1.0
 */
public class MonsterAnnotationTest {
    //两个属性
    private SqlSession sqlSession; //相当于连接
    private MonsterAnnotation monsterAnnotation;

    //编写方法完成初始化
    @Before //标注了Before之后表示了在执行目标测试方法前会执行该方法
    public void init() {
        //获取到sqlSession
        sqlSession = MyBatisUtils.getSqlSession();
        //获取到代理对象
        monsterAnnotation = sqlSession.getMapper(MonsterAnnotation.class);
    }

    @Test
    public void addMonster() {
        for (int i = 0; i < 2; i++) {
            Monster monster = new Monster
                    (null, 10 + i, new Date(), "sun@qq.com", 0, "孙显圣", 10.0 + i);
            //代理对象执行接口的方法
            monsterAnnotation.addMonster(monster);
        }
        //如果是增删改还要提交一下事务
        if (sqlSession != null) {
            sqlSession.commit();
            //将连接放回连接池
            sqlSession.close();
        }
        System.out.println("成功");
    }


    @Test
    public void find() {
        List<Monster> allMonster = monsterAnnotation.findAllMonster();
        for (Monster monster : allMonster) {
            System.out.println(monster);
        }
        if (sqlSession != null) {
            //将连接放回连接池
            sqlSession.close();
        }
    }



}

2.注意事项和细节
1.复制sql语句
  • 如果有/n则将这个/n去掉然后替换成空格
  • 如果一行的前面有很多空格,就将这些空格都去掉
2.使用注解方式也要在配置文件中引入这个类!
3.返回自增值(update和insert适用)
  • 自增值对应的列如果与属性名相同则可以省略

MyBatis(注解方式操作)-LMLPHP

4.配置SQL提示

MyBatis(注解方式操作)-LMLPHP

2.MyBatis配置文件详解

1.外部属性文件设置相关的值
1.resources/jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root
2.修改mybatis-config.xml引入外部文件

MyBatis(注解方式操作)-LMLPHP

2.settings配置日志

MyBatis(注解方式操作)-LMLPHP

3.typeAliases配置类型别名

MyBatis(注解方式操作)-LMLPHP

4.environments注册XXXMapper.xml或者含有注解的类

MyBatis(注解方式操作)-LMLPHP

5.pom.xml配置在build的时候要扫描的文件
  <!--在父模块中的pom.xml文件中配置在build的时候要扫描的文件,解决某些类型文件拷贝到target目录失败的问题-->
  <build>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <!--在java文件夹下的多级目录下的xml文件-->
          <include>**/*.xml</include>
        </includes>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <!--在resources文件夹下的多级目录下的xml文件和properties文件-->
          <include>**/*.xml</include>
          <include>**/*.properties</include>
        </includes>
      </resource>
    </resources>
  </build>
04-30 02:53