Spring-MyBatis整合步骤

1.引入相应的jar

 

2.创建实体类

package cn.chenghao.bean;
/*
 * @Author chenghao
 * @Date 上午 09:43 2019-05-31
 * 实体类
 */

public class Student {
    private Integer id;
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Student(Integer id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer 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;
    }

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

3.创建mapper 

package cn.chenghao.mapper;

import cn.chenghao.bean.Student;

import java.util.List;

public interface IStudentMapper {

    /**
     * 新增
     */
    void addStudent(Student student);

    /**
     * 删除
     */
    void delStudent(Integer id);

    /**
     * 修改
     */
    void updStudent(Student student);

    /**
     * 查询
     */
    List<Student> selStudent();
}

4.创建service

 

package cn.chenghao.service;

import cn.chenghao.bean.Student;

import java.util.List;

public interface IStudentService {

    /**
     * 新增
     */
    void addStudent(Student student);

    /**
     * 删除
     */
    void delStudent(Integer id);

    /**
     * 修改
     */
    void updStudent(Student student);

    /**
     * 查询
     */
    List<Student> selStudent();

}

5.创建service实现类

package cn.chenghao.service.impl;

import cn.chenghao.bean.Student;
import cn.chenghao.mapper.IStudentMapper;
import cn.chenghao.service.IStudentService;
import org.springframework.stereotype.Service;

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

@Service
public class StudentServiceImpl implements IStudentService {

    @Resource(name = "IStudentMapper")
    private IStudentMapper iStudentMapper;

    /**
     * 新增
     */
    @Override
    public void addStudent(Student student) {
        iStudentMapper.addStudent(student);
    }

    /**
     * 删除
     */
    @Override
    public void delStudent(Integer id) {
        iStudentMapper.delStudent(id);
    }

    /**
     * 修改
     */
    @Override
    public void updStudent(Student student) {
        iStudentMapper.updStudent(student);
    }

    /**
     * 查询
     */
    @Override
    public List<Student> selStudent() {
        return iStudentMapper.selStudent();
    }
}

 6.创建mapper.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="cn.chenghao.mapper.IStudentMapper">

    <insert id="addStudent" parameterType="Student">
        INSERT INTO student(name,age) VALUES(#{name},#{age})
    </insert>

    <delete id="delStudent" parameterType="Integer">
        DELETE FROM student WHERE id=#{id}
    </delete>

    <update id="updStudent" parameterType="Student">
        UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}
    </update>

    <select id="selStudent" resultType="Student">
        SELECT id,name,age FROM student
    </select>

</mapper>

 7.创建MyBatis-config——MyBatis主配置文件

<?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>

    <settings>
        <!-- 全局映射器启用缓存 -->
        <setting name="cacheEnabled" value="true"/>
        <!-- 查询时,关闭关联对象即时加载以提高性能 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指定),不会加载关联表的所有字段,以提高性能 -->
        <setting name="aggressiveLazyLoading" value="false"/>
        <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
        <setting name="multipleResultSetsEnabled" value="true"/>
        <!-- 允许使用列标签代替列名 -->
        <setting name="useColumnLabel" value="true"/>
        <!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->
        <setting name="useGeneratedKeys" value="true"/>
        <!-- 给予被嵌套的resultMap以字段-属性的映射支持 -->
        <setting name="autoMappingBehavior" value="FULL"/>
        <!-- 对于批量更新操作缓存SQL以提高性能  -->
        <setting name="defaultExecutorType" value="BATCH"/>
        <!-- 数据库超过25000秒仍未响应则超时 -->
        <setting name="defaultStatementTimeout" value="25000"/>
    </settings>

    <!--定义别名-->
    <typeAliases>
        <package name="cn.chenghao.bean"/>
    </typeAliases>

    <!--扫描映射文件-->
    <mappers>
        <package name="cn.chenghao.mapper"/>
    </mappers>

</configuration>

 8.创建db.properties文件

#mysql jdbc
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///myschool?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=chenghao

 9.创建applicationContext.xml——Spring主配置文件(重要)

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--扫描包下面的所有注解-->
    <context:component-scan base-package="cn.chenghao"/>

    <!--引入properties属性文件-->
    <context:property-placeholder location="classpath:db.properties"/>

    <!--配置SqlSessionFactory-->
    <bean id="mySqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!---->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--配置数据源-->
        <property name="dataSource" ref="myDataSource_spring"/>
    </bean>

    <!--生成Mapper的代理对象
        指定单独接口
    -->
<!--    <bean id="studentMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">-->
<!--        <property name="sqlSessionFactory" ref="mySqlSessionFactory"/>-->
<!--        <property name="mapperInterface" value="cn.chenghao.mapper.IStudentMapper"/>-->
<!--    </bean>-->

    <!--指定的基本包中的所有接口生成代理对象-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--        <property name="sqlSessionTemplateBeanName" value="mySqlSessionFactory"/>-->
        <property name="basePackage" value="cn.chenghao.mapper"/>
    </bean>

    <!--数据源配置:Spring内置数据源-->
    <bean id="myDataSource_spring" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

</beans>

10.创建测试类

package cn.chenghao.test;
/*
 * @Author chenghao
 * @Date 下午 01:14 2019-06-02
 * 测试类
 */

import cn.chenghao.bean.Student;
import cn.chenghao.service.IStudentService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class MyTest {
    @Resource(name = "studentServiceImpl")
    private IStudentService iStudentService;

    /**
     * 新增
     */
    @Test
    public void text1() {
        iStudentService.addStudent(new Student("张三", 18));
    }

    /**
     * 删除
     */
    @Test
    public void text2() {
        iStudentService.delStudent(1);
    }

    /**
     * 修改
     */
    @Test
    public void text3() {
        iStudentService.updStudent(new Student(5, "李四", 17));
    }

    /**
     * 查询所有
     */
    @Test
    public void text4() {
        System.out.println(iStudentService.selStudent());
    }


}

 

测试成功!!!

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值