使用mybatis框架完成学生信息的增删改查操作的完整代码书写-代码拿走即用-看完秒懂哦

Posted JIANGJIZE1999

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用mybatis框架完成学生信息的增删改查操作的完整代码书写-代码拿走即用-看完秒懂哦相关的知识,希望对你有一定的参考价值。

1:首先在java文件下的bean包建立一个学生类

package net.chinaedu.mybatis.bean;


public class Student {

    private Integer sid;
    private String sname;
    private Integer age;
    private String gender;

    public Student() {
    }

    public Student(Integer sid, String sname, Integer age, String gender) {
        this.sid = sid;
        this.sname = sname;
        this.age = age;
        this.gender = gender;
    }

    public Integer getSid() {
        return sid;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public Integer getAge() {
        return age;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", sname='" + sname + '\\'' +
                ", age=" + age +
                ", gender='" + gender + '\\'' +
                '}';
    }
}

2:在java文件下的dao包建立一个对学生信息操作的方法接口:

package net.chinaedu.mybatis.dao;

import net.chinaedu.mybatis.bean.Student;

import java.util.List;

public interface IStudentDao {

    /**
     * 查询所有学生信息
     *
     * @return
     */
    List<Student> selectAll();

    /**
     * 添加学生信息
     *
     * @param student
     */
    void add(Student student);

    /**
     * 更新学生信息
     *
     * @param student
     */
    void update(Student student);

    /**
     * 通过id删除学生信息
     *
     * @param sid
     */
    void delete(Integer sid);

    /**
     * 通过id查询学生信息
     *
     * @param sid
     * @return
     */
    Student selectBySid(Integer sid);

    /**
     * 通过名称模糊查询学生信息
     *
     * @param sname
     * @return
     */
    List<Student> selectBySname(String sname);

    /**
     * 查询所有的学生信息
     *
     * @return
     */
    int selectTotal();

}

3:在resource文件下导入mybatis-config.xml配置文件和log4j.properties文件:

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>

    <!--配置mybatis环境-->
    <environments default="mysql">
        <!--配置mysql环境-->
        <environment id="mysql">
            <!--配置事务类型-->
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/hckj"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>


    <mappers>
        <!--告知mybatis映射文件的位置-->
        <mapper resource="net/chinaedu/mybatis/dao/StudentMapper.xml"/>
        <!--告知mybatis注解注解所在的接口位置-->
        <!--<mapper class="net.chinaedu.mybatis.dao.IStudentDao"/>-->
    </mappers>


</configuration>

log4j.properties

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:\\mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=info, stdout

4:在C:\\Users\\Dell\\Desktop\\mybatis_day03_crud\\src\\main\\resources\\mybatis\\dao文件下编写一个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="net.chinaedu.mybatis.dao.IStudentDao">

    <!--配置selectAll方法-->
    <select id="selectAll" resultType="net.chinaedu.mybatis.bean.Student">
        select * from student
    </select>

    <!--配置add方法-->
    <insert id="add" parameterType="net.chinaedu.mybatis.bean.Student">
        insert into student(sname, age, gender) values(#{sname}, #{age}, #{gender})
    </insert>

    <!--配置update方法-->
    <update id="update" parameterType="net.chinaedu.mybatis.bean.Student">
        update student set sname=#{sname}, age=#{age}, gender=#{gender} where sid=#{sid}
    </update>

    <!--配置delete方法-->
    <delete id="delete" parameterType="java.lang.Integer">
        delete from student where sid=#{sid}
    </delete>

    <!--配置selectBySid方法-->
    <select id="selectBySid" parameterType="int" resultType="net.chinaedu.mybatis.bean.Student">
        select * from student where sid=#{sid}
    </select>

    <!--配置selectBySname方法-->
    <select id="selectBySname" parameterType="String" resultType="net.chinaedu.mybatis.bean.Student">
        <!--select * from student where sname like #{sname}-->
        <!--/*value是固定写法*/-->
        select * from student where sname like '%${value}%'
    </select>

    <!--配置selectTotal方法-->
    <select id="selectTotal" resultType="int">
        select count(sid) from student
    </select>

</mapper>

5:在C:\\Users\\Dell\\Desktop\\mybatis_day03_crud\\src\\test\\java\\mybatis\\test文件下编写一个测试类把鼠标移到每一个@Test标签的后边,右键测试即可:

package net.chinaedu.mybatis.test;

import net.chinaedu.mybatis.bean.Student;
import net.chinaedu.mybatis.dao.IStudentDao;
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 TestMybatisCrud {

    private SqlSession session;
    private InputStream is;

    // Before注解
    @Before
    public void init() throws IOException {
        // 1.加载文件
        is = Resources.getResourceAsStream("mybatis-config.xml");
        // 2.构建builder对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        // 3.构建factory对象
        SqlSessionFactory factory = builder.build(is);
        // 4.构建session对象
        session = factory.openSession();
    }

    // After注解
    @After
    public void close() throws IOException {
        // 7.关闭资源
        session.close();
        is.close();
    }

    @Test
    public void testAdd() {

        // 5.构建持久层接口对象
        IStudentDao studentDao = session.getMapper(IStudentDao.class);
        // 6.调用新增方法
        Student student = new Student(0, "张倩倩", 18, "女");
        studentDao.add(student);

        // 提交事务
        session.commit();
    }

    @Test
    public void testUpdate() {

        // 5.构建持久层接口对象
        IStudentDao studentDao = session.getMapper(IStudentDao.class);
        // 6.调用修改方法
        Student student = new Student(4, "小贱贱", 22, "男");
        studentDao.update(student);
        // 提交事务
        session.commit();
    }

    @Test
    public void testDelete() {

        // 5.构建持久层接口对象
        IStudentDao studentDao = session.getMapper(IStudentDao.class);
        // 6.调用删除方法
        studentDao.delete(4);
        // 提交事务
        session.commit();
    }

    @Test
    public void testSelectBySid() {

        // 5.构建持久层接口对象
        IStudentDao studentDao = session.getMapper(IStudentDao.class);
        // 6.调用查询方法
        Student student = studentDao.selectBySid(9);
        System.out.println(student);
    }

    @Test
    public void testSelectBySname() {

        // 5.构建持久层接口对象
        IStudentDao studentDao = session.getMapper(IStudentDao.class);
        // 6.调用查询方法
        // List<Student> students = studentDao.selectBySname("%张%");
        List<Student> students = studentDao.selectBySname("张");
        for (Student student : students) {
            System.out.println(student);
        }
    }

    @Test
    public void testSelectTotal() {

        // 5.构建持久层接口对象
        IStudentDao studentDao = session.getMapper(IStudentDao.class);
        // 6.调用查询方法
        int count = studentDao.selectTotal();
        System.out.println(count);
    }

}

认为有帮助的盆友的点个关注吧,我以后会更新很多像这样的文章的,嘻嘻嘻嘻嘻
在这里插入图片描述

以上是关于使用mybatis框架完成学生信息的增删改查操作的完整代码书写-代码拿走即用-看完秒懂哦的主要内容,如果未能解决你的问题,请参考以下文章

使用mybatis框架完成学生信息的增删改查操作的完整代码书写-代码拿走即用-看完秒懂哦

在Idea中创建maven工程,搭建mybatis框架并完成数据库表的增删改查操作

SSM框架整合---完成对图书数据表的增删改查

Mybatis学习总结—使用接口实现数据的增删改查

Springmvc+Spring+Mybatis+Maven简单的增删改查

框架Mybatis入门(基于原生接口的XML版本),对数据库进行简单的增删改查操作