IDEA spring整合mybatis入门(上)

0.项目环境:

使用maven导入工程所需jar包
Spring 4.3.21.RELEASE
Mybatis 3.4.6
MySQL 8.0.13
druid 1.1.12

项目的整体结构如下

IDEA spring整合mybatis入门(上)_第1张图片

1.创建一个maven java项目,根据需求填写pom.xml配置文件,以及jdbc.properties和log4j.properties

pom.xml


<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.0modelVersion>

    <groupId>cn.springgroupId>
    <artifactId>spring_mybatisartifactId>
    <version>1.0-SNAPSHOTversion>

    <properties>
        <junit.version>4.12junit.version>
        <spring.version>4.3.21.RELEASEspring.version>
        <mybatis.version>3.4.6mybatis.version>
        <mybatis.spring.version>1.3.1mybatis.spring.version>
        <mysql.version>8.0.13mysql.version>
        <commons.logging.version>1.1.3commons.logging.version>
        <druid.version>1.1.12druid.version>
    properties>


    <dependencies>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>1.3.2version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-beansartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-expressionartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aopartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-txartifactId>
            <version>${spring.version}version>
        dependency>


        <dependency>
            <groupId>commons-logginggroupId>
            <artifactId>commons-loggingartifactId>
            <version>${commons.logging.version}version>
        dependency>


        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>${druid.version}version>
        dependency>

        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>${mybatis.version}version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>${mysql.version}version>
        dependency>
        
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
            <type>bundletype>
        dependency>

        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>${junit.version}version>
            <scope>testscope>
        dependency>
    dependencies>
    
    <build>
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.xmlinclude>
                includes>
            resource>
        resources>
    build>
project>

jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.username=root
jdbc.password=root
jdbc.url=jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai

log4j.properties

### set log levels ###
#trace debug info warn error fetal
log4j.rootLogger = debug,stdout,log
#, log, index, D, I, W, E

###  print log to console ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %d %p [%c] - <%m>%n

### create log to file ###
log4j.appender.log = org.apache.log4j.DailyRollingFileAppender
log4j.appender.log.File = /logs/log.log
log4j.appender.log.Append = true
log4j.appender.log.layout = org.apache.log4j.PatternLayout
log4j.appender.log.layout.ConversionPattern= %d %p [%c] - <%m>%n


# Control logging for other open source packages
log4j.logger.net.sf.navigator=ERROR
log4j.logger.net.sf.acegisecurity=WARN
log4j.logger.net.sf.acegisecurity.intercept.event.LoggerListener=WARN
log4j.logger.org.apache.commons=ERROR
log4j.logger.org.apache.struts=WARN
log4j.logger.org.displaytag=ERROR
log4j.logger.org.springframework=WARN
log4j.logger.org.apache.velocity=WARN


# SqlMap logging configuration...
log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.db=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.sqlmap.engine.cache.CacheModel=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientImpl=debug
log4j.logger.com.ibatis.sqlmap.engine.builder.xml.SqlMapParser=debug
log4j.logger.com.ibatis.common.util.StopWatch=debug


log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=error
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=error

2.数据库内表student 创建实体类

数据库内sql语句

CREATE TABLE student  (
  id int(11) PRIMARY KEY AUTO_INCREMENT,
  name varchar(10),
  sex varchar(2),
  addr varchar(10),
) ;

INSERT INTO `student` VALUES (1, '老王', '女', '北京');
INSERT INTO `student` VALUES (2, '小李', '男', '上海');
INSERT INTO `student` VALUES (3, '小刘', '女', '深圳');
INSERT INTO `student` VALUES (4, '小张', '男', '南京');
INSERT INTO `student` VALUES (5, '老王', '女', '哈尔滨');
INSERT INTO `student` VALUES (6, '老赵', '男', '沈阳');
INSERT INTO `student` VALUES (7, '老李', '女', '大连');

IDEA spring整合mybatis入门(上)_第2张图片

实体类Student

package cn.spring.bean;

import org.springframework.stereotype.Component;


@Component
public class Student {
    private Integer id;

    private String name;

    private String sex;

    private String addr;

    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 == null ? null : name.trim();
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex == null ? null : sex.trim();
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr == null ? null : addr.trim();
    }

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

3.分层设计controller以及service、dao内接口

StudentSeverlet.java

package cn.spring.controller;

import cn.spring.bean.Student;
import cn.spring.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;


@Controller
public class StudentSeverlet {
    @Autowired
    private StudentService studentService;

    public int deleteByPrimaryKey(Integer id) {
        return studentService.deleteByPrimaryKey(id);
    }

    public int insert(Student record) {
        return studentService.insert(record);
    }

    public int insertSelective(Student record) {
        return studentService.insertSelective(record);
    }

    public Student selectByPrimaryKey(Integer id) {
        return studentService.selectByPrimaryKey(id);
    }

    public int updateByPrimaryKeySelective(Student record) {
        return studentService.updateByPrimaryKeySelective(record);
    }

    public int updateByPrimaryKey(Student record) {
        return studentService.updateByPrimaryKey(record);
    }
}

StudentService .java

package cn.spring.service;

import cn.spring.bean.Student;

public interface StudentService {
    int deleteByPrimaryKey(Integer id);

    int insert(Student record);

    int insertSelective(Student record);

    Student selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);
}

StudentDao .java

package cn.spring.dao;

import cn.spring.bean.Student;

