Mybatis和Spring的整合

什么是 MyBatis-Spring?

MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。它将允许 MyBatis 参与到 Spring 的事务管理之中,创建映射器 mapper 和 SqlSession 并注入到 bean 中,以及将 Mybatis 的异常转换为 Spring 的 DataAccessException。最终,可以做到应用代码不依赖于 MyBatis,Spring 或 MyBatis-Spring。

MyBatis-Spring的一个小案例

在pom.xml中引入依赖

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.1</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.6</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

数据库的book表有以下字段:id,bname,btype,author,author_gender,price,description

创建与数据库book表对应的实体类Book.java

package com.lanou3g.bean;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class Book {
    private Integer id;

    private String bname;

    private Integer btype;

    private String author;

    private Integer authorGender;

    private Float price;

    private String description;

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", bname='" + bname + '\'' +
                ", btype=" + btype +
                ", author='" + author + '\'' +
                ", authorGender=" + authorGender +
                ", price=" + price +
                ", description='" + description + '\'' +
                "}\n";
    }
}

创建接口BookMapper.java

package com.lanou3g.dao;

import com.lanou3g.bean.Book;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public interface BookMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Book record);

    Book selectByPrimaryKey(Integer id);

    List<Book> selectAll();

    int updateByPrimaryKey(Book record);
}

数据库相关外部配置文件jdbc.properties

jdbc.url=jdbc:mysql://localhost:3306/lanou?characterEncoding=utf8
jdbc.driver=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root

配置数据源,连接Spring和Mybatis

applicationContext.xml

<?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"
       xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
       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
       http://mybatis.org/schema/mybatis-spring
       http://mybatis.org/schema/mybatis-spring.xsd">
    <!--引入文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--开启注解扫描-->
    <context:component-scan base-package="com.lanou3g"/>
    <!--扫描接口,spring自动管理-->
    <mybatis:scan base-package="com.lanou3g.dao"/>

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

    <!--连接spring和mybatis-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:/mapper/*"/>
    </bean>
</beans>

SQL配置文件BookMapper.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="com.lanou3g.dao.BookMapper">
  <resultMap id="BaseResultMap" type="com.lanou3g.bean.Book">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="bname" jdbcType="VARCHAR" property="bname" />
    <result column="btype" jdbcType="INTEGER" property="btype" />
    <result column="author" jdbcType="VARCHAR" property="author" />
    <result column="author_gender" jdbcType="INTEGER" property="authorGender" />
    <result column="price" jdbcType="REAL" property="price" />
    <result column="description" jdbcType="VARCHAR" property="description" />
  </resultMap>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from book
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.lanou3g.bean.Book">
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into book (bname, btype, author, 
      author_gender, price, description
      )
    values (#{bname,jdbcType=VARCHAR}, #{btype,jdbcType=INTEGER}, #{author,jdbcType=VARCHAR}, 
      #{authorGender,jdbcType=INTEGER}, #{price,jdbcType=REAL}, #{description,jdbcType=VARCHAR}
      )
  </insert>
  <update id="updateByPrimaryKey" parameterType="com.lanou3g.bean.Book">
    update book
    set bname = #{bname,jdbcType=VARCHAR},
      btype = #{btype,jdbcType=INTEGER},
      author = #{author,jdbcType=VARCHAR},
      author_gender = #{authorGender,jdbcType=INTEGER},
      price = #{price,jdbcType=REAL},
      description = #{description,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select id, bname, btype, author, author_gender, price, description
    from book
    where id = #{id,jdbcType=INTEGER}
  </select>
  <select id="selectAll" resultMap="BaseResultMap">
    select id, bname, btype, author, author_gender, price, description
    from book
  </select>

</mapper>

入口类App.java

package com.lanou3g;

import com.lanou3g.dao.BookMapper;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        System.out.println(ctx.getBean(BookMapper.class).selectAll());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值