SpringBoot 整合 Mybatis

Spring Boot 更多干货 SpringBoot系列目录

项目目录结构,创建的model层就没放一起,以JAR形式引入

SpringBoot 整合 Mybatis_第1张图片

1、创建SQL表

CREATE TABLE t_user(
  id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  name CHAR(100) NOT NULL ,
  age INT NOT NULL 
) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;

2、在springboot项目引入 自动构建 generator 依赖 , 其他基础 boot依赖就不列举出来了


		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
			
			
				org.mybatis.generator
				mybatis-generator-maven-plugin
				1.3.2
				
					${basedir}/src/main/resources/generator/generatorConfig.xml
					true
					true
				
			
		
	

在使用项目中加入mybatis依赖

        
       
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.2
       

        
       
        
            com.github.pagehelper
            pagehelper
            5.1.8
        

在springboot项目的资源文件夹目录下创建generator目录,并新建 generatorConfig.xml 文件,内容如下:




    
    
    
        
            
            
            
        
        
        
        
        
            
        
        
        
            
            
        
        
        
            
        
        
        
            
        
        
        

3、配置好自己的本地路径后,运行maven 命令

mybatis-generator:generate

随后可以看到自动生成好的 dao、service、mapper文件,这里我把文件移动到自己想存放的位置,不一定要跟生成的一样

4、配置项目的 application.properties , 内容如下。


server.name=leopard-admin
server.port=8081
server.tomcat.uri-encoding=utf-8
#session失效时间
server.session-timeout=30


#数据源
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.maxActive = 20
spring.datasource.initialSize = 1
spring.datasource.maxWait = 60000
spring.datasource.minIdle = 1
spring.datasource.timeBetweenEvictionRunsMillis = 60000
spring.datasource.minEvictableIdleTimeMillis = 300000
spring.datasource.validationQuery = select 1
spring.datasource.poolPreparedStatements = true
spring.datasource.maxOpenPreparedStatements = 20

## 该配置节点为独立的节点,容易将这个配置放在spring的节点下,导致配置无法被识别
#注意:一定要对应mapper映射xml文件的所在路径
mybatis.mapper-locations = classpath*:com/leopard/admin/mapper/*.xml
# 注意:对应实体类的路径
mybatis.type-aliases-package = com.leopard.model

#pagehelper分页插件
pagehelper.helperDialect = mysql
pagehelper.reasonable = true
pagehelper.supportMethodsArguments = true
pagehelper.params = count=countSql

现在可以查看下生成的 mapper.xml 文件




  
    
    
    
  
  
    id, name, age
  
  
  
    delete from t_user
    where id = #{id,jdbcType=INTEGER}
  
  
    insert into t_user (id, name, age)
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=CHAR}, #{age,jdbcType=INTEGER})
  
  
    insert into t_user
    
      
        id,
      
      
        name,
      
      
        age,
      
    
    
      
        #{id,jdbcType=INTEGER},
      
      
        #{name,jdbcType=CHAR},
      
      
        #{age,jdbcType=INTEGER},
      
    
  
  
    update t_user
    
      
        name = #{name,jdbcType=CHAR},
      
      
        age = #{age,jdbcType=INTEGER},
      
    
    where id = #{id,jdbcType=INTEGER}
  
  
    update t_user
    set name = #{name,jdbcType=CHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  

生成的dao接口 , 注意 要加上 @Mapper

package com.leopard.admin.dao;

import org.apache.ibatis.annotations.Mapper;

import com.leopard.model.User;

@Mapper
public interface UserMapper {
	
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

手动新建接口 UserService 和实现类 UserServiceImpl

package com.leopard.admin.service;

public interface UserService {

	public long addUser(String name , int age);
}
package com.leopard.admin.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.leopard.admin.dao.UserMapper;
import com.leopard.admin.service.UserService;
import com.leopard.model.User;

@Service
public class UserServiceImpl implements UserService{
	
	@Autowired
	private UserMapper userMapper;

	@Override
	public long addUser(String name, int age) {
		
		User user = new User();
		user.setName(name);
		user.setAge(age);
		return userMapper.insertSelective(user);
	}

}

控制层 UserController 

package com.leopard.admin.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.leopard.admin.base.Message;
import com.leopard.admin.service.impl.UserServiceImpl;

@RestController
@RequestMapping(value="/user")
public class UserController {

	@Autowired
	private UserServiceImpl userServiceImpl;
	
	
	@RequestMapping(value = "/addUser")
	public Message addUser(String name , int age){
		
		long result = userServiceImpl.addUser(name, age);
		int code = (int) result;
		return new Message(code , "success");
	}
	
}

启动类 AdminApplication

package com.leopard.admin.application;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync
@ComponentScan(basePackages = { "com.leopard.admin"})
@MapperScan(basePackages = { "com.leopard.admin.dao" })
public class AdminApplication extends SpringBootServletInitializer {

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

}

5、启动后,访问测试

http://localhost:8081/user/addUser?name="张三"&age=14

成功效果 

SpringBoot 整合 Mybatis_第2张图片

 

异常:

Invalid bound statement (not found): com.leopard.UserMapper.insertSelective

解决方案:  https://blog.csdn.net/qq_40212930/article/details/91356013

https://blog.csdn.net/CoderTnT/article/details/80593723

 

Cannot determine embedded database driver class for database type NONE

解决方案: https://blog.csdn.net/Master_Shifu_/article/details/80420099  网上找了,这个真的很有效 尚未理解


        com.h2database 
        h2
        runtime 

你可能感兴趣的:(java)