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

SSM之Mybatis_ch1——入门

程序员文章站 2022-06-28 07:59:19
SSM之Mybatis_ch1准备工作数据库方面新建数据库mybatis,并创建user表。CREATE DATABASE IF NOT EXISTS `mybatis`;USE `mybatis`;CREATE TABLE `user` ( `id` int PRIMARY KEY,`name` VARCHAR(100) NOT NULL,`pwd` VARCHAR(100) NOT NULL) ENGINE=INNODB DEFAULT CHARSET=utf8;向其中插入数...

SSM之Mybatis_ch1

准备工作

数据库方面

新建数据库mybatis,并创建user表。

CREATE DATABASE IF NOT EXISTS `mybatis`;

USE `mybatis`;

CREATE TABLE `user` ( 
`id` int PRIMARY KEY,
`name` VARCHAR(100) NOT NULL,
`pwd` VARCHAR(100) NOT NULL
) ENGINE=INNODB DEFAULT CHARSET=utf8;

向其中插入数据

INSERT INTO `user` VALUES
(1,'reflect111','pwd123456'),
(2,'reflect222','pwd123456'),
(3,'reflect333','pwd123456'),
(4,'reflect444','pwd123456'),
(5,'reflect555','pwd123456');

IDEA方面

1.新建Maven项目

File -> New -> Project -> Maven

取名为Mybatis_ch1,groupId可更改,如com.study

2.添加所需依赖

打开浏览器搜索Maven Repository,分别搜索mybatis和mysql

打开pom.xml文件,将Mybatis和MySQL的依赖导入,以及junit单元测试

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.6</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.21</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

3.新建所需的包和类

SSM之Mybatis_ch1——入门

开始测试

1.在pojo包下新建实体类User.java

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 + '\'' +
                '}';
    }
}

2.在Mapper包下新建一个mapper所对应的接口:UserMapper.java

public interface UserMapper {

    // 查询全部用户
    List<User> getUserList();
}

3.在UserMapper接口的同一位置新建UserMapper.xml(此处即在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">

<!--namespace绑定一个对应的mapper接口-->
<mapper namespace="com.reflect.mapper.UserMapper">

<!--    每个select/insert/update/delete的id都对应mapper接口中的方法名-->
<!--    resultType:sql执行后返回值的类型-->
<!--    resultMap:sql执行后返回的不止一个元素,需要对齐自定义解释-->
    <select id="getUserList" resultType="com.reflect.pojo.User">
        select * from mybatis.user
    </select>
</mapper>

4.新建Mybatis的工具类,避免以后繁琐进行SqlSession的创建

/**
 * 建议将Mybatis打开SqlSession这一操作
 * 直接在静态方法块中加载配置文件,
 * 最后使用静态方法对外返回(暴露)SqlSession
 */
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();
    }
}

5.新建mybatis配置文件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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <!--此处url记得换成localhost,或者自己虚拟机所在的ip-->
                <property name="url" value="jdbc:mysql://192.168.199.131:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <!--此处注意换成自己的mysql密码-->
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
<!--    此处的resource要注意是'/',而不是'.'-->
    <mappers>
        <mapper resource="com/reflect/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

6.最后新建测试类MyTest

public class MyTest {

    // 查询全部用户
    @Test
    public void getUserList() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        try {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> userList = mapper.getUserList();
            for (User user : userList) {
                System.out.println(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }
}

7.测试运行

单击@Test左边的绿色按钮运行,或者直接右键运行测试

最后得到的结果如下所示,即代表成功

SSM之Mybatis_ch1——入门

8.错误分析

①出现如下所示,一般是Test类中对应的getUserListUserMapper.xml未找到对应方法,即UserMapper.xml中的id不正确,请确定与UserMapper.java中的方法名一致。

SSM之Mybatis_ch1——入门

SSM之Mybatis_ch1——入门

SSM之Mybatis_ch1——入门

②出现如下所示,一般是mybatis-config.xml中的数据库配置不正确,导致数据库无法正确连接,特别是url一定要注意修改。

SSM之Mybatis_ch1——入门

测试总结

以上就是我重归SSM学习回顾mybatis的第一次测试。

接下来就不细说了,直接上我我第一次所写的所有代码了。有兴趣的朋友可以对着自己动手做做,只要修改了我上面所说的地方,都能成功。

全部代码

1.实体类User.java

package com.reflect.pojo;

/**
 * author: Administrator
 * date: 2020/12/30 - 10:08
 */
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 + '\'' +
                '}';
    }
}

2.映射接口UserMapper.java

package com.reflect.mapper;

import com.reflect.pojo.User;

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

/**
 * author: Administrator
 * date: 2020/12/30 - 10:18
 */

/**
 * 通过Mapper接口来写需要执行的操作
 * 映射到Mapper.xml来执行sql语句
 */
public interface UserMapper {

    // 查询全部用户
    List<User> getUserList();

    // 查询单个用户
    User getUser(int id);

    // 新增一个用户
    boolean insertUser(User user);

    // 修改一个用户
    boolean updateUser(User user);

    // 删除一个用户
    boolean deleteUser(int id);

    // 万能Map???
    User getMapUser(Map<String,Object> map);
    boolean insertMapUser(Map<String,Object> map);
    boolean updateMapUser(Map<String,Object> map);
    boolean deleteMapUser(Map<String,Object> map);

    // 模糊查询
    List<User> getUserLike(String vale);

}

3.Mapper文件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">

<!--namespace绑定一个对应的mapper接口-->
<mapper namespace="com.reflect.mapper.UserMapper">

