spring boot(11)集成mybatis

1 maven依賴

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.2.0</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.40</version>
</dependency>

2 數據源配置

2.1 數據源自動配置

      在application.properties中配置數據源信息java

spring.datasource.url = jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driver-class-name = com.mysql.jdbc.Driver

      自動配置類DataSourceAutoConfiguration和DataSourceProperties。mysql

2.2 自定義數據源

      Spring Boot默認使用tomcat-jdbc數據源,若是你想使用其餘的數據源,好比這裏使用了阿里巴巴的數據池管理,除了在application.properties配置數據源以外,你應該額外添加如下依賴:git

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.29</version>
</dependency>
spring.datasource.db.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.db.url=jdbc:mysql://localhost:3306/ml_ordering?characterEncoding=utf8
spring.datasource.db.username=root
spring.datasource.db.password=123456
spring.datasource.db.driverClassName=com.mysql.jdbc.Driver

spring.datasource.db.initialSize=5
spring.datasource.db.minIdle=5
spring.datasource.db.maxActive=20
spring.datasource.db.maxWait=60000
spring.datasource.db.timeBetweenEvictionRunsMillis=60000
spring.datasource.db.minEvictableIdleTimeMillis=300000
spring.datasource.db.validationQuery=SELECT 'x'
spring.datasource.db.testWhileIdle=true
spring.datasource.db.testOnBorrow=false
spring.datasource.db.testOnReturn=false
spring.datasource.db.poolPreparedStatements=true
spring.datasource.db.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.db.filters=stat,wall,slf4j
spring.datasource.db.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
spring.datasource.db.useGlobalDataSourceStat=true
@Bean(name = "dataSource", initMethod = "init", destroyMethod = "close")
public DruidDataSource dataSource() throws SQLException {
		// druid數據源
		if (StringUtils.isEmpty(propertyResolver.getProperty("db.url"))) {
			throw new ApplicationContextException("Database connection pool is not configured correctly");
		}
		DruidDataSource druidDataSource = new DruidDataSource();
		druidDataSource.setDriverClassName(propertyResolver.getProperty("db.driverClassName"));
		druidDataSource.setUrl(propertyResolver.getProperty("db.url"));
		druidDataSource.setUsername(propertyResolver.getProperty("db.username"));
		druidDataSource.setPassword(propertyResolver.getProperty("db.password"));
		druidDataSource.setInitialSize(Integer.parseInt(propertyResolver.getProperty("db.initialSize")));
		druidDataSource.setMinIdle(Integer.parseInt(propertyResolver.getProperty("db.minIdle")));
		druidDataSource.setMaxActive(Integer.parseInt(propertyResolver.getProperty("db.maxActive")));
		druidDataSource.setMaxWait(Integer.parseInt(propertyResolver.getProperty("db.maxWait")));
		druidDataSource.setTimeBetweenEvictionRunsMillis(
				Long.parseLong(propertyResolver.getProperty("db.timeBetweenEvictionRunsMillis")));
		druidDataSource.setMinEvictableIdleTimeMillis(
				Long.parseLong(propertyResolver.getProperty("db.minEvictableIdleTimeMillis")));
		druidDataSource.setValidationQuery(propertyResolver.getProperty("db.validationQuery"));
		druidDataSource.setTestWhileIdle(Boolean.parseBoolean(propertyResolver.getProperty("db.testWhileIdle")));
		druidDataSource.setTestOnBorrow(Boolean.parseBoolean(propertyResolver.getProperty("db.testOnBorrow")));
		druidDataSource.setTestOnReturn(Boolean.parseBoolean(propertyResolver.getProperty("db.testOnReturn")));
		druidDataSource.setPoolPreparedStatements(
				Boolean.parseBoolean(propertyResolver.getProperty("db.poolPreparedStatements")));
		druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(
				Integer.parseInt(propertyResolver.getProperty("db.maxPoolPreparedStatementPerConnectionSize")));
		druidDataSource.setFilters(propertyResolver.getProperty("db.filters"));
		druidDataSource.setUseGlobalDataSourceStat(
				Boolean.parseBoolean(propertyResolver.getProperty("db.useGlobalDataSourceStat")));
		return druidDataSource;
}

3 dao層相關

3.1 dao層掃描實現

3.1.1 註解@Mapper實現

package com.liusq.dao;

@Mapper
public interface UserDao {
    User findUserById(Integer id);
}

3.1.2  註解@MapperScan實現

@SpringBootApplication
@MapperScan("com.liusq.dao")
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

3.1.3 配置類實現

import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * dao層與mybatis映射文件掃描配置
 * 
 * @author liusq
 *
 */
@Configuration
@AutoConfigureAfter(DataSourceConfig.class)
public class DaoMapperScanConfig {
	@Bean
    public MapperScannerConfigurer dbMapperScannerConfigurer() {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        // 設置自動掃描包, 該包下的Dao將會被mybatis自動註冊, 不用寫實現類
        configurer.setBasePackage("com.liusq.dao");
        configurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        return configurer;
    }
}

3.2 sql實現方式

3.2.1 dao層方法上方註解

package com.liusq.dao;

@Mapper
public interface UserDao {
    @Select("select * from user where id = #{id}")
    User findUserById(@Param("id")Integer id);
}

3.2.2 xml映射方式

<mapper namespace="com.liusq.dao.UserDao" >
    <resultMap id="BaseResultMap" type="com.liusq.entity.User" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="userName" property="userName" jdbcType="VARCHAR" />
        <result column="passWord" property="passWord" jdbcType="VARCHAR" />
        <result column="user_sex" property="userSex" jdbcType="VARCHAR"/>
        <result column="nick_name" property="nickName" jdbcType="VARCHAR" />
    </resultMap>

    <select id="findUserById" parameterType="Integer" resultMap="BaseResultMap" >
        SELECT * FROM user
	WHERE id = #{id}
    </select>
</mapper>

      讀取xml配置,兩種方式:github

第一種,application.properties配置方式spring

mybatis.mapperLocations=classpath:com/liusq/mapper/**/*.xml

第二種,java代碼配置sql

@Bean("sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws SQLException {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		// 設置數據源
		sqlSessionFactoryBean.setDataSource(dataSource());
		// 自動重命名
		sqlSessionFactoryBean.setTypeAliasesPackage("com.liusq.entity");
		// 設置 typeHandler
		// sqlSessionFactoryBean.setTypeHandlersPackage("com.example.project.typeHandler");
		// 添加攔截器插件 (若是有的話, 分頁插件, 分表插件等)
		// sqlSessionFactory.setPlugins(new Interceptor[]{pageHelper});
		// 設置 mapper 文件
		try {
			ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
			sqlSessionFactoryBean
					.setMapperLocations(resolver.getResources("classpath:com/liusq/mapper/**/*.xml"));
			return sqlSessionFactoryBean.getObject();
		} catch (Exception e) {
			LOGGER.error("初始化DBSqlSessionFactory失敗", e);
			throw new RuntimeException(e);
		}
}

3 掃描實體類方式

第一種,application.properties配置方式tomcat

mybatis.type-aliases-package=com.liusq.entity

第二種,java代碼配置mybatis

@Bean("sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws SQLException {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		// 設置數據源
		sqlSessionFactoryBean.setDataSource(dataSource());
		// 自動重命名
		sqlSessionFactoryBean.setTypeAliasesPackage("com.liusq.entity");
		// 設置 typeHandler
		// sqlSessionFactoryBean.setTypeHandlersPackage("com.example.project.typeHandler");
		// 添加攔截器插件 (若是有的話, 分頁插件, 分表插件等)
		// sqlSessionFactory.setPlugins(new Interceptor[]{pageHelper});
		// 設置 mapper 文件
		try {
			ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
			sqlSessionFactoryBean
					.setMapperLocations(resolver.getResources("classpath:com/liusq/mapper/**/*.xml"));
			return sqlSessionFactoryBean.getObject();
		} catch (Exception e) {
			LOGGER.error("初始化DBSqlSessionFactory失敗", e);
			throw new RuntimeException(e);
		}
}

4 分頁插件配置和使用

4.1 maven依賴

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>

4.2 分頁配置

​@Bean("sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws SQLException {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		// 設置數據源
		sqlSessionFactoryBean.setDataSource(dataSource());
		// 自動重命名
		sqlSessionFactoryBean.setTypeAliasesPackage("com.liusq.entity");
		// 設置 typeHandler
		// sqlSessionFactoryBean.setTypeHandlersPackage("com.example.project.typeHandler");
		// 添加攔截器插件 (若是有的話, 分頁插件, 分表插件等)
        //分頁插件
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("returnPageInfo", "check");
        properties.setProperty("params", "count=countSql");
        pageHelper.setProperties(properties);
		sqlSessionFactory.setPlugins(new Interceptor[]{pageHelper});
		// 設置 mapper 文件
		try {
			ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
			sqlSessionFactoryBean
					.setMapperLocations(resolver.getResources("classpath:com/liusq/mapper/**/*.xml"));
			return sqlSessionFactoryBean.getObject();
		} catch (Exception e) {
			LOGGER.error("初始化DBSqlSessionFactory失敗", e);
			throw new RuntimeException(e);
		}
}
​

4.3 分頁使用

@GetMapping("/getUsers/{page}/{size}")
	public ResponseEntity getUsers(@PathVariable String page, @PathVariable String size) {
		PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(size), true).pageSizeZero(true);
		List<User> users = userService.getUsers();
		return (users == null) ? ResponseEntity.ok()
				: ResponseEntity.ok(uses);
	}
相關文章
相關標籤/搜索