MyBatis的基本使用

Terwer 后端开发 MyBatis评论38字数 6872阅读22分54秒阅读模式

快速入门

Mybatis的官网:https://mybatis.org/mybatis-3/文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

MyBatis的开发步骤

添加MyBatis的坐标

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
    <java.version>1.8</java.version>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependencies>
    <!--mybatis坐标-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.5</version>
    </dependency>
    <!--mysql驱动坐标-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
        <scope>runtime</scope>
    </dependency>
    <!--单元测试坐标-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <!--⽇志坐标-->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.12</version>
    </dependency>
</dependencies>

创建user数据表

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;

INSERT INTO `user` VALUES ('1', '小唐', '123');
INSERT INTO `user` VALUES ('2', '小张', '456');
INSERT INTO `user` VALUES ('3', '小雨', '789');

编写User实体类

文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

/**
 * 用户信息
 *
 * @name: User
 * @author: terwer
 * @date: 2022-05-08 11:32
 */
class User {
    var id: Int? = null
    var username: String? = null
    override fun toString(): String {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                '}'
    }
}

文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

/**
 * 用户信息
 *
 * @name: User
 * @author: terwer
 * @date: 2022-03-15 11:32
 **/
public class User {
    private Integer id;
    private String username;

    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;
    }

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

文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

编写映射⽂件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="user">
    <select id="findAll" resultType="com.test.pojo.User">
        select * from user
    </select>
</mapper>

编写核⼼⽂件SqlMapConfig.xml

<!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">
            <!-- 当前事务交给JDBC -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 当前只用MyBatis提供的连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/zdy_mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>

编写测试类

文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

@Test
@Throws(IOException::class)
fun test1() {
    val resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml")
    val sqlSessionFactory = SqlSessionFactoryBuilder().build(resourceAsStream)
    val sqlSession = sqlSessionFactory.openSession()
    val userList = sqlSession.selectList<User>("user.findAll")
    for (user in userList) {
        println(user)
    }

    // 关闭资源
    sqlSession.close()
}

文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

@Test
public void test1() throws IOException {
    InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

    SqlSession sqlSession = sqlSessionFactory.openSession();
    List<User> userList = sqlSession.selectList("user.findAll");
    for (User user : userList) {
        System.out.println(user);
    }

    // 关闭资源
    sqlSession.close();
}

文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

运行结果文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

MyBatis的基本使用文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

乱码解决文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

修改url为文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

jdbc:mysql://localhost:3306/zdy_mybatis?characterEncoding=utf8

效果文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

MyBatis的基本使用文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

完善,添加新增方法文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