<!--    每个select/insert/update/delete的id都对应mapper接口中的方法名-->
<!--    resultType:sql执行后返回值的类型-->
<!--    resultMap:sql执行后返回的不止一个元素,需要对齐自定义解释-->
    <select id="getUserList" resultType="com.reflect.pojo.User">
        select * from mybatis.user
    </select>

<!--    #{}可防止sql注入、推荐使用,${}一般不推荐使用-->
    <select id="getUser" parameterType="int" resultType="com.reflect.pojo.User">
        select *
        from mybatis.user where id = #{id};
    </select>

<!--    parameterType:sql语句的参数类型-->
    <insert id="insertUser" parameterType="com.reflect.pojo.User">
        insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd})
    </insert>

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

    <delete id="deleteUser" parameterType="com.reflect.pojo.User">
        delete from mybatis.user where id=#{id}
    </delete>
    
<!--    万能Map合集-->
<!--    参数可以自定义,此处将参数id改为reflect为例-->
    <select id="getMapUser" parameterType="map" resultType="com.reflect.pojo.User">
        select * from mybatis.user where id=#{reflect} and name=#{name}
    </select>
    <insert id="insertMapUser" parameterType="map">
        insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd})
    </insert>
    <update id="updateMapUser" parameterType="map">
        update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id}
    </update>
    <delete id="deleteMapUser" parameterType="map">
        delete from mybatis.user where id=#{id}
    </delete>

<!--    模糊查询-->
    <select id="getUserLike" parameterType="String" resultType="com.reflect.pojo.User">
        select * from mybatis.user where name like #{value};
    </select>

</mapper>

4.Mybatis工具类MybatisUtils.java

package com.reflect.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;

/**
 * author: Administrator
 * date: 2020/12/29 - 23:47
 */

/**
 * 建议将Mybatis打开SqlSession这一操作
 * 直接在静态方法块中加载配置文件,
 * 最后使用静态方法对外返回(暴露)SqlSession
 */
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();
    }
}

5.Mybatis配置文件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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
<!--    此处的resource要注意是'/',而不是'.'-->
    <mappers>
        <mapper resource="com/reflect/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

6.测试类MyTest

import com.reflect.mapper.UserMapper;
import com.reflect.pojo.User;
import com.reflect.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.*;

/**
 * author: Administrator
 * date: 2020/12/30 - 10:27
 */

/**
 * 为了保证SqlSession一定关闭,建议将其放在finally块中。
 * 增删改这三项操作之后,一定要记得Commit提交事务,否则数据库将不会进行相关操作的改动
 */
public class MyTest {

    // 查询全部用户
    @Test
    public void getUserList() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        try {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> userList = mapper.getUserList();
            for (User user : userList) {
                System.out.println(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    // 查询单个用户
    @Test
    public void getUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        try {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            User user = mapper.getUser(1);
            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    // 新增一个用户
    @Test
    public void insertUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        int id = (int) (Math.random()*1000000000);
        String string = UUID.randomUUID().toString();

        try {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            boolean res = mapper.insertUser(new User(id, string, "pwd"+string));
            if (res) {
                System.out.println("插入成功!!!");
            }
            // 提交事务(即使打印出成功结果,不提交也是不会插入数据库)
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    // 修改一个用户
    @Test
    public void updateUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        String string = UUID.randomUUID().toString();

        try {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            boolean res = mapper.updateUser(new User(2,string,"pwd"+string));
            if (res) {
                System.out.println("修改成功!!!");
            }
            // 提交事务
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    // 删除一个用户
    @Test
    public void deleteUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        try {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            boolean res = mapper.deleteUser(2);
            if (res) {
                System.out.println("删除成功!!!");
            }
            // 提交事务
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    // 万能Map???
    // 查
    @Test
    public void getMapUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        try {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            Map<String,Object> map = new HashMap<>();
            map.put("reflect",1);
            map.put("name","reflect111");
            User user = mapper.getMapUser(map);
            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }
    // 增
    @Test
    public void insertMapUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        int id = (int) (Math.random()*1000000000);
        String string = UUID.randomUUID().toString();

        try {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            Map<String,Object> map = new HashMap<>();
            map.put("id",id);
            map.put("name",string);
            map.put("pwd","pwd"+string);
            boolean res = mapper.insertMapUser(map);
            if (res) {
                System.out.println("使用Map插入成功!!!");
            }
            // 提交事务
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }
    // 改
    @Test
    public void updateMapUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        String string = UUID.randomUUID().toString();

        try {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            Map<String, Object> map = new HashMap<>();
            map.put("id",2);
            map.put("name",string);
            map.put("pwd","pwd"+string);
            boolean res = mapper.updateMapUser(map);
            if (res) {
                System.out.println("使用Map修改成功!!!");
            }
            //提交事务
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }
    // 删
    @Test
    public void deleteMapUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        try {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            Map<String, Object> map = new HashMap<>();
            map.put("id",2);
            boolean res = mapper.deleteMapUser(map);
            if (res) {
                System.out.println("使用Map删除成功!!!");
            }
            // 提交事务
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

    // 模糊查询
    @Test
    public void getUserLike() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            // value使用%通配符,左右两边都加即代表只要含有"reflect"字符即可查询
            List<User> userLike = mapper.getUserLike("%reflect%");
            for (User user : userLike) {
                System.out.println(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }
}

全部代码就是这样了,上面所需要修改的就是mysql的配置,之后就肯定能运行起来的。

最后就是希望对大家学习SSM略有帮助。

本文地址:https://blog.csdn.net/A13777852949/article/details/111993362