spring快速入门--整合mybatis

Spring整合mybatis

1、添加依赖

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.3.3version>
        dependency>

        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.6version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.3.3version>
            <scope>compilescope>
        dependency>

        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.2version>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.26version>
        dependency>

        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>

2、方式一

编写配置文件
dataSource-----sqlSessionFactory--------sqlSession

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:content="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 https://www.springframework.org/schema/context/spring-context.xsd">
    
    <content:property-placeholder location="classpath:db.properties"/>

    <content:component-scan base-package="dao"/>

    <bean id="dataSource" 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>
    
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
        <property name="dataSource" ref="dataSource">property>
        
        <property name="configLocation" value="classpath:mybatis.xml"/>
        
        <property name="mapperLocations" value="classpath:dao/PeopleMapper.xml"/>
    bean>
    
    <bean class="org.mybatis.spring.SqlSessionTemplate" id="sqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    bean>

    <bean id="people1" class="dao.PeopleMapperImpl">
        <property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
    bean>


beans>
编写对应接口及其实现类
package dao;

import org.apache.ibatis.annotations.Mapper;
import pojo.People;

@Mapper
public interface PeopleMapper {
    public People findById(int id);
}

实现类

package dao;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Component;
import pojo.People;

@Component
public class PeopleMapperImpl implements PeopleMapper{
    private SqlSessionTemplate sqlSessionTemplate;

    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate){
        this.sqlSessionTemplate=sqlSessionTemplate;
    }
    @Override
    public People findById(int id) {
        PeopleMapper mapper = sqlSessionTemplate.getMapper(PeopleMapper.class);

        return mapper.findById(1);
    }
}
编写sql逻辑

DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="dao.PeopleMapper">
    
    <select id="findById" parameterType="int" resultType="People">
        select * from springboot.people where id=#{id};
    select>

mapper>

DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <typeAliases>
        <package name="pojo"/>
    typeAliases>

configuration>
测试
@Test
public void test11(){
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
    PeopleMapper people1 = context.getBean("people1", PeopleMapper.class);
    People people1ById = people1.findById(1);
    System.out.println(people1ById);
}

3、方式二

SqlSessionDaoSupport

SqlSessionDaoSupport 是一个抽象的支持类,用来为你提供 SqlSession。调用 getSqlSession() 方法你会得到一个 SqlSessionTemplate,之后可以用于执行 SQL 方法

只需修改spring配置文件


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:content="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 https://www.springframework.org/schema/context/spring-context.xsd">
    
    <content:property-placeholder location="classpath:db.properties"/>

    <content:component-scan base-package="dao"/>

    <bean id="dataSource" 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>
    
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
        <property name="dataSource" ref="dataSource">property>
        <property name="configLocation" value="classpath:mybatis.xml"/>
        <property name="mapperLocations" value="classpath:dao/PeopleMapper.xml"/>
    bean>
    <bean id="people1" class="dao.PeopleMapperImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    bean>


beans>
package dao;

import org.apache.ibatis.session.SqlSession;

import org.mybatis.spring.support.SqlSessionDaoSupport;

import pojo.People;

public class PeopleMapperImpl extends SqlSessionDaoSupport implements PeopleMapper{
    @Override
    public People findById(int id) {
        SqlSession sqlSession = getSqlSession();
        PeopleMapper mapper = sqlSession.getMapper(PeopleMapper.class);
        return mapper.findById(1);
    }
}

测试

@Test
public void test11(){
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
    PeopleMapper people1 = context.getBean("people1", PeopleMapper.class);
    People people1ById = people1.findById(1);
    System.out.println(people1ById);
}

4、方式三

MapperFactoryBean

需要注意的是:所指定的映射器类必须是一个接口,而不是具体的实现类。在这个示例中,通过注解来指定 SQL 语句,但是也可以使用 MyBatis 映射器的 XML 配置文件。

配置好之后,你就可以像 Spring 中普通的 bean 注入方法那样,将映射器注入到你的业务或服务对象中。MapperFactoryBean 将会负责 SqlSession 的创建和关闭。 如果使用了 Spring 的事务功能,那么当事务完成时,session 将会被提交或回滚。最终任何异常都会被转换成 Spring 的 DataAccessException 异常。

<bean id="blog" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="com.piao.dao.BlogMapper"/>
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
bean>

测试

@Test
public void test12(){
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
    PeopleMapper people1 = context.getBean("mapperFactoryBean", PeopleMapper.class);
    People people1ById = people1.findById(1);
    System.out.println(people1ById);
}

Spring整合mybatis----注解

1、接口

package dao;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import pojo.People;

@Mapper
public interface PeopleMapper {
    @Select("select * from springboot.people where id=#{id}")
    public People findById(int id);
}

2、编写配置类

package config;

import dao.PeopleMapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;


@Configuration
@ComponentScan({"dao"})
public class springConfig {

    //dataSource
    @Bean
    public DataSource dataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        dataSource.setUrl("jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        return dataSource;
    }
    //sqlSessionFactory
    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception{
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        //PathMatchingResourcePatternResolver可以用来解析资源文件,主要是用来解析类路径下的资源文件。
        //当然它也可以用来解析其它资源文件,如基于文件系统的本地资源文件。
        sqlSessionFactoryBean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public PeopleMapper getPeople() throws Exception {
        SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactoryBean());
        PeopleMapper mapper = sqlSessionTemplate.getMapper(PeopleMapper.class);
        return mapper;
    }

}

3、mybatis配置文件


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="pojo"/>
    typeAliases>

<mappers>
    <mapper class="dao.PeopleMapper"/>
mappers>
configuration>

4、测试

@Test
public void test13(){
    BeanFactory context = new AnnotationConfigApplicationContext(springConfig.class);
    PeopleMapper getPeople = context.getBean("getPeople", PeopleMapper.class);
    System.out.println(getPeople.findById(1));
}

你可能感兴趣的:(spring,java,java-ee)