<!-- 添加用户
parameterType:参数类型
-->
<insert id="saveUser" parameterType="com.terwergreen.pojo.User">
insert into user(id, username) values(#{id}, #{username})
</insert>

MyBatis的基本使用文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

没有添加成功原因文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

未提交事务文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

解决文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

sqlSession.insert("user.saveUser", user);
sqlSession.commit();

MyBatis的基本使用文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

更新文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

<!-- 修改 -->
  <update id="updateUser" parameterType="com.terwergreen.pojo.User">
  update user set username=#{username} where id=#{id}
</update>

MyBatis的基本使用文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

删除文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

<!-- 删除 -->
<update id="deleteUser" parameterType="java.lang.Integer">
delete from user where id=#{id}
</update>

MyBatis的基本使用文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

备注:只有一个参数的时候,参数名的占位符可以是任意字符,例如下面的语句也是正常的文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

<!-- 删除 -->
<update id="deleteUser" parameterType="java.lang.Integer">
delete from user where id=#{abc}
</update>

MyBatis的Dao层实现

传统开发方式

  1. 定义Dao层接口

    文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

    文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

    /**
     * 用户Dao层接口
     *
     * @name: IUserDao
     * @author: terwer
     * @date: 2022-05-08 20:53
     */
    interface IUserDao {
        /**
         * 查询所有用户
         */
        @Throws(IOException::class)
        fun findAll(): List<User?>?
    }
    

    文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

    文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

    /**
     * 用户Dao层接口
     *
     * @name: IUserDao
     * @author: terwer
     * @date: 2022-03-16 20:53
     **/
    public interface IUserDao {
        /**
         * 查询所有用户
         */
        public List<User> findAll() throws IOException;
    }
    

    文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

    文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

  2. DaoImpl实现文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

    文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

    文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

    /**
     * 用户Dao层实现类
     *
     * @name: UserDaoImpl
     * @author: terwer
     * @date: 2022-05-08 20:54
     */
    class UserDaoImpl : IUserDao {
        @Throws(IOException::class)
        override fun findAll(): List<User> {
            val resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml")
            val sqlSessionFactory = SqlSessionFactoryBuilder().build(resourceAsStream)
            val sqlSession = sqlSessionFactory.openSession()
            val userList = sqlSession.selectList<User>("user.findAll")
    
            // 关闭资源
            sqlSession.close()
            return userList
        }
    }
    

    文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

    文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

    /**
     * 用户Dao层实现类
     *
     * @name: UserDaoImpl
     * @author: terwer
     * @date: 2022-03-16 20:54
     **/
    public class UserDaoImpl implements IUserDao {
        @Override
        public List<User> findAll() throws IOException {
            InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    
            SqlSession sqlSession = sqlSessionFactory.openSession();
            List<User> userList = sqlSession.selectList("user.findAll");
    
            // 关闭资源
            sqlSession.close();
            return userList;
        }
    }
    

    文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

    文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

  3. 测试文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

    文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

    文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

    // ===============
    // Dao层常规方式
    @Test
    @Throws(IOException::class)
    fun test5() {
        val userDao: IUserDao = UserDaoImpl()
        val userList = userDao.findAll()
        for (user in userList) {
            println(user)
        }
    }
    

    文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

    文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

    @Test
    public void test5() throws Exception{
        IUserDao userDao = new UserDaoImpl();
        List<User> all = userDao.findAll();
    
        for (User user : all) {
            System.out.println(user);
        }
    }
    

    文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

    文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

代理开发方式

Mapper 接口开发方法只需要程序员编写Mapper 接口(相当于Dao 接口),由Mybatis 框架根据接口定义创建接文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

Mapper 接口开发需要遵循以下规范:文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

1) Mapper.xml文件中的namespacemapper接口的全限定名相同文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

2) Mapper接口方法名和Mapper.xml中定义的每个statementid相同文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

3) Mapper接口方法的输入参数类型和mapper.xml中定义的每个sqlparameterType的类型相同文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

4) Mapper接口方法的输出参数类型和mapper.xml中定义的每个sqlresultType的类型相同文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

编写UserMapper接口文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

MyBatis的基本使用文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

测试代理方式文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

// ===============
// Dao层代理开发方式
@Test
@Throws(IOException::class)
fun test5() {
    val resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml")
    val sqlSessionFactory = SqlSessionFactoryBuilder().build(resourceAsStream)
    val sqlSession = sqlSessionFactory.openSession()
    val userDao = sqlSession.getMapper(IUserDao::class.java)
    val userList = userDao.findAll()
    for (user in userList) {
        println(user)
    }
}

文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

// ===============
// Dao层代理开发方式
@Test
public void test5() throws IOException {
  InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

  SqlSession sqlSession = sqlSessionFactory.openSession();
  IUserDao userDao = sqlSession.getMapper(IUserDao.class);

  List<User> userList = userDao.findAll();

  for (User user : userList) {
    System.out.println(user);
  }
}

文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

MyBatis的基本使用文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

文章更新历史
2022/05/08 feat:新增Kotlin支持 文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html
相关文章
  • 扫码加我微信
  • 验证消息请输入:来自你的博客
  • weinxin
  • 我的微信公众号
  • 微信扫一扫与我交流吧
  • weinxin
Terwer
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: