Mybatis实现增删改查

 

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录


前言

提示:这里可以添加本文要记录的大概内容:
例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。


提示:以下是本篇文章正文内容,下面案例可供参考

一、Mybatis是什么

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

二、使用步骤

1.使用Maven导入jar包

代码如下(示例):

 </properties>-->
<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.1</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-mxj</artifactId>
        <version>5.0.12</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <resources>
        <!-- resources文件 -->
        <resource>
            <directory>src/main/java</directory>
            <!-- 引入映射文件等 -->
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
    </resources>
</build>

 

2.创建Mbatis工具类

<mapper resource="Dao/UrseMapper.xml"/>这个是自己写的接口的xml文件

代码如下(示例):

 private static SqlSessionFactory sqlSessionFactory;

 static {
     InputStream inputStream = null;
     try {
         String resource="mybatis-config.xml";
         inputStream = Resources.getResourceAsStream(resource);
         sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
     } catch (IOException e) {
         e.printStackTrace();
     }
 }
public static SqlSession getSqlSession()
{
    return sqlSessionFactory.openSession();
}

24.4.写核心配置文件

<?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.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="Dao/UrseMapper.xml"/>
    </mappers>
</configuration>

接口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 namespace="Dao.UrseMapper">
<!--   id就是对应的接口里面的方法名
       resultType这个是sql语句的返回值
       parameterType这个是要传入sql语句的值
-->
    <select id="getList" resultType="pojo.Urse">
        SELECT * FROM USER
    </select>

    <select id="getUserBy" resultType="pojo.Urse" parameterType="int">
        select * from user where Id=#{Id}
    </select>

    <insert id="adduser" parameterType="pojo.Urse">
        insert into user (Id,Name,Age,Sex)VALUES (#{Id},#{Name},#{Age},#{Sex})
    </insert>

    <update id="updateuser" parameterType="pojo.Urse">
       update user set Name=#{Name},Age=#{Age},Sex=#{Sex} where Id=#{Id}
    </update>

    <delete id="deleteuser" parameterType="int">
        delete from user where Id=#{Id}
    </delete>
</mapper>

3.写实体类和接口

private int Id;
private String Name;
private  int Age;
private String Sex;
public Urse() {
}

public Urse(int id, String name, int age, String sex) {
    Id = id;
    Name = name;
    Age = age;
    Sex = sex;
}

public int getId() {
    return Id;
}

public void setId(int id) {
    Id = id;
}

public String getName() {
    return Name;
}

public void setName(String name) {
    Name = name;
}

public int getAge() {
    return Age;
}

public void setAge(int age) {
    Age = age;
}

public String getSex() {
    return Sex;
}

public void setSex(String sex) {
    Sex = sex;
}

@Override
public String toString() {
    return "Urse{" +
            "Id=" + Id +
            ", Name='" + Name + '\'' +
            ", Age=" + Age +
            ", Sex='" + Sex + '\'' +
            '}';
}

接口如下

public interface UrseMapper {
    /*这个是查询全部用户*/
    List<Urse> getList();
    /*根据ID查询用户*/
    Urse getUserBy(int Id);
    /*添加用户*/
    int adduser(Urse urse);
    /*修改用户*/
    int updateuser(Urse urse);
    /*删除一个用户*/
    int deleteuser(int Id);
}

4.创建测试类

package Dao;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import pojo.Urse;
import utils.MybatisUtils;

import java.util.List;

public class UrseDaoTset {

@Test
    public void tset()
    {
      SqlSession sqlSession= MybatisUtils.getSqlSession();
        UrseMapper urseMapper=sqlSession.getMapper(UrseMapper.class);
        List<Urse>list=urseMapper.getList();
        for (Urse urse:list
             ) {
            System.out.println(urse);
        }
        sqlSession.close();
    }
    @Test
    public void getUserBy()
    {
        SqlSession sqlSession=MybatisUtils.getSqlSession();
        UrseMapper urseMapper=sqlSession.getMapper(UrseMapper.class);
        Urse urse=urseMapper.getUserBy(3);
        System.out.println(urse);
    }
    /*增删改需要提交事务*/
    @Test
    public void adduser()
    {
        SqlSession sqlSession=MybatisUtils.getSqlSession();
        UrseMapper urseMapper=sqlSession.getMapper(UrseMapper.class);
        urseMapper.adduser(new Urse(6,"龙琪",19,"女"));
        sqlSession.commit();
        /* sqlSession.commit();这个方法是提交事务的方法*/
        sqlSession.close();
    }
    @Test
      public void updateuser()
      {
          SqlSession sqlSession=MybatisUtils.getSqlSession();
          UrseMapper urseMapper=sqlSession.getMapper(UrseMapper.class);
          urseMapper.updateuser(new Urse(2,"黄榆坤是傻逼",999,"不男不女"));
          sqlSession.commit();
          sqlSession.close();
      }
      @Test
      public void deleteuser()
      {
          SqlSession sqlSession=MybatisUtils.getSqlSession();
          UrseMapper urseMapper=sqlSession.getMapper(UrseMapper.class);
          urseMapper.deleteuser(6);
          sqlSession.commit();
          sqlSession.close();
      }
}

需要注意的是测试类是在test包下的要和上面对src目录对应,还要注意的是增删改必须提交事务

sqlSession.commit();否则数据库不会更新。


总结

写这个的原因是作为一个笔记,作者水平有限,请各位大佬指点

 

上一篇:Mybatis流程


下一篇:Mybatis学习笔记(1)——基本配置入门