spring快速入门--整合mybatis

Spring整合mybatis

1、添加依赖

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.3</version>
        </dependency>
<!--        mybatis-spring-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
<!--        spring-jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.3</version>
            <scope>compile</scope>
        </dependency>
<!--        mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
<!--        mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

2、方式一

编写配置文件
dataSource-----sqlSessionFactory--------sqlSession
<?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: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>
        <!--   引入Mybatis的配置文件信息 -->
        <property name="configLocation" value="classpath:mybatis.xml"/>
        <!--   引入Mybatis的mapper配置文件信息 -->
        <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逻辑
<?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">
<!--namespace:指定命名空间-->
<mapper namespace="dao.PeopleMapper">
    <!--    parameterType:表示参数是什么类型
        resultType:返回值是什么类型
        如果数据库中的类型与Entity类中的属性的类型不一致,需要用resultMap-->
    <select id="findById" parameterType="int" resultType="People">
        select * from springboot.people where id=#{id};
    </select>

</mapper>
<?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>
<!--
我们编写的Entity类中的类要被应用需要些他的全限定名,很麻烦,因此我们可以给他区别名,这样方便使用
package:表示对应的包中的所有类的名字都是该类的名字的首字母小写
例如:public class People {}
       别名为:people
-->
    <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配置文件

<?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: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配置文件

<?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>
    <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));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值