首页 > 其他 > 详细

Mybatis简单的增删改查

时间:2021-05-20 00:10:49      阅读:20      评论:0      收藏:0      [点我收藏+]

Mybatis

mybatis – MyBatis 3 | 入门

1.创建一个简单的数据库

插入自己所需的数据

CREATE DATABASE `runningman`

USE `runningman`

CREATE TABLE `mc`(
`id` INT(10) NOT NULL PRIMARY KEY,
`name` VARCHAR(20) DEFAULT NULL,
`age` INT(20) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;

2.环境搭建

1.创建一个普通的Maven项目

2.删除原本项目中的src文件

3.修改系统配置

技术分享图片

4.导入所需Maven依赖

<dependencies>
        <!--Mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <!--Mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.24</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
    </dependencies>

5.防止资源导入失败

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

6.新建一个Moudle文件

7.完整项目

技术分享图片


3.操作数据库及获取资源文件

1.mybatis核心配置文件(mybatis-config.xml)

mysql版本不同,driver和url的写法也不同

Communications link failure报错的可能性 - yeyu2000 - 博客园 (cnblogs.com)

<?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/runningman?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=Asia/Shanghai"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/yeyu/dao/McMapper.xml"/>
    </mappers>
</configuration>

2.从 XML 中构建 SqlSessionFactory(utils.MybatisUtils)

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

3.编写数据库Mc对象(pojo.Mc)

package com.yeyu.pojo;

public class Mc {
    private int id;
    private String name;
    private int age;

    public Mc() {
    }

    public Mc(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    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 getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Mc{" +
                "id=" + id +
                ", name=‘" + name + ‘\‘‘ +
                ", age=" + age +
                ‘}‘;
    }
}

4.实现增删改查

1.接口(McMapper)

public interface McMapper {
    //查询所有用户
    List<Mc> getMcList();
    //插入一个用户
    int insertMc(Mc mc);
    //更新信息
    int updateMc(Mc mc);
    //删除信息
    int deleteMc(int mc);
    //查询一个用户的
    Mc getMc(int id);
}

2.sql语句(McMapper.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.yeyu.dao.McMapper">
    <!--查询-->
    <select id="getMcList" resultType="com.yeyu.pojo.Mc" parameterType="int">
        select * from runningman.mc
    </select>

    <!--插入-->
    <insert id="insertMc" parameterType="com.yeyu.pojo.Mc">
        insert into runningman.mc (id,name,age) values (#{id},#{name},#{age});
    </insert>

    <!--更新-->
    <update id="updateMc" parameterType="com.yeyu.pojo.Mc">
        update runningman.mc
        set name =#{name},age=#{age}
        where id=#{id};
    </update>

    <!--删除-->
    <delete id="deleteMc" parameterType="int">
        delete from runningman.mc where id=#{id}
    </delete>
    
    <!--查询一个用户-->
    <select id="getMc" resultType="com.yeyu.pojo.Mc" parameterType="int">
        select * from runningman.mc where id=#{id}
    </select>
</mapper>

3.测试(McMapperTest)

注意:增删改需要提交事务 sqlSession.commit();

public class McMapperTest {
    //查询所有用户
    @Test
    public void testSelect(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        McMapper mapper = sqlSession.getMapper(McMapper.class);
        List<Mc> mcList = mapper.getMcList();
        for (Mc mc : mcList) {
            System.out.println(mc);
        }
        sqlSession.close();
    }

    //插入信息
    @Test
    public void testInsert(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        McMapper mapper = sqlSession.getMapper(McMapper.class);
        int QZM = mapper.insertMc(new Mc(7, "yeyu", 21));
        if(QZM>0){
            System.out.println("插入成功");
        }
        sqlSession.commit();
        sqlSession.close();
    }

    //更新信息
    @Test
    public void testUpdate(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        McMapper mapper = sqlSession.getMapper(McMapper.class);
        int yeyu = mapper.updateMc(new Mc(7, "yeyu", 18));
        if(yeyu>0){
            System.out.println("更新成功");
        }
        sqlSession.commit();
        sqlSession.close();
    }

    //删除信息
    @Test
    public void testDelete(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        McMapper mapper = sqlSession.getMapper(McMapper.class);
        mapper.deleteMc(7);
        sqlSession.commit();
        sqlSession.close();
    }

    //查找一个用户
    @Test
    public void testGetMc(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        McMapper mapper = sqlSession.getMapper(McMapper.class);
        Mc mc=mapper.getMc(4);
        System.out.println(mc);
        sqlSession.close();
    }
}

5.错误原因

1.字符编码

Cause:com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceExcep

在pom.xml中配置

	<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

Mybatis简单的增删改查

原文:https://www.cnblogs.com/yeyu2000/p/14786246.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!