Sprint Boot项目搭建STEP2:整合Mybatis

1.pom.xml添加mybatis-spring-boot-starter,mapper-spring-boot-starter,mysql-connector-java,spring-boot-starter-jdbc,druid依赖后编译

注:druid替代

<!--mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!--mapper -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
           <version>1.1.0</version>
        </dependency>
       <!--mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId> 
        </dependency>
        <!--jdbc -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--druid(DataSource) -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.11</version>
        </dependency>
        

2.创建一个mysql数据库study,创建表student。

在这里插入图片描述

3.application.properties配置数据库连接。

在这里插入图片描述

study.driverClassName=com.mysql.jdbc.Driver
study.url=jdbc:mysql://localhost:3306/study?useUnicode=true&characterEncoding=utf-8
study.username=root
study.password=123456

4.用MyBatis Generator自动生成代码,如何集成MyBatis Generator,或者把它独立成一个工具,见下一章Sprint Boot项目搭建STEP3:MyBatis Generator。

注意生成后指定数据表名和唯一键

Mapper.xml指定的Model.java和Mapper.java路径要对上

4.druid配置DataSource和扫描Mapper。

在这里插入图片描述

package com.zhy.study.common.config;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * 数据源配置 Created by zhy on 2019/3/23.
 */
@Configuration
@MapperScan(basePackages = DataSourceConfig.PACKAGE, sqlSessionTemplateRef = "studySqlSessionTemplate")
public class DataSourceConfig {
    public final static String PACKAGE = "com.zhy.study.mapper";

    static final String MAPPER_LOCATION = "classpath:study/mapper/*.xml";

    @Value("${study.url}")
    private String url;

    @Value("${study.username}")
    private String user;

    @Value("${study.password}")
    private String password;

    @Value("${study.driverClassName}")
    private String driverClass;

    /*@Autowired
    private PageHelper pageHelper;*/

    @Bean(name = "studyDataSource")
    @Primary
    public DruidDataSource dataSource() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        // 配置初始化大小、最小、最大
        dataSource.setInitialSize(10);
        dataSource.setMinIdle(10);
        dataSource.setMaxActive(300);
        // 配置获取连接等待超时的时间
        dataSource.setMaxWait(60000);
        // 配置间隔多久才进行一次检测需要关闭的空闲连接,单位是毫秒
        dataSource.setTimeBetweenEvictionRunsMillis(60000);
        // 配置一个连接在池中最小生存的时间,单位是毫秒
        dataSource.setMinEvictableIdleTimeMillis(300000);
        dataSource.setValidationQuery("SELECT 'x'");
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);
        // 打开PSCache,并且指定每个连接上PSCache的大小
        dataSource.setPoolPreparedStatements(true);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
        // 配置监控统计拦截的filters
        dataSource.setFilters("stat,log4j,config");
        // 打开removeAbandoned功能
        dataSource.setRemoveAbandoned(true);
        // 1800秒,也就是30分钟
        dataSource.setRemoveAbandonedTimeout(1800);
        // 关闭abanded连接时输出错误日志
        dataSource.setLogAbandoned(true);
        // 提示对数据库密码进行解密
        dataSource.setConnectionProperties("config.decrypt=false");

        return dataSource;
    }

    @Bean(name = "studySqlSessionFactory")
    @Primary
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("studyDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(DataSourceConfig.MAPPER_LOCATION));
        /*bean.setPlugins(new Interceptor[] { pageHelper });*/
        return bean.getObject();
    }

    @Bean(name = "studyTransactionManager")
    @Primary
    public DataSourceTransactionManager testTransactionManager(@Qualifier("studyDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "studySqlSessionTemplate")
    @Primary
    public SqlSessionTemplate testSqlSessionTemplate(
            @Qualifier("studySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

package com.zhy.study.common.config;


import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

/**
 * Mybatis扫描配置
 * Created by zhy on 2019/3/23.
 */
@Configuration
public class MyBatisScannerConfigStudy {

	 	@Bean
	    public MapperScannerConfigurer MapperScannerConfigurer() {
	        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
	        mapperScannerConfigurer.setBasePackage("com.zhy.study.mapper");
	        mapperScannerConfigurer.setSqlSessionFactoryBeanName("studySqlSessionFactory");
	        //集成Mapper
	        Properties properties = new Properties();
	        // 这里要特别注意,不要把MyMapper放到 basePackage 中,也就是不能同其他Mapper一样被扫描到。 
	        properties.setProperty("mappers", Mapper.class.getName());
	        properties.setProperty("notEmpty", "false");
	        properties.setProperty("IDENTITY", "MYSQL");
	        mapperScannerConfigurer.setProperties(properties);
	        // Properties properties = new Properties();
	        // 这里要特别注意,不要把MyMapper放到 basePackage 中,也就是不能同其他Mapper一样被扫描到。 
	        return mapperScannerConfigurer;
	    }
}

5.编译启动出错nested exception is java.lang.NoClassDefFoundError: org/apache/log4j/Priority。添加log4j依赖后编译,启动成功。

  <!--log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>

记得添加log4j.properties

6.StudyController.java添加StudentMapper注入和getStudentList接口方法,启动访问。

@Autowired 
private StudentMapper studentMapper;

@RequestMapping(value = "/getStudentList")
 public @ResponseBody List<Student> getStudentList() {
		
		return studentMapper.selectAll();
}

7.访问http://localhost:8080/study/getStudentList出时区错误,Spring Boot 2.1.3 对应 mysql-connector-java版本8.0.15,这是在使用MySQL 8.0以上版本(MySQL连接驱动和版本都是8.0以上)的时候出现的问题错误。数据库连接添加serverTimezone=GMT%2B8

在这里插入图片描述
在这里插入图片描述

serverTimezone=GMT%2B8

8.访问成功。返回空集合。

在这里插入图片描述

9.我们来添加一个增加student表数据的接口。然后调用http://localhost:8080/study/insertStudent,再调用查询接口查看下。

@RequestMapping(value = "/insertStudent", method = RequestMethod.POST)
    public @ResponseBody void insertStudent() {
		
		Student aStudent = new Student();
		aStudent.setName("张三疯");
		aStudent.setStudentno("001");
		studentMapper.insertSelective(aStudent);
	}

在这里插入图片描述
成功插入但控制台有个异常。原因是新的mysql版本驱动变了。改成如下。重新编译启动调用。

study.driverClassName=com.mysql.cj.jdbc.Driver

在这里插入图片描述

然后调用查询。http://localhost:8080/study/getStudentList
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43733834/article/details/88757646