MyBatis的简单入门

1、什么是MyBatis,解决什么问题?

  1. 如雷贯耳的SSM框架集最后的M指的就是MyBatis
  2. 简单一点说,MyBatis就是能让你用最简单的方法操作数据库;
  3. 再深入一点讲,MyBatis将以前的jdbc操作进行了再次封装;
  4. 简单到什么程度了呢?简单到了sql语句从代码中分离写到配置文件中就行了;

2、如何使用MyBatis

  1. 操作数据库是在Dao层,即各种XxxDao的接口+实现类,MyBatis只需要我们定义接口,他能帮我们实现;
  2. 首先要理解MyBatis的思路,SqlSessionFactoryBuilder–>SqlSessionFactory–>SqlSession
  3. 有了SqlSession,通过SqlSession的getMapper方法得到接口的代理实现类;
  4. 接口定义的各种方法就都可以直接调用了,得到我们想要的数据;

3、代码实现

3.1、xml方式

  1. 创建一个Maven项目,参考官方文档:https://mybatis.org/mybatis-3/zh/getting-started.html
    <?xml version="1.0" encoding="UTF-8"?>
    <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/xsd/maven-4.0.0.xsd">
       <modelVersion>4.0.0</modelVersion>
    
       <groupId>com.yusian</groupId>
       <artifactId>sian-batis</artifactId>
       <version>1.0-SNAPSHOT</version>
       <packaging>jar</packaging>
    
       <dependencies>
           <dependency>
               <groupId>org.mybatis</groupId>
               <artifactId>mybatis</artifactId>
               <version>3.5.6</version>
           </dependency>
           <dependency>
               <groupId>mysql</groupId>
               <artifactId>mysql-connector-java</artifactId>
               <version>5.1.49</version>
           </dependency>
    
           <dependency>
               <groupId>junit</groupId>
               <artifactId>junit</artifactId>
               <version>4.12</version>
               <scope>test</scope>
           </dependency>
       </dependencies>
       <properties>
           <maven.compiler.source>8</maven.compiler.source>
           <maven.compiler.target>8</maven.compiler.target>
       </properties>
    
    </project>
    
  2. 准备数据库及相关表, 如:mybatis库中有一个tab_user表,该表只有id,username,password三个字段

  3. 准备实体类User

    package com.yusian.domain;
    
    import java.io.Serializable;
    
    public class User implements Serializable {
       private Integer id;
       private String username;
       private String password;
    
       public Integer getId() {
           return id;
       }
    
       public void setId(Integer id) {
           this.id = id;
       }
    
       public String getUsername() {
           return username;
       }
    
       public void setUsername(String username) {
           this.username = username;
       }
    
       public String getPassword() {
           return password;
       }
    
       public void setPassword(String password) {
           this.password = password;
       }
    
       @Override
       public String toString() {
           return "User{" +
                   "id='" + id + '\'' +
                   ", username='" + username + '\'' +
                   ", password='" + password + '\'' +
                   '}';
       }
    }
    
    
  4. 准备接口UserDao,接口中有一个findAll的方法查询所有用户数据
    package com.yusian.dao;
    
    import com.yusian.domain.User;
    import org.apache.ibatis.annotations.Select;
    
    import java.util.List;
    
    public interface UserDao {
       /**
        * 获取所有用户列表
        * @return
        */
       List<User> findAll();
    }
    
    
  5. 在Resources的根目录下创建SqlMapConfig.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>
       <environments default="development">
           <environment id="development">
               <transactionManager type="JDBC"/>
               <dataSource type="POOLED">
                   <property name="driver" value="com.mysql.jdbc.Driver"/>
                   <property name="url" value="jdbc:mysql://数据库地址:3306/mybatis?useSSL=false"/>
                   <property name="username" value="root"/>
                   <property name="password" value="******"/>
               </dataSource>
           </environment>
       </environments>
       <!--指定映射配置文件的位置-->
       <mappers>
           <mapper resource="com/yusian/dao/UserDao.xml"/>
       </mappers>
    </configuration>
    
  6. 在Resources目录下创建com/yusian/dao三层目录,再创建UserDao.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.yusian.dao.UserDao">
       <select id="findAll" resultType="com.yusian.domain.User">
           select * from tab_user
       </select>
    </mapper>
    
  7. 测试
    public class MyBatisTest {
       public static void main(String[] args) throws Exception{
           // 1、创建SqlSessionFactoryBuilder
           SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
           // 2、加载配置文件生成SqlSessionFactory对象
           InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
           SqlSessionFactory factory = builder.build(is);
           // 3、factory生成SqlSession对象
           SqlSession sqlSession = factory.openSession();
           // 4、SqlSession生成代理实现类
           UserDao userDao = sqlSession.getMapper(UserDao.class);
           // 5、操作数据库获取数据
           List<User> users = userDao.findAll();
           for (User user : users) {
               System.out.println(user);
           }
           // 6、释放资源
           is.close();
           sqlSession.close();
       }
    }
    

3.2、注解方式

注解的方式与xml的区别在于:

  1. 删除xml文件,否则会有干扰,MyBais会优先加载xml文件;

  2. SqlMapConfig.xml文件中最后面的<mapper>标签中resource属性改成class属性

    <?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>
       <environments default="development">
           <environment id="development">
               <transactionManager type="JDBC"/>
               <dataSource type="POOLED">
                   <property name="driver" value="com.mysql.jdbc.Driver"/>
                   <property name="url" value="jdbc:mysql://数据库地址:3306/mybatis?useSSL=false"/>
                   <property name="username" value="root"/>
                   <property name="password" value="******"/>
               </dataSource>
           </environment>
       </environments>
       <!--指定映射配置文件的位置-->
       <mappers>
           <mapper class="com.yusian.dao.UserDao"/>
       </mappers>
    </configuration>
    
  3. 接口类中方法上添加Select注释,注释属性为sql语句
    package com.yusian.dao;
    
    import com.yusian.domain.User;
    import org.apache.ibatis.annotations.Select;
    
    import java.util.List;
    
    public interface UserDao {
       /**
        * 获取所有用户列表
        * @return
        */
       @Select("select * from tab_user")
       List<User> findAll();
    }
    
    
  4. 其他都一样,没有区别

发表评论

邮箱地址不会被公开。 必填项已用*标注

Captcha Code