MyBatis的基本使用

Terwer 后端开发 MyBatis评论167字数 5327阅读17分45秒阅读模式
摘要

本文介绍了使用MyBatis进行数据库操作的开发步骤,包括添加MyBatis坐标、创建user数据表、编写User实体类和映射文件UserMapper.xml。通过示例代码展示了相关配置和SQL操作,帮助开发者快速入门MyBatis。

快速入门

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 实体类

/**
 * 用户信息
 *
 * @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 + '\'' +
                '}';
    }
}

编写映射⽂件 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>

编写测试类

@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

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
    /**
     * 用户Dao层接口
     *
     * @name: IUserDao
     * @author: terwer
     * @date: 2022-03-16 20:53
     **/
    public interface IUserDao {
        /**
         * 查询所有用户
         */
        public List<User> findAll() throws IOException;
    }
    
  2. DaoImpl 实现文章源自浅海拾贝-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;
        }
    }
    
  3. 测试文章源自浅海拾贝-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);
        }
    }
    

代理开发方式

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

// ===============
// 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);
  }
}

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

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

2022/05/08 feat: 初稿 文章源自浅海拾贝-https://blog.terwergreen.com/basic-use-of-mybatis.html

本文介绍了使用MyBatis进行数据库操作的开发步骤,包括添加MyBatis坐标、创建user数据表、编写User实体类和映射文件UserMapper.xml。通过示例代码展示了相关配置和SQL操作,帮助开发者快速入门MyBatis。文章源自浅海拾贝-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: