SpringBoot入门系列:第六篇 mybatis

    这一篇,代码折腾的时间较长,完成之后都是一些小细节,主要有三:

1、引入的依赖错误;

2、启动配置错误;

3、xml文件的mapper命名空间错误。

一、完整的pom.xml

<?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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.example</groupId>
	<artifactId>spring-boot-sample-mybatis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>spring-boot-sample-mybatis</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.3.5.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- mysql连接 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<!-- mybatis -->
		<dependency>
  			<groupId>org.mybatis.spring.boot</groupId>
  			<artifactId>mybatis-spring-boot-starter</artifactId>
  			<version>1.1.1</version>
		</dependency>
	</dependencies>
	
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
比较关键的是:mysql-connector-java、mybatis-spring-boot-starter,其它的根据使用引用。

二、启动文件 Application.java

package com.example;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;


@SpringBootApplication
@MapperScan("com.example.mapper")
public class Application {
	
	protected static Logger logger=LoggerFactory.getLogger(Application.class);

	@Bean
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource dataSource() {
        return new org.apache.tomcat.jdbc.pool.DataSource();
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));

        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
		logger.info("SpringBoot Start Success");
	}
}
注意3点:

1、在类上声明MapperScan,这是mybatis-spring-boot-starter在1.1.1引入的类Mapper,从而在mapper接口上不需要任何声明

2、配置dataSource、SqlSessionFactory、PlatformTransactionManager,其实默认的都已经配好,这里主要是为了标明Mapper的xml文件存在位置

3、src/main/resources下的文件,在打包之后,都在工程的根目录。

这个只需要更改两个地方:

1、MapperScan之后的"com.example.mapper",改成Mapper接口文件所在的包名

2、sqlSessionFactoryBean方法中"classpath:/mybatis/*.xml",改成Mapper的xml文件存在位置

三、启动配置文件 application.properties

spring.datasource.url=jdbc:mysql://192.168.56.201:3306/bootsample?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-active=10
spring.datasource.max-idle=5
spring.datasource.min-idle=0
这个根据数据库情况配置

四、Mapper的XML文件

<?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必须指向Dao接口 -->
<mapper namespace="com.example.mapper.HotelDtoMapper">
    <resultMap id="ListHotelDto" type="com.example.dto.HotelDto" >
        <result column="cityName" property="cityName" />
        <result column="hotelName" property="hotelName" />
        <result column="address" property="address" />
        <result column="zip" property="zip" />
        <result column="state" property="state" />
        <result column="country" property="country" />
    </resultMap>

    <!-- 根据ID查询数据 -->
    <select id="findByCountry" parameterType="String" resultMap="ListHotelDto">
    	select 
    		c.name as cityName,
    		h.name as hotelName,
    		h.address,
    		h.zip,
    		c.state,
    		c.country 
    	from city c 
    	join hotel h on c.id=h.city 
    	where c.country = #{country}
    </select>
</mapper>
与普通的mybatis配置一样,只是小心:

1、mapper的命名空间(namespace),一定是所对应的接口的包名+类名

2、parameterType和resultMap,与实际匹配

五、接口文件

package com.example.mapper;

import java.util.List;

import com.example.dto.HotelDto;

public interface HotelDtoMapper {
	
	public List<HotelDto> findByCountry(String country);
}
注意:

1、类上没有任何的声明

2、方法的名称、输入参数书,与xml定义的一直

六、文件结构


七、其它说明

      使用mybatis的主要目的,就是解决复杂sql。在数据库工具中拼写好sql,拷贝进xml文件;验证sql,仅需要把sql拷贝到数据库工具进行分析即可,简单高效。



源代码:http://download.csdn.net/detail/lxhjh/9560276


没有更多推荐了,返回首页