public interface StudentDao {
    int deleteByPrimaryKey(Integer id);

    int insert(Student record);

    int insertSelective(Student record);

    Student selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);
}

4.根据需求创建StudentDao.xml

也可以利用mybatis反向工程创建
StudentDao.xml



<mapper namespace="cn.spring.dao.StudentDao" >

    <resultMap id="BaseResultMap" type="student" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="name" property="name" jdbcType="VARCHAR" />
        <result column="sex" property="sex" jdbcType="VARCHAR" />
        <result column="addr" property="addr" jdbcType="VARCHAR" />
    resultMap>

    <sql id="Base_Column_List" >
        id, name, sex, addr
    sql>

    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select 
        <include refid="Base_Column_List" />
        from student
        where id = #{id,jdbcType=INTEGER}
    select>

    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
        delete from student
        where id = #{id,jdbcType=INTEGER}
    delete>

    <insert id="insert" parameterType="student" >
        insert into student (id, name, sex, 
            addr)
        values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, 
            #{addr,jdbcType=VARCHAR})
    insert>

    <insert id="insertSelective" parameterType="student" >
        insert into student
        <trim prefix="(" suffix=")" suffixOverrides="," >
            <if test="id != null" >
                id,
            if>
            <if test="name != null" >
                name,
            if>
            <if test="sex != null" >
                sex,
            if>
            <if test="addr != null" >
                addr,
            if>
        trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
            <if test="id != null" >
                #{id,jdbcType=INTEGER},
            if>
            <if test="name != null" >
                #{name,jdbcType=VARCHAR},
            if>
            <if test="sex != null" >
                #{sex,jdbcType=VARCHAR},
            if>
            <if test="addr != null" >
                #{addr,jdbcType=VARCHAR},
            if>
        trim>
    insert>

    <update id="updateByPrimaryKeySelective" parameterType="student" >
        update student
        <set >
            <if test="name != null" >
                name = #{name,jdbcType=VARCHAR},
            if>
            <if test="sex != null" >
                sex = #{sex,jdbcType=VARCHAR},
            if>
            <if test="addr != null" >
                addr = #{addr,jdbcType=VARCHAR},
            if>
        set>
        where id = #{id,jdbcType=INTEGER}
    update>

    <update id="updateByPrimaryKey" parameterType="student" >
        update student
        set name = #{name,jdbcType=VARCHAR},
            sex = #{sex,jdbcType=VARCHAR},
            addr = #{addr,jdbcType=VARCHAR}
        where id = #{id,jdbcType=INTEGER}
    update>
mapper>

5.创建service层实现类

StudentServiceImpl

package cn.spring.service.impl;

import cn.spring.bean.Student;
import cn.spring.dao.StudentDao;
import cn.spring.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentDao studentDao;

    public StudentDao getStudentDao() {
        return studentDao;
    }

    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }

    public int deleteByPrimaryKey(Integer id) {
        return studentDao.deleteByPrimaryKey(id);
    }

    public int insert(Student record) {
        return studentDao.insert(record);
    }

    public int insertSelective(Student record) {
        return studentDao.insertSelective(record);
    }

    public Student selectByPrimaryKey(Integer id) {
        return studentDao.selectByPrimaryKey(id);
    }

    public int updateByPrimaryKeySelective(Student record) {
        return studentDao.updateByPrimaryKeySelective(record);
    }

    public int updateByPrimaryKey(Student record) {
        return studentDao.updateByPrimaryKey(record);
    }
}

6.填写spring和mybatis的配置文件

applicationContext.xml


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

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

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

        
        <property name="filters" value="stat"/>

        
        <property name="maxActive" value="20"/>
        <property name="initialSize" value="1"/>
        <property name="minIdle" value="1"/>

        
        <property name="maxWait" value="60000"/>

        
        <property name="timeBetweenEvictionRunsMillis" value="60000"/>

        
        <property name="minEvictableIdleTimeMillis" value="300000"/>

        <property name="testWhileIdle" value="true"/>
        <property name="testOnBorrow" value="false"/>
        <property name="testOnReturn" value="false"/>

        
        <property name="poolPreparedStatements" value="true"/>
        <property name="maxOpenPreparedStatements" value="20"/>
        
        <property name="validationQuery" value="select 1"/>
    bean>


    
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="dataSource" ref="dataSource"/>
        
        <property name="configLocation" value="classpath:mybatisConfig.xml"/>
    bean>
    
    <bean id="studentDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="cn.spring.dao.StudentDao"/>
        <property name="sqlSessionFactory" ref="sqlSessionFactory">property>
    bean>
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.spring.dao">property>
    bean>


    
    <context:component-scan base-package="cn.spring"/>
beans>

mybatisConfig.xml



<configuration>
    
    <typeAliases>
        <package name="cn.spring.bean"/>
    typeAliases>
    
    
    

configuration>

7.写一个测试程序测试,以查询方法为例

TestSpring_Mybatis.java

import cn.spring.bean.Student;
import cn.spring.controller.StudentSeverlet;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring_Mybatis {
    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        StudentSeverlet studentSeverlet = context.getBean(StudentSeverlet.class);
        int id = 1;
//      测试查询方法
        Student student = studentSeverlet.selectByPrimaryKey(id);
        System.out.println(student);

    }
}

运行结果

IDEA spring整合mybatis入门(上)_第3张图片

项目中如果有差错,还请大神指正。

你可能感兴趣的:(spring,SSM,mybatis)