MyBatis增删改——idea

1、创建maven工程,并创建对应包,类,接口,配置文件

MyBatis增删改——idea

2、pom.xml导入jar包依赖

 <dependencies>
<!--        mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
<!--mybatis所需jar包-->
        <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>
<!--    解决资源导不出问题-->
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>
复制代码

3、配置mybatis-config配置文件

<?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>
<!--        1、可以给实体类起别名,实体类少使用-->
<!--        <typeAlias type="pojo.User" alias="User"/>-->
<!--        2、可以给实体类起别名,默认别名为类名首字母小写
            若有注解,则以注解为别名-->
        <package name="pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
<!--            连接数据库,数据库使用的是mysql8.0-->
            <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>

<!--    绑定配置资源,注册mapper,每一个都需要注册-->
    <mappers>
<!--       1、 resources绑定需要使用路劲,推荐使用-->
        <mapper resource="dao/UserMapper.xml"/>

<!--       2、 使用class绑定注册
        接口和mapper配置文件必须同名
        接口和mapper必须在同一包下
       <mapper class="dao.UserMapper"/>
-->

<!--        3、使用包扫描进行注册
        接口和mapper配置文件必须同名
        接口和mapper必须在同一包下
       <package name="dao"/>
-->
    </mappers>


</configuration>
复制代码

4、配置db.properties文件

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
username=数据库用户名
password=数据库密码
复制代码

5、编写工具类MyBatisUntil

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 MyBatisUntil {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    //创建sqlSession对象
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
复制代码

6、创建数据库表,以及对应实体类

create table user(

id integer auto_increment PREPARE key,

name varchar(20),

pwd varchar(20)

);

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", 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;
    }

    public User() {
    }

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

7、创建接口

package dao;

import pojo.User;

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

public interface UserMapper {

    //获取全部用户
    List<User> getUserList();

    //根据id查询用户
    User getUserById(int id);

    //添加用户
    public int AddUser(User user);

    //修改用户
    int updateUser(User user);

    //删除用户
    int deleteUser(int id);



}
复制代码

8、创建对应接口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接口,此处绑定UserDao接口-->
<mapper namespace="dao.UserMapper">
<!--    查询语句,id对应UserDao方法名字,resultType为全类名-->
<!--    User起别名后,直接用别名-->
    <select id="getUserList" resultType="user">
        select * from user
    </select>
    
<!--parameterType参数类型-->
    <select id="getUserById" parameterType="int" resultType="pojo.User">
        select * from user where id = #{id}
    </select>

    <insert id="AddUser" parameterType="pojo.User" >
        insert into user (id,name ,pwd) values (#{id},#{name},#{pwd})
    </insert>

    <update id="updateUser" parameterType="pojo.User">
        update user set name=#{name },pwd=#{pwd} where id=#{id}
    </update>

    <delete id="deleteUser" parameterType="int">
        delete from user where id=#{id}
    </delete>
</mapper>
复制代码

9、到mybatis-config配置文件中注册UserMapper

    <mappers>
<!--       1、 resources绑定需要使用路劲,推荐使用-->
        <mapper resource="dao/UserMapper.xml"/>

<!--       2、 使用class绑定注册
        接口和mapper配置文件必须同名
        接口和mapper必须在同一包下
       <mapper class="dao.UserMapper"/>
-->

<!--        3、使用包扫描进行注册
        接口和mapper配置文件必须同名
        接口和mapper必须在同一包下
       <package name="dao"/>
-->
    </mappers>
复制代码

10、创建测试类

package dao;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import pojo.User;
import until.MyBatisUntil;

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

public class UserDaoTest {
    @Test
    public void test1(){
        //获取sqlSession对象
        SqlSession sqlSession = MyBatisUntil.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 test2(){
        SqlSession sqlSession = MyBatisUntil.getSqlSession();
        //获取类mapper接口
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        System.out.println(mapper.getUserById(1));

        sqlSession.close();
    }

    //增删改要提交事务
    @Test
    public void test3(){
        SqlSession sqlSession = MyBatisUntil.getSqlSession();

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

        int res = mapper.AddUser(new User(4, "小小", "12345"));

        //提交事务,不能漏掉
        sqlSession.commit();

        sqlSession.close();
    }

    @Test
    public void test4(){
        SqlSession sqlSession = MyBatisUntil.getSqlSession();

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

        mapper.updateUser(new User(4,"小睡","2323"));

        sqlSession.commit();

        sqlSession.close();
    }

    @Test
    public void test5(){
        SqlSession sqlSession = MyBatisUntil.getSqlSession();

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

        mapper.deleteUser(4);

        sqlSession.commit();

        sqlSession.close();

    }

}
复制代码

完工

 

上一篇:安装docker并使用docker安装mysql


下一篇:mysqld: Can‘t read dir of ‘/etc/mysql/conf.d/‘ (Errcode: 13 - Permission denied)