11、整合Mybatis

本文详细介绍了如何在Spring Boot项目中整合Mybatis,包括依赖导入、配置文件编写、实体类与Mapper接口的定义、Mapper XML编写,以及Mybatis-Spring两种使用方式:SqlSessionTemplate和SqlSessionDaoSupport的实战步骤。重点讲解了资源文件导出、UTC时区设置和常见问题解决。
摘要由CSDN通过智能技术生成

11、整合Mybatis

步骤:

  • 1.导入相关jar包

  • Junit

  • mybatis

  • MySQL

  • spring相关

  • aop织入

  • mybatis-spring【new】

配置:

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.19.RELEASE</version>
        </dependency>
        <!--spring操作数据库的话,还需要spring-jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>
    </dependencies>

maven资源导出问题

 <!--在build中配置resources,来防止我们资源导出失败的问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
  • 2.编写配置文件

  • 3.测试

11.1 回忆 Mybatis

1.编写实体类

@Data
public class User {

    private Integer id;
    private String name;
    private String pwd;
}

2.编写核心配置文件

mybatis-config.xml

<?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核心配置文件-->
<configuration>

    <typeAliases>
        <package name="com.hardy.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper class="com.hardy.mapper.UserMapper"/>
    </mappers>
</configuration>

3.编写接口

UserMapper

public interface UserMapper {
    //查询所有用户信息
    List<User> selectUsers();
}

4.编写Mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.kuang.mapper.UserMapper">
    <select id="selectUsers" resultType="user">
        select * from user
    </select>
</mapper>

5.测试

    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream in = Resources.getResourceAsStream(resource);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = sessionFactory.openSession(true);

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.selectUser();
        for (User user : users) {
            System.out.println(user);
        }
    }

注意点:

1.找不到类就是maven资源导出问题, target中没有导出文件

2.编写完mapper.xml文件后,一定要去mybatis-config中绑定mapper

3.数据库UTC设置 Asia/Shanghai

4.工具类放下下面

//sqlSessionFactory -->sqlSession
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try{
            //使用mybatis第一步:获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";//注意
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    //
    public static SqlSession getSqlSession(){
         return sqlSessionFactory.openSession(true);
    }

}

11.2 Mybatis-spring

方式一:基于SqlSessionTrmplate

  • 编写spring-dao.xml

    • 1.编写数据源配置

    • 2.sqlSessionFactory

    • 3.sqlSessionTemplate

<?xml version="1.0" encoding="UTF8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--Datasource:使用spring的数据源替换mybatis的配置  c3p0 dbcp druid
       我们这里使用spring提供的jdbc:org.springframework.jdbc.datasource
   -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <!--创建SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--注册mybatis-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--注册userMapper-->
        <property name="mapperLocations" value="classpath:com/kuang/mapper/UserMapper.xml"/>
    </bean>

    <!--SqlSessionTemplate,就是我们使用的sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--通过构造器给SqlSessionTemplate 传入参数  它需要一个sqlSessionFactory
            且它没有set方法,只能 使用构造器注入-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

</beans>
  • 给UserMapper接口添加实现类
public class UserMapperImpl implements UserMapper{

    //原来我们 使用操作都使用SqlSession,现在所有的都使用sqlSessionTemplate,这两个一样
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    public List<User> selectUsers() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.selectUsers();
        return users;
    }
}
  • 将自己写的实现类,注入到spring核心配置文件 applicationContext.xml中
<?xml version="1.0" encoding="UTF8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--导入spring-dao.xml,之间联系在一起-->
    <import resource="spring-dao.xml"/>

    <!--将实现类 注入到spring中-->
    <bean id="userMapper" class="com.kuang.mapper.UserMapperImpl">
        <!--UserMappperImpl 类中需要SqlSessionTemplate这个参数,传入 -->
        <property name="sqlSession" ref="sqlSession"/>
    </bean>



</beans>
  • mybatis核心配置文件 mybatis-config.xml 只做以下两项配置
<?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="com.kuang.pojo"/>
  </typeAliases>

  <!--<settings>
  </settings>-->

</configuration>
  • 测试
@Test
    public void  test1() throws IOException {

       ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = (UserMapper) context.getBean("userMapper");
        List<User> users = userMapper.selectUsers();
        for (User user : users) {
            System.out.println(user);
        }
    }

方式二 :基于SqlSessionDaoSupport

在这里插入图片描述

spring-dao.xml 不变

<?xml version="1.0" encoding="UTF8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--Datasource:使用spring的数据源替换mybatis的配置  c3p0 dbcp druid
       我们这里使用spring提供的jdbc:org.springframework.jdbc.datasource
   -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <!--创建SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--注册mybatis-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--注册userMapper-->
        <property name="mapperLocations" value="classpath:com/kuang/mapper/UserMapper.xml"/>
    </bean>

    <!--SqlSessionTemplate,就是我们使用的sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--通过构造器给SqlSessionTemplate 传入参数  它需要一个sqlSessionFactory
            且它没有set方法,只能 使用构造器注入-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

</beans>

实现类:UserMapperImpl2 继承了SqlSessionDaoSupport

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
    public List<User> selectUsers() {
        return getSqlSession().getMapper(UserMapper.class).selectUsers();
    }

applicationContext.xml

<?xml version="1.0" encoding="UTF8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--导入spring-dao.xml,之间联系在一起-->
    <import resource="spring-dao.xml"/>


    <!--方法二:将实现类 注入到spring中-->
    <bean id="userMapper2" class="com.kuang.mapper.UserMapperImpl2">
        <!--UserMapperImpl 类中需要SqlSessionTemplate这个参数,传入      -->
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

</beans>

测试:

@Test
    public void  test2() throws IOException {

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = (UserMapper) context.getBean("userMapper2");
        List<User> users = userMapper.selectUsers();
        for (User user : users) {
            System.out.println(user);
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值