Mybatis基本流程实现

一:maven导包(一个连接包、一个mybatis包,一个测试包)

<dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

二:配置mybatis-config、do.properties文件,进行数据库连接

<?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="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/ma/dao/UserMapper.xml"/>
    </mappers>

</configuration>
View Code
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8
username=root
password=1234
View Code

三:要用工具去使用mybatis里面的东西,而这个“工具”写成代码后,是固定的,所以可以封装成一个工具类

package com.ma.utils;

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;

public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory;
    static{
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream= Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

使用方法为:调用这个工具类,去找到相应的mapper类,对对应的数据表进行操作,如下例子:

public void test(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserMapper userDao = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userDao.getUserList();
        for(User user:userList){
            System.out.println(user);
        }
        sqlSession.close();
    }

四:(1)数据库情况

 

 

(2)编写bean(pojo)类 

package com.ma.pojo;

public class User {
    private int id;
    private String name;
    private String pwd;

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }
    public User(){

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

    public String getName() {
        return name;
    }

    public int getId() {
        return id;
    }

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

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

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
}
View Code

(3)编写dao类,以及实现增删改查的xml文件

package com.ma.dao;

import com.ma.pojo.User;

import java.util.List;
import java.util.Map;

public interface UserMapper {
    List<User> getUserList();
    List<User> getUserLike(String value);
    User getUserById(int id);
    int addUser(User user);
    int updateUser(User user);
    int deleteUser(int id);
    int addUser2(Map<String, Object> map);

}
View Code
<?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.ma.dao.UserMapper">

    <!--映射之后的User&#45;&#45;com.ma.pojo.User-->
   <!-- <select id="getUserList" resultType="hello">-->
    <select id="getUserList" resultType="User">
        select * from mybatis.user
     </select>

    <select id="getUserLike" resultType="com.ma.pojo.User">
        select * from mybatis.user where name like "%"#{value}"%";
    </select>

    <select id="getUserById" parameterType="int" resultType="com.ma.pojo.User">
        select * from mybatis.user where id = #{id};
    </select>
    
    <insert id="addUser" parameterType="com.ma.pojo.User">
        insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd});
    </insert>

   <!-- map用法,可以随意给某赋值,然后其他值不定义-->
    <!--<insert id="addUser2" parameterType="map">
        insert into mybatis.user (id, name, pwd) values (#{userid},#{userName},#{passWord});
    </insert>-->
    
    <update id="updateUser" parameterType="com.ma.pojo.User">
        update mybatis.user set name = #{name}, pwd = #{pwd} where id = #{id};
    </update>

    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id =#{id};
    </delete>
</mapper>
View Code

其中,除了sql语句之外,<mapper namespace="com.ma.dao.UserMapper">也是需要有对应关系,比如studentmapper对应studentmapper.xml

而这里是Usermapper对应Usermapper.xml

注(对应的xml文件的命名最好与其相同)

 五:测试

 public void test(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserMapper userDao = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userDao.getUserList();
        for(User user:userList){
            System.out.println(user);
        }
        sqlSession.close();
    }

但是,这样子去测试的话,是会报错的,我们需要在mybatis-config中对每一个mapper进行配置

<mappers>
        <mapper resource="com/ma/dao/UserMapper.xml"/>
    </mappers>

六:以上操作完毕之后,还是会报错,我们需要在pom中增加一个内容,如下:

<build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
View Code

 

posted @ 2021-05-25 09:55  古比  阅读(111)  评论(0编辑  收藏  举报