Mybatis增删改查数据库

1.新建一个maven项目,配置第三方库

<?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>Mybatis03</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>Mybatis11</module>
    </modules>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>
    </dependencies>

</project>

2.编写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"/>

    <!--起别名-->
    <typeAliases>
        <typeAlias type="com.kuang.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="jdbc:mysql://localhost:3306/mybatis?useLegacyDatetimeCode=false&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="userMapper.xml"/>
    </mappers>
</configuration>

3.编写工具类

package com.kuang.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 resoure ="mybatis-config.xml";
            InputStream resourceAsStream = Resources.getResourceAsStream(resoure);
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

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

4.编写实体类

package com.kuang.pojo;

import org.apache.ibatis.type.Alias;

//注解起别名
//@Alias("Hello1")
public class User {
    private int id;
    private String name;
    private String pwd;

    public User() {
    }

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

    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 String getPwd() {
        return pwd;
    }

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

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

5.编写接口

package com.kuang.dao;

import java.util.List;
import com.kuang.pojo.User;


public interface UserDao {
    //查询全部用户
    List<User> getUserList();
    //根据id查询用户
    User getUserById(int id);
    //insert一个用户
    int addUser(User user);
    //update一个用户
    int updatUser(User user);
    //删除一个用户
    int deleteUser(int id);
}

6.编写接口实现mapper

<?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.kuang.dao.UserDao">
    <select id="getUserList" resultType="com.kuang.pojo.User">
        select * from mybatis.user
    </select>

    <select id="getUserById" parameterType="int" resultType="User">
        select * from mybatis.user where id = #{id}
    </select>
    <!--parameterType表示参数类型-->
    <insert id="addUser" parameterType="com.kuang.pojo.User">
        insert into mybatis.user (id, name, pwd) value (#{id},#{name},#{pwd})
    </insert>

    <update id="updatUser" parameterType="com.kuang.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>

7.编写测试单元测试

package com.kuang.dao;

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

import java.util.List;


public class UserDaoTest {
    @Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSessiong();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }

    //查询一个用户
    @Test
    public void getUserId(){
        SqlSession sqlSession = MybatisUtils.getSqlSessiong();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User userById = userDao.getUserById(1);
        System.out.println(userById);
        sqlSession.close();
    }
    //新增一个用户
    @Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSessiong();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        int i = userDao.addUser(new User(7, "dd", "wang"));
        if(i>0){
            System.out.println("插入成功!");
        }
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

    //update一个用户
    @Test
    public void updateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSessiong();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        int i = userDao.updatUser(new User(1, "dd", "wang"));
        if(i>0){
            System.out.println("更新成功!");
        }
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void deleteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSessiong();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        int i = userDao.deleteUser(1);
        if(i>0){
            System.out.println("删除成功!");
        }
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void tee(){
        System.out.println("ttt");
    }

}

Mybatis增删改查数据库

 

上一篇:每天一个Linux命令:pwd


下一篇:Linux命令系列之 - 路径切换和查看cd - pwd - ls - find