欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MyBatis新手教程,附代码和解析。

程序员文章站 2022-09-20 12:42:00
1.新建一个maven项目,并配置pom.xml。

1.新建一个maven项目,并配置pom.xml。

<?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>org.example</groupId>
    <artifactId>MyBatis</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <!--1.MyBatis 3.4.5-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <!--2.mysql 8.0.12-->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.12</version>
        </dependency>
        <!--3.log4j-->
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
</project>

2.建立如下图的项目结构
MyBatis新手教程,附代码和解析。
其中:admin.class源码为:
也就是你要操作的数据库的映射bean(ORM)

public class admin {
    private int id;
    private String username;
    private String password;

    public admin() {
    }

    public admin(int id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public int getId() {
        return id;
    }

    public void setId(int 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 "admin{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

3.DAO层中的adminMapper:

/*用户持久层接口*/
public interface daoMapper {
    /*查询所有操作*/
    List<admin> findAll();
}

4.新建一个SqlMapConfig.xml放在resource目录下

<?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">
<!--mybatis的主配置文件-->
<configuration>
    <!--1.配置环境-->
    <environments default="mysql">
        <!--2.配置mysql的环境,注意default=mysql&id 是相同的-->
        <environment id="mysql">
            <!--3.配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!--4.配置数据源(也叫连接池)-->
            <dataSource type="POOLED">
                <!--5.配置连接池的四个基本属性-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value=""/>
                <property name="user" value=""/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
    <!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
    <mappers>
        <mapper resource="com/young/dao/adminMapper.xml"></mapper>
    </mappers>
</configuration>

5.新建一个jdbc.proerties

url= jdbc:mysql://localhost:3306/db_hotel?useUnicode=true&characterEncoding=UTF-8\
driver=com.mysql.cj.jdbc.Driver
user=root
password=123

6.在resource 目录下新建com/young/dao/adminMapper.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.young.dao.adminMapper">
    <select id="findAll">
        select * from user
    </select>
</mapper>

7.引入log4j

# rootLogger\u662F\u6240\u6709\u65E5\u5FD7\u7684\u6839\u65E5\u5FD7,\u4FEE\u6539\u8BE5\u65E5\u5FD7\u5C5E\u6027\u5C06\u5BF9\u6240\u6709\u65E5\u5FD7\u8D77\u4F5C\u7528
# \u4E0B\u9762\u7684\u5C5E\u6027\u914D\u7F6E\u4E2D,\u6240\u6709\u65E5\u5FD7\u7684\u8F93\u51FA\u7EA7\u522B\u662Finfo,\u8F93\u51FA\u6E90\u662Fcon
log4j.rootLogger=debug,con
# \u5B9A\u4E49\u8F93\u51FA\u6E90\u7684\u8F93\u51FA\u4F4D\u7F6E\u662F\u63A7\u5236\u53F0
log4j.appender.con=org.apache.log4j.ConsoleAppender
# \u5B9A\u4E49\u8F93\u51FA\u65E5\u5FD7\u7684\u5E03\u5C40\u91C7\u7528\u7684\u7C7B
log4j.appender.con.layout=org.apache.log4j.PatternLayout
# \u5B9A\u4E49\u65E5\u5FD7\u8F93\u51FA\u5E03\u5C40
log4j.appender.con.layout.ConversionPattern=%d{MM-dd HH:mm:ss}[%p]%c%n -%m%n

8.编写测试类

package com.young.dao;

import com.young.domain.admin;
import org.apache.ibatis.annotations.Delete;
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 org.apache.log4j.lf5.util.Resource;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import static org.junit.Assert.*;

/**
 * Create by wuyang9769@163.com
 * Decorate:
 *
 * @author young_wu
 * @date 2020/11/27 0027 0:28
 * You can't be killed, it will only make you stronger
 */
public class daoMapperTest {
    @Test
    public void test() throws IOException {
        //1.读取配置文件
        InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = sqlSessionFactoryBuilder.build(is);
        //3.使用工厂生产SqlSession对象
        SqlSession sqlSession = build.openSession();
        //4.使用SqlSession创建Dao接口的代理对象
        daoMapper mapper = sqlSession.getMapper(daoMapper.class);
        //5.使用代理对象执行方法
        List<admin> all = mapper.findAll();
        for(admin admin : all){
            System.out.println(admin);
        }
        //6.释放资源
        sqlSession.close();
        is.close();

    }
}

成功!

本文地址:https://blog.csdn.net/young_qin/article/details/110210657