实验五、六 MyBatis配置文件编写及CRUD操作

配置文件:

pom.xml

<?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>org.example</groupId>
    <artifactId>ch5.1</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.1</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.30</version>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.12</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.10</version>
    </dependency>
    </dependencies>

</project>

 main/java文件夹下创建Java类文件和Mapper接口文件

com/cqust/ch5/Employee.java

package com.cqust.ch5;

import org.apache.ibatis.type.Alias;

@Alias("employee")
public class Employee {
    
    private int id;//员工编号
    private String name;//员工名称
    private int age;//员工年龄
    private String position;//员工职位

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

    public String getPosition() {
        return position;
    }

    public void setPosition(String position) {
        this.position = position;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", position='" + position + '\'' +
                '}';
    }
}

​

com/cqust/ch5/mapper/EmployeeMapper.java

package com.cqust.ch5.mapper;

import com.cqust.ch5.Employee;

import java.util.List;

public interface EmployeeMapper {

    public List<Employee> selectById(int id);//根据Id查询员工信息

    public void addEmployee(Employee employee);//添加员工信息

    public void updateById(Employee employee);//修改指定Id的员工信息

    public void deleteById(int id);//删除指定Id的员工信息

}

 com/cqust/ch5/Student.java

package com.cqust.ch5;

public class Student {
    private String sno;//学号
    private String name;//姓名
    private String major;//专业

    public String getSno() {
        return sno;
    }

    public void setSno(String sno) {
        this.sno = sno;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sno='" + sno + '\'' +
                ", name='" + name + '\'' +
                ", major='" + major + '\'' +
                '}';
    }
}

com/cqust/ch5/mapper/StudentMapper.java

package com.cqust.ch5.mapper;

import com.cqust.ch5.Student;

import java.util.List;

public interface StudentMapper {

    public List<Student> selectByArbitrarily(Student student);//多条件查询

    public List<Student> selectLessThanSno(int number);//单条件查询

}

 resources文件夹下创建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>
    <typeAliases>
        <package name="com.cqust.ch5"/>
    </typeAliases>

    <environments default="development">
        <!--配置数据库连接环境,可以配置多个,通过default切换-->
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///javaee_test?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <package name="com.cqust.ch5.mapper"/>
    </mappers>

</configuration>

数据库准备

employeeTable表(id设置自动递增)

 

 studentTable表(sno设置自动递增)

 

 

resources文件夹下创建mapper.xml文件(注意对应的mapper.xml文件应与mapper.java文件路径一一对应)

