springboot整合mybatis两种方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sunqingzhong44/article/details/82527201

springboot整合mybaits有两种方式:

第一种:使用mybatis官方提供的Spring Boot整合包实现,地址:https://github.com/mybatis/spring-boot-starter

第二种:使用mybatis-spring整合的方式,也就是我们传统的方式

我们推荐使用第二种,因为这样我们可以很方便的控制Mybatis的各种配置,下面介绍两种整合方式详细步骤:

  1. 第一种 pom.xml增加mybatis,mysql依赖
<?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.sun.houses</groupId>
	<artifactId>hm</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>hm</name>
	<description>Demo project for Spring Boot</description>

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

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
   </properties>
	
	<repositories><!-- 配置aliyun仓库 -->
        <repository>
            <id>maven-ali</id>
            <url>http://maven.aliyun.com/nexus/content/groups/public//</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
                <updatePolicy>always</updatePolicy>
                <checksumPolicy>fail</checksumPolicy>
            </snapshots>
        </repository>
    </repositories>

	<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>
		
		<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>
		</dependency>
    
        <dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.6</version>
		</dependency>
		
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
	

</project>

application.yml文件:增加mybatis配置  mapper配置路径和别名

server:
  port: 80
spring:
  datasource:
    url: jdbc:mysql://192.168.43.212:3306/houses?characterEncoding=UTF-8
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml
  type-aliases-package: com.sun.houses.model

启动类:增加MapperScan注解路径执行mapper接口路径

package com.sun.houses;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.sun.houses.mapper")
public class HousesApplication {

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

userMapper.xml文件放在resources/mybaits/mapper/下

<?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">
<mapper namespace="com.sun.houses.mapper.UserMapper">
    <insert id="save" parameterType="User">
        INSERT INTO user(name,phone,email)
        VALUES
        (
        #{name},#{phone},#{email}
        )
    </insert>
</mapper>

UserMapper.java文件:

package com.sun.houses.mapper;

import org.apache.ibatis.annotations.Mapper;

import com.sun.houses.model.User;

@Mapper
public interface UserMapper {
	
	/**
	 * 保存
	 */
	void save(User user);
}

User.java文件:

package com.sun.houses.model;

import java.util.Date;
/**
 * 用户实体
 * @author Dell
 *
 */
public class User {


	private Long id;//主键
	
	private String name;//姓名
	
	private String phone;//手机号
	
	private String email;//电子邮件
	
	private String aboutme;//自我介绍
	
	private String passwd;//经过MD5加密的密码
	
	private String avatar;//头像图片
	
    private Integer type;//1:普通用户,2:房产经纪人
    
    private Date createTime;//创建时间
    
    private Integer enable;//是否启用,1启用,0停用
    
    private Long agencyId;//所属经纪机构

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getAboutme() {
		return aboutme;
	}

	public void setAboutme(String aboutme) {
		this.aboutme = aboutme;
	}

	public String getPasswd() {
		return passwd;
	}

	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}

	public String getAvatar() {
		return avatar;
	}

	public void setAvatar(String avatar) {
		this.avatar = avatar;
	}

	public Integer getType() {
		return type;
	}

	public void setType(Integer type) {
		this.type = type;
	}

	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	public Integer getEnable() {
		return enable;
	}

	public void setEnable(Integer enable) {
		this.enable = enable;
	}

	public Long getAgencyId() {
		return agencyId;
	}

	public void setAgencyId(Long agencyId) {
		this.agencyId = agencyId;
	}
    
    
}

Service层:

package com.sun.houses.service;

import com.sun.houses.model.User;

public interface IUserService {
	
	void save(User user);
}	


package com.sun.houses.service.impl;

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

import com.sun.houses.mapper.UserMapper;
import com.sun.houses.model.User;
import com.sun.houses.service.IUserService;
@Service
public class UserServiceImpl implements IUserService{

	
		@Autowired
		private UserMapper userMapper;

		@Override
		public void save(User user) {
			// TODO Auto-generated method stub
			userMapper.save(user);
		}
		
		
}

controller层:

package com.sun.houses.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.sun.houses.model.User;
import com.sun.houses.service.IUserService;

@RestController
public class UserController {
	
	@Autowired
	private IUserService userService;
	
