其他分享
首页 > 其他分享> > Mybatis实现CRUD

Mybatis实现CRUD

作者:互联网

Mybatis 对数据库进行操作,所以首先打开数据库 以及服务,我使用的是mysql 

以对学生表进行增删改查(CRUD)为例

步骤

1.创建数据库 即 数据表(确保自己的Mysql服务已打开)

数据库名 mybatis-zcong  数据表名 tb_student

数据表 创建的 脚本语言

CREATE TABLE `tb_student` (
  `id` varchar(20) NOT NULL,
  `name` varchar(20) DEFAULT NULL,
  `grade` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 

自行往里面加一些数据,方便测试

2.使用 idea 创建 Maven 工程  

使用Maven创建项目需要配置Maven环境

Maven 环境搭建 : 配置maven_进步1点的博客-CSDN博客

配置好来创建项目

        

 这里要确保jdk已经选好

 Finish即可

3.Mybatis实现CRUD 

 1.在pom.xml配置文件里导入mybatis依赖

<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>5.1.47</version>
    </dependency>
</dependencies>

2.搭建基本项目结构

mapper相当于dao

3.编写配置文件(mybatis-config.xml)  在resources下创file文件 自己写.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.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis-zcong?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/kuang/dao/UserMapper.xml"/>
    </mappers>
</configuration>

4.在 util 包下编写工具类(MybatisUtils.class)

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.编写实体类(pojo包里)

写完属性 按 alt+insert生成getter setter 构造方法 tostring方法

 6.在mapper(dao)包下 根据实体类编写对应的 xxxMapper接口 和 相同名称的.xml配置文件

public interface StudentMapper {
    
}

 7.对应配置文件

<?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="">
    <!--这里写sql语句-->
</mapper>

8.CRUD

1.查询所有学生信息

mapper包下的接口里面写

public interface StudentMapper {
    //查询所有学生信息
    public List<Student> queryAll();
}

2.它下面的配置文件写sql语句

<?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.fan.mapper.StudentMapper">

    <select id="queryAll" resultType="com.fan.pojo.Student">
        select * from tb_student
    </select>

</mapper>

注:    namespace 对应的mapper下接口的全名

        id为接口里面的方法名(直接粘贴) 

        resultType为返回值类型(对应实体类的全类名)

        parameterType 为参数列表类型

3.测试

在test下的java里面创建 MybatisTest 类

public class MybatisTest {
    @Test
    public void queryAll(){
        //这里面的3部部是固定的
        //1.工具类打点getSqlSession
        final SqlSession sqlSession = MybatisUtils.getSqlSession();
        //2.getSqlSession.getmapper(这里面写的是那个接口的.class)
        final StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        final List<Student> students = mapper.queryAll();
        for (Student student : students) {
            System.out.println(student);
        }
        //3.关闭sqlSession.close
        sqlSession.close();
    }
}

运行结果

接下来的操作仅需要改mapper的接口和它下面的配置文件 然后 在test里面进行测试即可   

注意:查询不用提交事务 其他都需要提交事务

以下为完整的StudentMapper接口

package com.fan.mapper;

import com.fan.pojo.Student;

import java.util.List;

public interface StudentMapper {
    //查询所有学生信息
    public List<Student> queryAll();
    //增加一条学生信息
    public void addStudent(Student student);
    //修改一条学生信息
    public void updataStudent(Student student);
    //删除一条学生信息
    public void deleteStudent(int id);
    //通过查询一条学生信息
    public Student queryOneById(int id);
}

完整StudentMapper.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.fan.mapper.StudentMapper">
    <!-- 查询所有学生信息 -->
    <select id="queryAll" resultType="com.fan.pojo.Student">
        select * from tb_student
    </select>
    
    <!--增加学生信息-->
    <insert id="addStudent" parameterType="com.fan.pojo.Student">
        insert into tb_student (id,name,grade)
        values (#{id},#{name},#{grade});
    </insert>

    <!-- 修改一条学生信息 -->
    <update id="updataStudent" parameterType="com.fan.pojo.Student">
        update tb_student
        set name = #{name} ,grade = #{grade}  where id = #{id};
    </update>

    <!-- 删除一条学生信息 -->
    <delete id="deleteStudent" parameterType="int">
        delete from tb_student
        where id = ${id}
    </delete>

    <!-- 通过 id 查询一条学生信息-->
    <select id="queryOneById" resultType="com.fan.pojo.Student" parameterType="int">
        select * from tb_student
        where id = #{id}
    </select>
</mapper>

完整测试类:

        

package com.fan;

import com.fan.mapper.StudentMapper;
import com.fan.pojo.Student;
import com.fan.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;

import java.util.List;

public class MybatisTest {
    //查询所有学生信息
    @Test
    public void queryAll(){
        //这里面的3部部是固定的
        //1.工具类打点getSqlSession
        final SqlSession sqlSession = MybatisUtils.getSqlSession();
        //2.getSqlSession.getmapper(这里面写的是那个接口的.class)
        final StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        final List<Student> students = mapper.queryAll();
        for (Student student : students) {
            System.out.println(student);
        }
        //3.关闭sqlSession.close
        sqlSession.close();
    }

    //增加一条学生信息
    @Test
    public void addStudent(){
        //这里依旧是三步走,不过要添加事务 否则不成功
        final SqlSession sqlSession = MybatisUtils.getSqlSession();
        final StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        mapper.addStudent(new Student(333,"hhh","11H22"));
        //!!!!提交事务
        sqlSession.commit();
        sqlSession.close();
    }

    //修改一条学生信息
    @Test
    public void updataStudent(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        mapper.updataStudent(new Student(333, "successful", "445566"));
        sqlSession.commit();
        sqlSession.close();
    }

    //删除一个学生信息
    @Test
    public void deleteStudent(){
        final SqlSession sqlSession = MybatisUtils.getSqlSession();
        final StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        mapper.deleteStudent(333);
        sqlSession.commit();
        sqlSession.close();
    }

    //通过id查询一条学生信息
    @Test
    public void queryOneById(){
        final Student student = MybatisUtils.getSqlSession().getMapper(StudentMapper.class).queryOneById(2);
        System.out.println(student);
    }
}

切记:确保数据库 、mybatis相关依赖 以及配置文件没问题!!!

标签:mapper,实现,StudentMapper,CRUD,id,sqlSession,student,Mybatis,public
来源: https://blog.csdn.net/qq_58856859/article/details/120337480