spring+mybatis通过注解+xml配置详细流程

前述

  • maven项目
  • 数据库用druid

依赖引入

<dependencies>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.3.16version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>5.3.16version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.3.16version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-txartifactId>
            <version>5.3.16version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.7version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.6version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.28version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.2.8version>
        dependency>
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poiartifactId>
            <version>3.14version>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.11version>
            <scope>testscope>
        dependency>
    dependencies>

创建文件夹

spring+mybatis通过注解+xml配置详细流程_第1张图片

创建spring的配置文件(applicationContext.xml)


<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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    
    <context:property-placeholder location="classpath:db.properties"/>

    
    <context:annotation-config/>
    
    <context:component-scan base-package="cn.edu.seig.csms"/>

    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <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>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    bean>

    
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    bean>

    
    <tx:annotation-driven transaction-manager="txManager"/>


    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.edu.seig.csms.mapper"/>
    bean>

beans>

创建mybatis配置文件(mybatis-config.xml)


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"/>
        
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    settings>
    
    <typeAliases>
        <package name="cn.edu.seig.csms"/>
    typeAliases>

    
    <mappers>
        <package name="cn.edu.seig.csms.mapper"/>
    mappers>
configuration>

创建数据库连接

	jdbc.driver=com.mysql.cj.jdbc.Driver
	jdbc.url=jdbc:mysql://localhost:3306/cms?useUnicode=true&characterEncoding=utf-8&useSSL=true
	jdbc.username=root
	jdbc.password=root

创建实体类

package cn.edu.seig.csms.pojo;

import org.springframework.stereotype.Component;

/**
 * @author admin
 */
@Component
public class Course {

	private String courseId;//课程编号
	private String courseName;//课程名
	private double needCredits;//学分
	private String assess;//考查方式
	private String beforeCourse;//先修课程

	public String getCourseId() {
		return courseId;
	}
	public void setCourseId(String courseId) {
		this.courseId = courseId;
	}
	public String getCourseName() {
		return courseName;
	}
	public void setCourseName(String courseName) {
		this.courseName = courseName;
	}
	public double getNeedCredits() {
		return needCredits;
	}
	public void setNeedCredits(double needCredits) {
		this.needCredits = needCredits;
	}
	public String getAssess() {
		return assess;
	}
	public void setAssess(String assess) {
		this.assess = assess;
	}
	public String getBeforeCourse() {
		return beforeCourse;
	}
	public void setBeforeCourse(String beforeCourse) {
		this.beforeCourse = beforeCourse;
	}
	@Override
	public String toString() {
		return "Course [courseId=" + courseId + ", courseName=" + courseName + ", needCredits=" + needCredits
				+ ", assess=" + assess + ", beforeCourse=" + beforeCourse + "]";
	}
}

创建mapper映射

package cn.edu.seig.csms.mapper;

import cn.edu.seig.csms.pojo.Course;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;

/**
 * @author admin
 */
@Repository
public interface CourseMapper {

    @Insert("insert into tb_course(courseId,courseName,needCredits) Values(#{courseId},#{courseName},#{needCredits})")
    //添加课程
    public int insertCourse(Course course);

    @Select("select * from tb_course limit #{limit}")
    //查询指定个数的课程信息
    public ArrayList<Course> getCoursesLimit(int limit);

    @Select("select * from tb_course where courseId=#{courseId}")
    //根据课程号获取课程信息
    public Course getCourseById(String courseId);

}

创建service业务层接口

package cn.edu.seig.csms.service;

import cn.edu.seig.csms.pojo.Course;

import java.util.ArrayList;

/**
 * @author admin
 */
public interface CourseService {
    int insertCourse(Course course);

    ArrayList<Course> getCoursesLimit(int limit);

    Course getCourseById(String courseId);
}

实现业务层接口方法

package cn.edu.seig.csms.service.impl;

import cn.edu.seig.csms.mapper.CourseMapper;
import cn.edu.seig.csms.pojo.Course;
import cn.edu.seig.csms.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

@Service
@Transactional
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Override
    public int insertCourse(Course course) {
        return courseMapper.insertCourse(course);
    }

    @Override
    public ArrayList<Course> getCoursesLimit(int limit) {
        return courseMapper.getCoursesLimit(limit);
    }

    @Override
    public Course getCourseById(String courseId) {
        return courseMapper.getCourseById(courseId);
    }
}

编写测试方法

import cn.edu.seig.csms.mapper.CourseMapper;
import cn.edu.seig.csms.pojo.Course;
import cn.edu.seig.csms.service.CourseService;
import cn.edu.seig.csms.service.TakeService;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;

public class CourseTest {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    CourseService courseService = context.getBean(CourseService.class);

    @Test
    public void insertCourse(){
        Course course = new Course();
        course.setCourseName("123");
        course.setCourseId("123");
        course.setNeedCredits(22);
        course.setBeforeCourse("13");
        course.setAssess("2132");
        int i = courseService.insertCourse(course);
        System.out.println(i);
    }

    @Test
    public void getCoursesLimit(){
        ArrayList<Course> coursesLimit = courseService.getCoursesLimit(5);
        coursesLimit.forEach(i -> System.out.println(i));
    }

    @Test
    public void getCourseById(){
        Course courseById = courseService.getCourseById("123");
        System.out.println(courseById);
    }
}

你可能感兴趣的:(笔记,spring,java,xml,mybatis)