	@RequestMapping(value="/save")
	public String save() {
		User user = new User();
		user.setName("xx");
		user.setEmail("www@baidu.com");
		user.setPhone("13112312312");
		userService.save(user);
		return "success";
	}
	
}

配置完毕  

  1. 第二种方式:

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.sun.houses</groupId>
	<artifactId>hm2</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>hm2</name>
	<description>Demo project for Spring Boot</description>

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

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>
	
	<repositories><!-- 配置aliyun仓库 -->
        <repository>
            <id>maven-ali</id>
            <url>http://maven.aliyun.com/nexus/content/groups/public//</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
                <updatePolicy>always</updatePolicy>
                <checksumPolicy>fail</checksumPolicy>
            </snapshots>
        </repository>
    </repositories>
	

	<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>
		
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.6</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.4.5</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.3.0</version>
		</dependency>
		
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.43.212:3306/houses?characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root

配置数据源:这里使用druid数据源

package com.sun.houses.config.mybatis;

import javax.sql.DataSource;

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;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@PropertySource(value = {"classpath:jdbc.properties"})//也可以使用@ConfigurationProperties直接注入属性
public class DataSourceConfig {
	@Value("${jdbc.url}")
    private String jdbcUrl;
 
    @Value("${jdbc.driverClassName}")
    private String jdbcDriverClassName;
 
    @Value("${jdbc.username}")
    private String jdbcUsername;
 
    @Value("${jdbc.password}")
    private String jdbcPassword;
 
    /**
     * 配置数据库
     * @return
     */
    @Bean(name = "dataSource")
    public DataSource dataSource(){
        DruidDataSource datasource = new DruidDataSource();
        // 数据库驱动
        datasource.setDriverClassName(jdbcDriverClassName);
        // 相应驱动的jdbcUrl
        datasource.setUrl(jdbcUrl);
        // 数据库的用户名
        datasource.setUsername(jdbcUsername);
        // 数据库的密码
        datasource.setPassword(jdbcPassword);
        // 每个分区最大的连接数
        datasource.setMaxActive(20);
        // 每个分区最小的连接数
        datasource.setMinIdle(5);
        return datasource;
       
    }

}

配置mapperscanner

package com.sun.houses.config.mybatis;

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
@AutoConfigureAfter(MyBatisConfig.class)
public class MapperScannerConfig {
	@Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        mapperScannerConfigurer.setBasePackage("com.sun.houses.mapper");
        return mapperScannerConfigurer;
    }

}

sqlsessionFactory配置

package com.sun.houses.config.mybatis;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

@Configuration
public class MyBatisConfig {
	@Autowired
	private DataSource dataSource;
	
	@Bean(name="sqlSessionFactory")
    @ConditionalOnMissingBean //当容器里没有指定的Bean的情况下创建该对象
    public SqlSessionFactory sqlSessionFactory() {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		try {
	        // 设置数据源
	        sqlSessionFactoryBean.setDataSource(dataSource);
	        // 设置mybatis的主配置文件
	        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
	        Resource mybatisConfigXml = resolver.getResource("classpath:mybatis/mybatis-config.xml");
	        sqlSessionFactoryBean.setConfigLocation(mybatisConfigXml);
	        
	      //设置mybatis扫描的mapper.xml文件的路径(非常重要,否则找不到mapper.xml文件)
	        Resource[] mapperResources = resolver.getResources("classpath:mybatis/mapper/*.xml");
	        sqlSessionFactoryBean.setMapperLocations(mapperResources);
	        // 设置别名包,便于在mapper.xml文件中ParemeType和resultType不要写完整的包
	       
	        sqlSessionFactoryBean.setTypeAliasesPackage("com.sun.houses.model");
	        return sqlSessionFactoryBean.getObject();
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			throw  new RuntimeException();
		}
		 
    }

}

mapper-config.xml文件放在resources下的mybatis下:

<?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>
	<settings>
		
		<setting name="mapUnderscoreToCamelCase" value="true" />
		<setting name="cacheEnabled" value="true" /><!-- 全局映射器启用缓存 -->
		<setting name="useGeneratedKeys" value="true" />
		<setting name="defaultExecutorType" value="REUSE" />
		
	</settings>
</configuration>

mapper.xml,mapper,service,controller和第一种方式一样 第二种就配置完毕了

代码下载地址:https://download.csdn.net/download/sunqingzhong44/10653498

展开阅读全文

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