Spring整合MyBatis实现依赖注入式增删查改

版权声明:Leo.All Rights Reserved. https://blog.csdn.net/qq_41113081/article/details/89219935

Spring整合MyBatis实现依赖注入式增删查改

对于如何使用idea+maven创建javaweb项目以及配置spring,请看我的其他博文

项目结构

在这里插入图片描述

创建数据库表以及对应的实体类

在这里插入图片描述

package entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Serializable {
    /**
     *
     */
    private Integer id;

    /**
     *
     */
    private String name;

    /**
     *
     */
    private String sex;

    /**
     *
     */
    private String specialty;

    /**
     *
     */
    private String grade;

    public Student(String name, String sex, String specialty, String grade) {
        this.name = name;
        this.sex = sex;
        this.specialty = specialty;
        this.grade = grade;
    }
}

创建对数据库的操作接口以及对应的mybatis配置文件

package dao;

import entity.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Mapper
public interface StudentMapper {
    int insert(@Param("student") Student student);

    int insertSelective(@Param("student") Student student);

    int insertList(@Param("students") List<Student> students);

    int updateByPrimaryKeySelective(@Param("student") Student student);

    void delete(Integer integer);

    Student getStudentById(Integer integer);

    void update(Student student);

    List<Student> selectAll();
}
<?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="dao.StudentMapper">
    <!--auto generated Code-->
    <resultMap id="BaseResultMap" type="entity.Student">
        <result column="id" property="id" jdbcType="INTEGER"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="sex" property="sex" jdbcType="VARCHAR"/>
        <result column="specialty" property="specialty" jdbcType="VARCHAR"/>
        <result column="grade" property="grade" jdbcType="VARCHAR"/>
    </resultMap>

    <!--auto generated Code-->
    <sql id="Base_Column_List">
            id,
            `name`,
            sex,
            specialty,
            grade
    </sql>

    <!--auto generated Code-->
    <insert id="insert" parameterType="entity.Student">
        INSERT INTO student (
            name,
            sex,
            specialty,
            grade
        ) VALUES (
            #{name},
            #{sex},
            #{specialty},
            #{grade}
        )
    </insert>

    <delete id="delete" parameterType="int">
        delete from student
        where id = #{id}
    </delete>

    <update id="update" parameterType="entity.Student">
        update student
        set name = #{name}, sex = #{sex}, specialty = #{specialty}, grade = #{grade}
        where id = #{id}
    </update>

    <select id="getStudentById" parameterType="int" resultType="entity.Student">
        select *
        from student
        where id = #{id}
    </select>
    <!--若查询的返回结果是集合 则resultType类型应为具体类型 而不是list-->
    <select id="selectAll" resultType="entity.Student">
        select *
        from student
    </select>

    <!--auto generated Code-->
    <insert id="insertSelective" useGeneratedKeys="true" keyProperty="student.id">
        INSERT INTO student
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="student.id!=null">id,</if>
            <if test="student.name!=null">`name`,</if>
            <if test="student.sex!=null">sex,</if>
            <if test="student.specialty!=null">specialty,</if>
            <if test="student.grade!=null">grade,</if>
        </trim>
        VALUES
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="student.id!=null">#{student.id,jdbcType=INTEGER},
            </if>
            <if test="student.name!=null">#{student.name,jdbcType=VARCHAR},
            </if>
            <if test="student.sex!=null">#{student.sex,jdbcType=VARCHAR},
            </if>
            <if test="student.specialty!=null">#{student.specialty,jdbcType=VARCHAR},
            </if>
            <if test="student.grade!=null">#{student.grade,jdbcType=VARCHAR},
            </if>
        </trim>
    </insert>

    <!--auto generated Code-->
    <insert id="insertList">
        INSERT INTO student (
        id,
        `name`,
        sex,
        specialty,
        grade
        )VALUES
        <foreach collection="students" item="student" index="index" separator=",">
            (
            #{student.id,jdbcType=INTEGER},
            #{student.name,jdbcType=VARCHAR},
            #{student.sex,jdbcType=VARCHAR},
            #{student.specialty,jdbcType=VARCHAR},
            #{student.grade,jdbcType=VARCHAR}
            )
        </foreach>
    </insert>

    <!--auto generated Code-->
    <update id="updateByPrimaryKeySelective">
        UPDATE student
        <set>
            <if test="student.name != null">`name`= #{student.name,jdbcType=VARCHAR},</if>
            <if test="student.sex != null">sex= #{student.sex,jdbcType=VARCHAR},</if>
            <if test="student.specialty != null">specialty= #{student.specialty,jdbcType=VARCHAR},</if>
            <if test="student.grade != null">grade= #{student.grade,jdbcType=VARCHAR}</if>
        </set>
        WHERE id = #{student.id,jdbcType=INTEGER}
    </update>