com/cqust/ch5/mapper/EmployeeMapper.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.cqust.ch5.mapper.EmployeeMapper">

    <resultMap id="employeeResultMap" type="employee">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="age" property="age"/>
        <result column="position" property="position"/>
    </resultMap>


    <insert id="addEmployee" useGeneratedKeys="true" keyProperty="id">
        insert into employeetable(name, age, position) values (#{name}, #{age}, #{position})
    </insert>

    <update id="updateById">
        update employeetable
<set>
    <if test="name!=null and name!=''">
        name=#{name},
    </if>
    <if test="age!=null and age!=''">
        age=#{age},
    </if>
    <if test="position!=null and position!=''">
        position=#{position},
    </if>
</set>
            <where>
                id=#{id}
            </where>
    </update>
    <delete id="deleteById">
        delete from employeetable where id=#{id};
    </delete>

    <select id="selectById" resultMap="employeeResultMap">
        select * from employeetable where id=#{id};
    </select>
</mapper>

com/cqust/ch5/mapper/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.cqust.ch5.mapper.StudentMapper">
    <resultMap id="studentResultMap" type="student">
        <id column="sno" property="sno"/>
        <result column="name" property="name"/>
        <result column="major" property="major"/>
    </resultMap>

    <select id="selectByArbitrarily" resultType="student">
        select * from studenttable
            <where>
                <if test="name!=null and name!='' ">
                    name like #{name};
                </if>
                <if test="(name==null or name=='') and major!=null  and major!='' ">
                    major=#{major};
                </if>
                <if test="name==null and major==null and name=='' and major=='' ">
                    sno!=null;
                </if>
            </where>
    </select>
    <select id="selectLessThanSno" resultType="com.cqust.ch5.Student">
        select * from studenttable
<where>
    sno
    <![CDATA[
    <
    ]]>
    #{number}
</where>
    </select>
</mapper>

编写Test.java测试(此处每个测试方法对应完成各个题目)

package com.cqust.ch5;

import com.cqust.ch5.mapper.EmployeeMapper;
import com.cqust.ch5.mapper.StudentMapper;
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;
import java.util.List;
import java.util.Scanner;

public class Test {

    @org.junit.Test
    public void selectByIdTest() throws IOException {
        String resource="mybatis-config.xml";
        InputStream inputStream= Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession(true);
        EmployeeMapper employeeMapper=sqlSession.getMapper(EmployeeMapper.class);

        System.out.println("输入需要查找的id:");
        int id=new Scanner(System.in).nextInt();
        List<Employee> employeeList=employeeMapper.selectById(id);
        System.out.println(employeeList);

        sqlSession.close();
    }

    @org.junit.Test
    public void addEmployeeTest() throws IOException {
        String resource="mybatis-config.xml";
        InputStream inputStream= Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession(true);
        EmployeeMapper employeeMapper=sqlSession.getMapper(EmployeeMapper.class);

        System.out.println("输入需要添加的员工信息:\n姓名:");
        String name = new Scanner(System.in).nextLine();
        System.out.println("年龄:");
        int age = Integer.parseInt(new Scanner(System.in).nextLine());
        System.out.println("职位:");
        String position = new Scanner(System.in).nextLine();
        Employee employee=new Employee();
        employee.setName(name);
        employee.setAge(age);
        employee.setPosition(position);
        employeeMapper.addEmployee(employee);
        System.out.println("success!");

        sqlSession.close();
    }

    @org.junit.Test
    public void updateByIdTest() throws IOException {
        String resource="mybatis-config.xml";
        InputStream inputStream= Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession(true);
        EmployeeMapper employeeMapper=sqlSession.getMapper(EmployeeMapper.class);

        System.out.println("输入需要修改的员工编号:");
        int id=new Scanner(System.in).nextInt();
        employeeMapper.selectById(id);
        System.out.println("输入需要修改的员工信息(年龄不可为空):\n姓名:");
        String name = new Scanner(System.in).nextLine();
        System.out.println("年龄:");
        int age=new Scanner(System.in).nextInt();
        System.out.println("职位:");
        String position = new Scanner(System.in).nextLine();
        Employee employee=new Employee();
        employee.setId(id);
        employee.setName(name);
        employee.setAge(age);
        employee.setPosition(position);
        employeeMapper.updateById(employee);

        System.out.println("success!");

        sqlSession.close();
    }

    @org.junit.Test
    public void deleteByIdTest() throws IOException {
        String resource="mybatis-config.xml";
        InputStream inputStream= Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession(true);
        EmployeeMapper employeeMapper=sqlSession.getMapper(EmployeeMapper.class);

        System.out.println("输入需要删除的员工的id:");
        int id=new Scanner(System.in).nextInt();
        employeeMapper.deleteById(id);

        System.out.println("success!");

        sqlSession.close();
    }

    @org.junit.Test
    public void StudentSelectTest() throws IOException {
        String resource="mybatis-config.xml";
        InputStream inputStream= Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession(true);
        StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);

        System.out.println("多条件查询:\n姓名:");
        String name=new Scanner(System.in).nextLine();
        System.out.println("专业:");
        String major=new Scanner(System.in).nextLine();
        System.out.println("若以上都为空则查询学号不为空");
        Student student=new Student();
        student.setName(name);
        student.setMajor(major);
        List<Student> studentList=studentMapper.selectByArbitrarily(student);
        System.out.println(studentList);

        sqlSession.close();
    }

    @org.junit.Test
    public void StudentSelectTest2() throws IOException {
        String resource="mybatis-config.xml";
        InputStream inputStream= Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession(true);
        StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);

        System.out.println("单条件查询:\n学号小于多少值:");
        int number=new Scanner(System.in).nextInt();
        List<Student> studentList=studentMapper.selectLessThanSno(number);
        System.out.println(studentList);

        sqlSession.close();
    }

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
手把手视频详细讲解项目开发全过程,需要的小伙伴自行百度网盘下载,链接见附件,永久有效。 课程简介 MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。使用原生的Mybatis编写持久层逻辑时,所需要的代码是比较繁琐的,需要定义Mapper接口和Mapper.xml文件,每一个方法都需要编写对应的sql语句,会存在很多大量的重复工作,使用MP之后,对通用的方法做了高度的抽取,避免了很多重复工作,可以非常快速的实现了单表的各种增、删、改、查操作。除此之外,MP还提供了其他的高级功能,如:枚举、插件、ActiveRecord、SQL注入等。 本课程全面讲解了Mybatis-Plus框架的使用,从快速入门到原理分析再到插件的应用。每一个知识点都有案例进行演示学习,最终通过学习你将全面掌握MP的使用,从而使Mybatis的的开发更加的高效,达到事半功倍的效果。 适应人群 有一定的Java以及Mybatis框架的基础。 从0开始全面讲解Mybatis-Plus框架 l 快速入门 n Mybatis + MP 整合 n Spring + Mybatis + MP 整合 n SpringBoot + Mybatis + MP 整合 n 通用CRUD的全面讲解 n 配置 l 高级用法 n 条件构造器 n Oracle 主键Sequence n 通用枚举n ActiveRecord n 逻辑删除 l 插件 n 执行分析插件 n 性能分析插件 n 乐观锁插件 主讲内容 章节一:快速入门 1. Mybatis-Plus简介 2. 快速入门 3. 通用CRUD 4. 配置 5. 条件构造器 章节二:进阶 1. ActiveRecord 2. Oracle 主键Sequence 3. 插件 章节三:高级应用 1. Sql 注入器 2. 自动填充功能 3. 逻辑删除 4. 通用枚举 5. 代码生成器 6. MybatisX 快速开发插件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值