系列一、Spring + SpringMVC + MyBatis整合

一、概述

整合 Spring、SpringMVC、MyBatis。

二、整合步骤

2.1、pom


	
	
		org.projectlombok
		lombok
		1.18.22
	
	
		org.slf4j
		slf4j-api
		1.7.32
	
	
		ch.qos.logback
		logback-classic
		1.2.10
	

	
	
		com.alibaba
		fastjson
		1.2.76
	
	
		org.apache.commons
		commons-collections4
		4.3
	
	
		org.apache.commons
		commons-lang3
		3.11
	
	
		cn.hutool
		hutool-all
		5.7.22
	
	
		com.fasterxml.jackson.core
		jackson-databind
		2.12.1
	

	
		org.apache.logging.log4j
		log4j-web
		2.12.1
	

	
	
		org.springframework
		spring-webmvc
		5.3.4
	
	
		org.mybatis
		mybatis
		3.5.6
	
	
		org.mybatis
		mybatis-spring
		2.0.6
	
	
		mysql
		mysql-connector-java
		8.0.26
	
	
		org.springframework
		spring-jdbc
		5.3.4
	
	
		org.springframework
		spring-aop
		5.3.4
	

	
		org.springframework
		spring-beans
		5.3.4
	
	
		org.springframework
		spring-context
		5.3.4
	
	
		org.springframework
		spring-core
		5.3.4
	
	
		org.springframework
		spring-expression
		5.3.4
	
	
		org.springframework
		spring-tx
		5.3.4
	

	
	
		cglib
		cglib
		3.1
	
	
		aopalliance
		aopalliance
		1.0
	
	
		org.aspectj
		aspectjweaver
		1.9.19
	




	
	
		
			src/main/java
			
				**/*.xml
			
		
		
			src/main/resources
		
	

	
		
			org.apache.maven.plugins
			maven-compiler-plugin
			3.10.1
			
				8
				8
			
		
	

2.2、db.properties

db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/20231106_ssm?useSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT
db.username=root
db.password=123456

2.3、init.sql

drop DATABASE if EXISTS 20231106_ssm;
create DATABASE 20231106_ssm;
use 20231106_ssm;

CREATE TABLE `user`  (
                         `id` int NOT NULL AUTO_INCREMENT COMMENT '主键',
                         `username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户名',
                         `password` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '密码',
                         `age` int NULL DEFAULT NULL COMMENT '年龄',
                         PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

INSERT INTO `user` VALUES (1, 'zhangsan', 'zhangsan123', 23);
INSERT INTO `user` VALUES (2, 'lisi', 'lisi123', 24);

2.4、applicationContext.xml



    

    
        
    

    
        
        
        
        
    

    
        
        
        
            
                
                
            
        
        
        
    
    
        
        
    

    
    
        
    

    
    
        
        
            
            
        
    

    
        
        
    

2.5、dispatcherServlet.xml




    
        
    
    

2.6、web.xml




    
    
        contextConfigLocation
        classpath:applicationContext.xml
    
    
        org.springframework.web.context.ContextLoaderListener
    

    
    
        springmvc
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:dispatcherServlet.xml
        
    
    
        springmvc
        /
    

    
    
        encodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            UTF-8
        
        
            forceRequestEncoding
            true
        
        
            forceResponseEncoding
            true
        
    
    
        encodingFilter
        /*
    

2.7、UserDO

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2023/11/6 11:34
 * @Description:
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@ToString(callSuper = true)
public class UserDO implements Serializable {
    /**
     * 编号
     */
    private Integer id;

    /**
     * 用户名
     */
    private String username;

    /**
     * 密码
     */
    private String password;

    /**
     * 年龄
     */
    private Integer age;
}

2.8、UserMappper

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2023/11/6 11:35
 * @Description:
 */
public interface UserMapper {

    /**
     * 添加用户
     * @param param
     */
    void saveUser(UserDO param);

    /**
     * 查询所有的用户
     * @return
     */
    List listAllUser();

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    UserDO getUserById(Integer id);
}

2.9、UserMapper.xml





    
        insert into `user`(username,password,age) values (#{username},#{password},#{age})
    


    

    

2.10、UserService

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2023/11/6 11:36
 * @Description:
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public List listAllUser() {

        return userMapper.listAllUser();
    }

    public void saveUser(UserDO param) {
        userMapper.saveUser(param);
    }

    /**
     * 不加此注解的话,将会执行多次数据库查询
     * 参考:https://blog.51cto.com/u_15942107/6019692
     * @param id
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public UserDO getUserById(Integer id) {
        UserDO u1 = userMapper.getUserById(id);
        UserDO u2 = userMapper.getUserById(id);
        UserDO u3 = userMapper.getUserById(id);
        System.out.println(u1);
        System.out.println(u2);
        System.out.println(u3);

        return userMapper.getUserById(id);
    }
}

2.11、UserController

@Slf4j
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/saveUser")
    public String saveUser(@RequestBody UserDO param) {
        log.info("UserController saveUser param:{}", param);
        userService.saveUser(param);
        return "SUCCESS";
    }

    @GetMapping("/listAllUser")
    public List listAllUser() {
        log.info("=================>listAllUser");
        return userService.listAllUser();
    }

    @GetMapping("/getUserById/{id}")
    public UserDO getUserById(@PathVariable("id") Integer id) {
        log.info("=================>getUserById id:{}",id);
        return userService.getUserById(id);
    }

}

三、测试

http://localhost:8080/listAllUser

系列一、Spring + SpringMVC + MyBatis整合_第1张图片

系列一、Spring + SpringMVC + MyBatis整合_第2张图片

四、项目结构

系列一、Spring + SpringMVC + MyBatis整合_第3张图片 

你可能感兴趣的:(SSM系列,spring,mybatis,java)