SpringBoot无废话入门04:MyBatis整合

1.Parent引入及pom配置

        首先,如果要支持mybatis,那么我们就应该引入mybatis的starter。同时,由于连接本身还需要用jdbc的connetor和连接池,所以一并需要引入这些依赖。如下是一个完整的的最简pom,

<?xml version="1.0" encoding="UTF-8"?>

<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/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <packaging>war</packaging>

  <parent>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-parent</artifactId>

    <version>2.1.3.RELEASE</version>

  </parent>

  <name>testboot01</name>

  <groupId>com.zuikc</groupId>

  <artifactId>testboot01</artifactId>

  <version>1.0-SNAPSHOT</version>

  <dependencies>

      <!--jsp支持, servlet 依赖. -->

      <dependency>

          <groupId>javax.servlet</groupId>

          <artifactId>javax.servlet-api</artifactId>

          <scope>provided</scope>

      </dependency>

      <dependency>

          <groupId>javax.servlet</groupId>

          <artifactId>jstl</artifactId>

      </dependency>

      <!-- tomcat 的支持.-->

      <dependency>

          <groupId>org.springframework.boot</groupId>

          <artifactId>spring-boot-starter-tomcat</artifactId>

      </dependency>

      <dependency>

          <groupId>org.apache.tomcat.embed</groupId>

          <artifactId>tomcat-embed-jasper</artifactId>

          <scope>provided</scope>

      </dependency>

      <dependency>

          <groupId>mysql</groupId>

          <artifactId>mysql-connector-java</artifactId>

      </dependency>

      <dependency>

          <groupId>org.apache.tomcat</groupId>

          <artifactId>tomcat-dbcp</artifactId>

          <version>7.0.47</version>

      </dependency>

      <dependency>

          <groupId>org.apache.tomcat</groupId>

          <artifactId>tomcat-dbcp</artifactId>

          <version>7.0.47</version>

      </dependency>

      <dependency>

          <groupId>org.mybatis.spring.boot</groupId>

          <artifactId>mybatis-spring-boot-starter</artifactId>

          <version>1.3.2</version>

      </dependency>

    <dependency>

      <groupId>org.springframework.boot</groupId>

      <artifactId>spring-boot-starter-web</artifactId>

    </dependency>

  </dependencies>

  <build>

    <plugins>

      <plugin>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-maven-plugin</artifactId>

      </plugin>

    </plugins>

  </build>

</project>

2.配置初始化

        首先我们需要将数据库连接配置到文件中,比如prop.properties,

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf8

jdbc.username=root

jdbc.password=root

jdbc.maxActive=2335

jdbc.maxIdel=120

jdbc.maxWait=100

        然后,用java配置的方式将其引入到代码中,创建DataSourceConfiguration,

package com.zuikc.config;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.PropertySource;

@Configuration

//这个注解导入刚才增加的jdbc配置文件

@PropertySource("classpath:prop.properties")

public class DataSourceConfiguration {

    @Value("${jdbc.driver}")

    private String driver;

    @Value("${jdbc.url}")

    private String url;

    @Value("${jdbc.username}")

    private String username;

    @Value("${jdbc.password}")

    private String password;

    @Value("${jdbc.maxActive}")

    private int maxActive;

    @Value("${jdbc.maxIdel}")

    private int maxIdel;

    @Value("${jdbc.maxWait}")

    private long maxWait;

    @Bean

    public BasicDataSource dataSource(){

        BasicDataSource dataSource = new BasicDataSource();

        dataSource.setDriverClassName(driver);

        dataSource.setUrl(url);

        dataSource.setUsername(username);

        dataSource.setPassword(password);

        dataSource.setMaxActive(maxActive);

        dataSource.setMaxIdle(maxIdel);

        dataSource.setMaxWait(maxWait);

        dataSource.setValidationQuery("SELECT 1");

        dataSource.setTestOnBorrow(true);

        return dataSource;

    }

}

        接着,增加mybatis配置,

package com.zuikc.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;

import org.mybatis.spring.SqlSessionFactoryBean;

