MyBatis 增删改查

简介

什么是 MyBatis?

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

整体目录

MyBatis 增删改查

 

 

安装

要使用 MyBatis, 只需将 mybatis-x.x.x.jar 文件置于类路径(classpath)中即可。

如果使用 Maven 来构建项目,则需将下面的依赖代码置于 pom.xml 文件中:

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

 

我们使用的是 postgresql 因此我们还需要导入postgresql驱动

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.2.5</version>
</dependency>

 

mybatis-config.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>
<!--  引入配置变量  -->
    <properties resource="db.properties"/>

<!--    打印日志-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

<!--  类型别名  -->
    <typeAliases>
        <typeAlias type="com.shang.pojo.User" alias="User"/>
    </typeAliases>

<!--  链接数据库配置  -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <!--                <property name="url" value="jdbc:postgresql://10.44.99.84:62432/situation?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>-->
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

<!--  映射器  -->
    <mappers>
        <mapper resource="com/shang/dao/UserMapper.xml"/>
    </mappers>

</configuration>

 

 db.properties文件:

driver=org.postgresql.Driver
url=jdbc:postgresql://11.44.99.33:62432/situation?useUnicode=true&amp;characterEncoding=UTF-8
username=postgres1
password=36o%Situation2011

User文件:

package com.shang.pojo;

import org.apache.ibatis.type.Alias;

// 数据库映射
public class User {
    public int id;
    public String name;
    public int password;

    public User() {
    }

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

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

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getPassword() {
        return password;
    }

    public void setPassword(int password) {
        this.password = password;
    }
}

 

MybatisUtils文件:

package com.shang.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 MybatisUtils {

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

}

UserMapper文件:

package com.shang.dao;

import com.shang.pojo.User;

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

public interface UserMapper {
    List<User> getUserList();

    int addUser(Map<String, Object> map);

    int delUser(Map<String, Object> map);

    int updateUser(Map<String, Object> map);

    List<User> getLikeUser(Map<String, Object> map);
}

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="com.shang.dao.UserMapper">

<!--    字段映射    -->
    <resultMap id="UserMapper" type="User">
        <result property="password" column="pwd"/>
    </resultMap>

    <insert id="addUser" parameterType="map">
        INSERT INTO t_user (id, name, pwd)
        VALUES (#{id}, #{name}, #{pwd});
    </insert>

    <delete id="delUser" parameterType="map">
        DELETE
        FROM t_user
        WHERE id = #{id};
    </delete>

    <update id="updateUser" parameterType="map">
        UPDATE t_user
        SET name=#{name},
            pwd=#{pwd}
        WHERE id = #{id};
    </update>

    <select id="getUserList" resultMap="UserMapper">
        SELECT *
        FROM t_user;
    </select>

    <select id="getLikeUser" resultMap="UserMapper" parameterType="map">
        SELECT *
        FROM t_user
        WHERE name LIKE #{name};
    </select>

</mapper>

UserMapperTest文件:

package com.shang.dao;

import com.shang.pojo.User;
import com.shang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

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

public class UserMapperTest {

    @Test
    public void test() {


        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        List<User> userList = mapper.getUserList();

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

        sqlSession.close();

    }

    @Test
    public void addUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id",2);
        map.put("name","222");
        map.put("pwd","222");
        mapper.addUser(map);

        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void delUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();

        stringObjectHashMap.put("id", 2);

        mapper.delUser(stringObjectHashMap);


        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void updateUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();

        stringObjectHashMap.put("id", 2);
        stringObjectHashMap.put("name", "223");
        stringObjectHashMap.put("pwd", "223");

        mapper.updateUser(stringObjectHashMap);

        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void getLikeUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();

        stringObjectHashMap.put("name", "2");

        List<User> likeUser = mapper.getLikeUser(stringObjectHashMap);

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

        sqlSession.commit();
        sqlSession.close();
    }

}

XML配置丢失可以配置

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

 

上一篇:chrome浏览器开发者工具F12中某网站的sources下的源码如何批量保存?


下一篇:Mybatis入门