</mapper>

创建继承dao层接口的具体操作类,用于对student表的增删查改

package daoimpl;

import dao.StudentMapper;
import entity.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 java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @ClassName: StudentMapperImpl
 * @Author: Leo
 * @Description:
 * @Date: 2019/4/11 14:22
 */
public class StudentMapperImpl implements StudentMapper {
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;
    private static final String resources = "mybatis-config.xml";

    public StudentMapperImpl() {
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resources);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            sqlSession = sqlSessionFactory.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int insert(Student student) {
        int insert = sqlSession.insert("insert", student);
        sqlSession.commit();
        return insert;

    }

    @Override
    public int insertSelective(Student student) {
        int insertSelective = sqlSession.insert("insertSelective", student);
        sqlSession.commit();
        return insertSelective;
    }

    @Override
    public int insertList(List<Student> students) {
        int insertList = sqlSession.insert("insertList", students);
        sqlSession.commit();
        return insertList;
    }

    @Override
    public int updateByPrimaryKeySelective(Student student) {
        int updateByPrimaryKeySelective = sqlSession.update("updateByPrimaryKeySelective", student);
        sqlSession.commit();
        return updateByPrimaryKeySelective;
    }

    @Override
    public void delete(Integer integer) {
        sqlSession.delete("delete", integer);
        sqlSession.commit();
    }

    @Override
    public Student getStudentById(Integer integer) {
        return sqlSession.selectOne("getStudentById", integer);
    }

    @Override
    public void update(Student student) {
        sqlSession.update("update", student);
        sqlSession.commit();
    }

    @Override
    public List<Student> selectAll() {
        return sqlSession.selectList("selectAll");
    }
}

创建service接口,用于定义一系列对数据库的操作,其实和dao接口一样

package service;

import entity.Student;

import java.util.List;

public interface StudentService {

    int insert(Student student);

    int insertSelective(Student student);

    int insertList(List<Student> students);

    int updateByPrimaryKeySelective(Student student);

    List<Student> selectAll();
}

定义实现service接口的类

package serviceimpl;

import dao.StudentMapper;
import entity.Student;
import org.springframework.stereotype.Service;
import service.StudentService;

import javax.annotation.Resource;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentMapper studentMapper;

    @Override
    public int insert(Student student) {
        return studentMapper.insert(student);
    }

    @Override
    public int insertSelective(Student student) {
        return studentMapper.insertSelective(student);
    }

    @Override
    public int insertList(List<Student> students) {
        return studentMapper.insertList(students);
    }

    @Override
    public int updateByPrimaryKeySelective(Student student) {
        return studentMapper.updateByPrimaryKeySelective(student);
    }

    @Override
    public List<Student> selectAll() {
        return studentMapper.selectAll();
    }

    public void setStudentMapper(StudentMapper studentMapper) {
        this.studentMapper = studentMapper;
    }

    public StudentMapper getStudentMapper() {
        return studentMapper;
    }
}

最后在spring的配置文件中注册bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--创建一个bean-->
    <bean id="student" class="entity.Student">
        <!--为属性赋值-->
        <property name="id" value="666"/>
        <property name="name" value="Spring"/>
        <property name="sex" value=""/>
        <property name="grade" value="大六"/>
        <property name="specialty" value="信息安全"/>
    </bean>

    <bean id="studentMapperImpl" class="daoimpl.StudentMapperImpl"/>

    <bean id="studentService" class="serviceimpl.StudentServiceImpl">
        <property name="studentMapper" ref="studentMapperImpl"/>
    </bean>
</beans>

测试增删查改

import entity.Student;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import serviceimpl.StudentServiceImpl;

/**
 * @ClassName: SpringTest
 * @Author: Leo
 * @Description:
 * @Date: 2019/4/10 22:30
 */
public class SpringTest {
    private static Logger logger = LogManager.getLogger("SpringTest");

    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        Student student = (Student) applicationContext.getBean("student");
        logger.debug(student.toString());

        StudentServiceImpl studentService = (StudentServiceImpl) applicationContext.getBean("studentService");
        int insert = studentService.insert(new Student("Java", "1", "1", "1"));
        logger.debug(insert);
        for (Student student1 : studentService.selectAll()) {
            logger.debug("测试:  " + student1.toString());
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41113081/article/details/89219935