MyBatis增删改查功能实现

什么是MyBatis?

  1. 基于java的数据库持久化框架。 使用java开发,做数据持久化。

  2. 它是一个轻量级,半自动的orm持久化框架。一个轻量级,一个orm框架(Hibernate)数据库表和对象映射。

mybatis环境搭建:

使用maven工程,mybatis是对jdbc的封装
(dtd文件输入网址自动下载或者本博客主页资源下载)

数据库准备

![在这里插入图片描述](https://img-blog.csdnimg.cn/202104182202059.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl81MzY5NjA1Nw==,size_16,color_FFFFFF,t_70
在这里插入图片描述

开始项目

  1. 创建maven project

在这里插入图片描述
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yKZtWJn8-1618754172731)(C:\Users\Devil\AppData\Roaming\Typora\typora-user-images\image-20210418212153002.png)]

  1. pom.xml 文件里面引入 mybatis和mysql依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.dxj</groupId>
    <artifactId>test_01</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.45</version>
        </dependency>

        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>

        <!--  -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>
  1. 创建实体类,dao接口

Student:

package com.dxj.pojo;

public class Student {
    
    
    private int id;
    private String stuname;
    private String password;
    private String address;
    private String telephone;

    public Student() {
    
    
    }

    public Student(String stuname, String password, String address, String telephone) {
    
    
        this.stuname = stuname;
        this.password = password;
        this.address = address;
        this.telephone = telephone;
    }

    public Student(int id, String stuname, String password, String address, String telephone) {
    
    
        this.id = id;
        this.stuname = stuname;
        this.password = password;
        this.address = address;
        this.telephone = telephone;
    }

    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public String getStuname() {
    
    
        return stuname;
    }

    public void setStuname(String stuname) {
    
    
        this.stuname = stuname;
    }

    public String getPassword() {
    
    
        return password;
    }

    public void setPassword(String password) {
    
    
        this.password = password;
    }

    public String getAddress() {
    
    
        return address;
    }

    public void setAddress(String address) {
    
    
        this.address = address;
    }

    public String getTelephone() {
    
    
        return telephone;
    }

    public void setTelephone(String telephone) {
    
    
        this.telephone = telephone;
    }

    @Override
    public String toString() {
    
    
        return "Student{" +
                "id=" + id +
                ", stuname='" + stuname + '\'' +
                ", password='" + password + '\'' +
                ", address='" + address + '\'' +
                ", telephone='" + telephone + '\'' +
                '}';
    }
}

StudentDao:

package com.dxj.dao;

import com.dxj.pojo.Student;

import java.util.List;

public interface StudentDao {
    
    
    //查询单个
    public Student queryStudentById(int id);

    //查询所有
    public List<Student> queryAllStudent();

    //增加
    public void insertStudent(Student student);

    //删除
    public void deleteStudent(int id);

    //修改
    public void updateStudent(Student student);

}

  1. 创建并配置mybatis配置文件

需要先引入mybatis-3-config.dtd文件

settings---->Schemas and DTDs------>右边点击 + 新建 ------>弹框 uri 输入 http://mybatis.org/dtd/mybatis-3-config.dtd (浏览器输入网址自动下载)

file 选择本机mybatis-3-config.dtd文件 ---->apply—>ok

在这里插入图片描述

创建数据库连接的properties文件 db.properties,配置数据库连接相关信息

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/javaweb?characterEncoding=utf-8&useSSL=false
jdbc.username=root
jdbc.password=123456

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

    <!-- 引入外部文件 -->
    <properties resource="db.properties"/>

    <!-- 别名定义 -->
    <typeAliases>
        <package name="com.dxj.pojo"/>
    </typeAliases>

    <!-- 配置连接数据库配置信息 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">

                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 引入映射文件 -->
    <mappers>
        <mapper resource="mapper/StudentMapper.xml"/>
    </mappers>

</configuration>
  1. 创建并配置mybatis映射文件(增删改查的sql语句)

需要先引入mybatis-3-mapper.dtd文件

settings---->Schemas and DTDs------>右边点击 + 新建 ------>弹框 uri 输入 http://mybatis.org/dtd/mybatis-3-mapper.dtd

file 选择本机mybatis-3-mapper.dtd文件 ---->apply—>ok

StudentMapper.xml:

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dxj.dao.StudentDao">

    <!-- resultMap是解决属性名和字段冲突 -->
    <resultMap id="stuResultMap" type="Student">
        <!--id 主键  result 普通属性-->
        <id property="id" column="id"/>
        <result property="stuname" column="username"/>
        <result property="password" column="password"/>
        <result property="address" column="address"/>
        <result property="telephone" column="telephone"/>

    </resultMap>

    <select id="queryStudentById" parameterType="java.lang.Integer" resultMap="stuResultMap">
    select * from mybatis_test where id = #{id}
</select>

    <select id="queryAllStudent" resultMap="stuResultMap">
        select * from mybatis_test
    </select>

    <insert id="insertStudent" parameterType="Student">
        INSERT INTO mybatis_test(`id`, `username`, `password`, `address`, `telephone`) VALUES (#{id}, #{username}, #{password},#{address}, #{telephone});
    </insert>

    <delete id="deleteStudent" parameterType="Student">
        delete from mybatis_test where id = #{id}
    </delete>

    <update id="updateStudent" parameterType="Student">
        UPDATE mybatis_test SET `username` = #{username}, `password` = #{password}, `address` = #{address}, `telephone` = #{telephone} WHERE `id` = #{id};
    </update>

</mapper>
  1. 单元测试调用

Test_01:

package test;

import com.dxj.dao.StudentDao;
import com.dxj.pojo.Student;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class Test_01 {
    
    

    SqlSession session;

    @Before
    public void getseesion() throws IOException {
    
    
        //加载配置文件 并读取 通过IO流
        //1.获取输入流
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        //sqlSessionFactory.openSession(true);设置自动提交
        session = sqlSessionFactory.openSession(true);

    }
    @After
    public void closeSession(){
    
    
        session.close();
    }

    @Test
    public void queryStudentById(){
    
    
        //获取接口对象
        StudentDao studentDao = session.getMapper(StudentDao.class);

        Student student =studentDao.queryStudentById(1);
        System.out.println(student);
    }

    @Test
    public void queryAllStudent(){
    
    
        StudentDao studentDao = session.getMapper(StudentDao.class);

        List<Student> students = studentDao.queryAllStudent();
        System.out.println(students);
    }

    @Test
    public void insertStudent(){
    
    
        StudentDao studentDao = session.getMapper(StudentDao.class);

        Student student = new Student(3,"熊二","123654","岳阳","16670078888");
        studentDao.insertStudent(student);
    }

    @Test
    public void deleteStudent(){
    
    
        StudentDao studentDao = session.getMapper(StudentDao.class);

        studentDao.deleteStudent(2);
    }

    @Test
    public void updateStudent(){
    
    
        StudentDao studentDao = session.getMapper(StudentDao.class);
        Student student = new Student(2,"熊二","123789","湘阴","16670078888");
        studentDao.updateStudent(student);
    }
}


以上内容有什么问题,欢迎大家评论区提出!

Guess you like

Origin blog.csdn.net/weixin_53696057/article/details/115840876