import org.mybatis.spring.SqlSessionTemplate;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import org.springframework.transaction.PlatformTransactionManager;

import org.springframework.transaction.annotation.EnableTransactionManagement;

import org.springframework.transaction.annotation.TransactionManagementConfigurer;

@Configuration

//加上这个注解,使得支持事务

@EnableTransactionManagement

public class MyBatisConfig implements TransactionManagementConfigurer {

    @Autowired

    private DataSource dataSource;

    @Override

    public PlatformTransactionManager annotationDrivenTransactionManager() {

        return new DataSourceTransactionManager(dataSource);

    }

    @Bean(name = "sqlSessionFactory")

    public SqlSessionFactory sqlSessionFactoryBean() {

        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();

        bean.setDataSource(dataSource);

        try {

            return bean.getObject();

        } catch (Exception e) {

            e.printStackTrace();

            throw new RuntimeException(e);

        }

    }

    @Bean

    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {

        return new SqlSessionTemplate(sqlSessionFactory);

    }

}

        注意上面的sqlSessionFactory这个bean。

        然后需要配置MyBatis配置文件的路径,这个配置需要与上面的配置分开来写,因为它们有着一个先后顺序,

package com.zuikc.config;

import org.mybatis.spring.mapper.MapperScannerConfigurer;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

// 因为这个对象的扫描,需要在MyBatisConfig的后面注入,所以加上下面的注解

@AutoConfigureAfter(MyBatisConfig.class)

public class MyBatisMapperScannerConfig {

    @Bean

    public MapperScannerConfigurer mapperScannerConfigurer() {

        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();

        //获取之前注入的beanName为sqlSessionFactory的对象

        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");

        //指定xml配置文件的路径

        mapperScannerConfigurer.setBasePackage("com.zuikc.dao");

        return mapperScannerConfigurer;

    }

}

3.三层架构

        先创建最底层的dao接口,如下:

package com.zuikc.dao;

import java.util.List;

import java.util.Map;

import org.apache.ibatis.annotations.Mapper;

import org.apache.ibatis.annotations.Select;

@Mapper

public interface TestDao {

    @Select("SELECT * FROM tbl_user;")

    public List<Map<String,Object>> find();

}

        接着创建service,

package com.zuikc.service;

import com.zuikc.dao.TestDao;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.List;

import java.util.Map;

@Service

public class TestService {

    @Resource

    TestDao dao;

    public List<Map<String,Object>> find(){

        List<Map<String,Object>> users = dao.find();

        return users;

    }

}

        然后是controller,

package com.zuikc.controller;

import com.zuikc.dao.TestDao;

import com.zuikc.service.TestService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.List;

import java.util.Map;

@Controller

public class StudentController {

    @Autowired

    TestService service;

    @RequestMapping(value = {"test01"})

    public String view(Map<String, Object> map) {

        List<Map<String,Object>> users = service.find();

        for (Map<String, Object> user : users) {

            for (Map.Entry<String, Object> entry : user.entrySet()) {

                System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

            }

        }

        System.out.println(users.size());

        map.put("name", "zuikc.com");

        map.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        return "views/test01";

    }

}

        经过上面的创建之后,我们的代码结构是这样的,

        执行之,

        注意了,如果你已经忘记了如何启动MySQL,那么,下面就是命令哦:

        sudo bin/mysqld_safe --user=mysql &

4.事务支持

        第一步,导入JDBC依赖,

      <dependency>

          <groupId>org.springframework.boot</groupId>

          <artifactId>spring-boot-starter-jdbc</artifactId>

      </dependency>

        注意,有了这个依赖,SpringBoot会自动注入DataSourceTransactionManager。 

        接着,直接在Service中添加@Transactional注解就能支持事务啦。本文不再赘述,大家自己尝试一下吧。

        感谢关注“码农星球”。本文版权属于“码农星球”。我们提供咨询和培训服务,关于本文有任何困惑,请关注并联系我们。

评论列表

添加评论

提交评论

服务热线

010-57480310

Java培训,专家一对一辅导