欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot系列 | 与mybatis整合

程序员文章站 2024-01-26 15:04:34
...

springboot与mybatis整合及其简单,与传统SSM框架整合少了很多烦人的配置,springboot与mybatis整合只需导入mybatis包,这样springboot就会帮我们自动配置及整合了。下面直接上所需代码:


依赖包引入


整个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.cwh</groupId>
	<artifactId>springbootMybatis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

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

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.10.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>

	<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.3.0</version>
		</dependency>
		
		<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.29</version>
        </dependency>
	</dependencies>

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


</project>


目录结构


整个demo的文件目录结构如下:

springboot系列 | 与mybatis整合

数据源配置及mybatis映射配置


application.properties:

spring.datasource.url=jdbc\:mysql\://127.0.0.1\:3306/springboots?useUnicode\=true&characterEncoding\=gbk&zeroDateTimeBehavior\=convertToNull
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# \u521D\u59CB\u5316\u5927\u5C0F\uFF0C\u6700\u5C0F\uFF0C\u6700\u5927  
spring.datasource.initialSize=5  
spring.datasource.minIdle=5  
spring.datasource.maxActive=20  
# \u914D\u7F6E\u83B7\u53D6\u8FDE\u63A5\u7B49\u5F85\u8D85\u65F6\u7684\u65F6\u95F4  
spring.datasource.maxWait=60000  

mybatis.mapper-locations=classpath*:mapper/*Mapper.xml
mybatis.type-aliases-package=com.cwh.springbootMybatis.entity


具体代码


UserMapper.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">
<mapper namespace="com.cwh.springbootMybatis.mapper.UserMapper">
 
  <select id="findUserInfo" resultType="com.cwh.springbootMybatis.entity.User">
    select id,name  from user;
  </select>
  <insert id="addUserInfo" parameterType="com.cwh.springbootMybatis.entity.User">
  	insert into user (id, name
      )
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}
      )
  </insert>
  <delete id="delUserInfo" parameterType="java.lang.Integer">
   delete from user where id = #{id,jdbcType=INTEGER}
  </delete>
 
</mapper>


UserMapper.java:

package com.cwh.springbootMybatis.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import com.cwh.springbootMybatis.entity.User;

@Mapper
public interface UserMapper {

	public List<User> findUserInfo();
	public int addUserInfo(User user);
	public int delUserInfo(int id);
}

User.java:

package com.cwh.springbootMybatis.entity;

import java.io.Serializable;  

public class User implements Serializable {  
    private Long id;  
    private String name;  
  
    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;  
    }  
  
    @Override  
    public boolean equals(Object o) {  
        if (this == o) return true;  
        if (o == null || getClass() != o.getClass()) return false;  
  
        User user = (User) o;  
  
        if (id != null ? !id.equals(user.id) : user.id != null) return false;  
  
        return true;  
    }  
  
    @Override  
    public int hashCode() {  
        return id != null ? id.hashCode() : 0;  
    }  
}  


UserService.java:

package com.cwh.springbootMybatis.service;

import java.util.List;

import com.cwh.springbootMybatis.entity.User;

public interface UserService {
    public List<User> getUserInfo();
    
    public void insert(User user);
}


UserServiceImpl.java:

package com.cwh.springbootMybatis.service.impl;

import java.util.List;

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

import com.cwh.springbootMybatis.entity.User;
import com.cwh.springbootMybatis.mapper.UserMapper;
import com.cwh.springbootMybatis.service.UserService;

@Service
public class UserServiceImpl implements UserService{

	@Autowired
    private UserMapper userMapper;

    public List<User> getUserInfo(){
        return userMapper.findUserInfo();
    }

    
	public void insert(User user) {
		userMapper.addUserInfo(user);
		
	}
}


UserController.java:

package com.cwh.springbootMybatis.controller;

import java.util.List;

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

import com.cwh.springbootMybatis.entity.User;
import com.cwh.springbootMybatis.service.UserService;
  
@RestController  
@RequestMapping("/user")  
public class UserController {  
	@Autowired
	private UserService userService;
	
	@RequestMapping("/getUserInfo")
    public List<User> getUserInfo() {
		List<User> user = userService.getUserInfo();
        System.out.println(user.toString());
        return user;
    }
	
	@RequestMapping("/addUserInfo")
    public String addUserInfo() {
		User user = new User();
		user.setId(3L);
		user.setName("cwh");
		userService.insert(user);
        return "success:"+user.toString();
    }
	
	
}  


Application.java:

package com.cwh.springbootMybatis;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application implements CommandLineRunner{

	@Autowired
    DataSource dataSource;
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
	
	/**
	 * 查看用了什么数据库连接池
	 */
	public void run(String... args) throws Exception {
        System.out.println("DATASOURCE = " + dataSource);
    }
}
说明:这里的实现CommandLineRunner接口,run方法是为了验证我们用了什么数据源,比如如果application.properties里没有配置如下信息:spring.datasource.type=com.alibaba.druid.pool.DruidDataSource,那么springboot默认给配置的是tomcat的jdbc,打印如下信息(部分信息):

DATASOURCE = aaa@qq.com{ConnectionPool[defaultAutoCommit=null; 


运行测试


访问http://localhost:8080/user/getUserInfo,页面打印如下信息:

[{"id":4,"name":"menco1"},{"id":5,"name":"menco"}]


以上算是基本完成mybatis的整合,下面是关于事务的引用,事务在这里引用很简单,只需用上这个@Transactional标签即可,这里先不开启事务试下异常是否会回滚:

public void insert(User user) {
		userMapper.addUserInfo(user);
		int i=1/0;
		userMapper.addUserInfo(user);
		
	}
这里我们可以发现抛出异常但是第一条执行语句还是可以被插入到数据库中


开启事务

 @Transactional
	public void insert(User user) {
		userMapper.addUserInfo(user);
		int i=1/0;
		userMapper.addUserInfo(user);
		
	}


源码下载:https://github.com/Menc0/springbootMybatis






相关标签: springboot