1. 程式人生 > >springboot整合mybatis兩種方式

springboot整合mybatis兩種方式

springboot整合mybaits有兩種方式:

第二種:使用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("[email protected]");
		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和第一種方式一樣 第二種就配置完畢了