springBoot学习笔记十一:Mybatis

原文链接: https://my.oschina.net/tij/blog/3057359
一、项目说明

项目环境:jdk1.8+tomcat8+idea2018+mysql5.7+navicat

源代码github地址:

实现目标:通过整合mybatis,实现数据库的增,删,改,查操作。

二、整合说明

(1)通过idea等方式创建springBoot模板项目

springBoot学习笔记十一:Mybatis_第1张图片

(2)在pom.xml文件中添加相关依赖



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.5.RELEASE
         
    
    com.example
    demo
    0.0.1-SNAPSHOT
    demo
    Demo project for Spring Boot

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.0.1
        
        
        
            mysql
            mysql-connector-java
            runtime
        
        
        
            com.alibaba
            druid
            1.0.28
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


(3)在 application.properties中添加数据库和mybatis配置

#mysql数据库配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/root?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=root

#mybatis配置
#指定mapper.xml的位置
mybatis.mapper-locations = classpath:mapper/*Mapper.xml
#指定sqlMapConfig.xml的位置
mybatis.config-location = classpath:config/sqlMapConfig.xml

(4)数据库创建user表

/*
Navicat MySQL Data Transfer

Source Server         : test
Source Server Version : 50725
Source Host           : localhost:3306
Source Database       : root

Target Server Type    : MYSQL
Target Server Version : 50725
File Encoding         : 65001

Date: 2019-06-02 11:03:19
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `NAME` varchar(255) DEFAULT NULL,
  `SEX` varchar(255) DEFAULT NULL,
  `AGE` int(11) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '丽丽', '女', '19');
INSERT INTO `user` VALUES ('2', '麻子', '男', '18');

(5)在entity中创建User

package com.example.entity;

/**
 * 用户实体类
 */
public class User {
    private Integer id;
    private String name;
    private String sex;
    private Integer age;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public User(Integer id, String name, String sex, Integer age) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    public User() {
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                '}';
    }
}

(6)在mapper下创建UserMapper

package com.example.mapper;

import com.example.entity.User;
import java.util.List;

/**
 * 用户mapper
 */
public interface UserMapper {
    int addUser(User user);
    int updateUser(User user);
    int deleteUser(Integer id);
    User getUserById(Integer id);
    List getUserList();
}

(7)在config下创建sqlMapConfig.xml




    
    

(8)在mapper下创建UserMapper.xml





    
    
        insert into user(name, sex, age) values(#{name}, #{sex}, #{age})
    

    
    
        update user set name = #{name}, sex = #{sex}, age = #{age} where id = #{id}
    

    
    
        delete from user where id = #{id}
    

    
    

    
    


(9)在service下创建UserService

package com.example.service;

import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户service
 */
@Service
public class UserService {
    //注入用户mapper
    @Autowired
    public UserMapper userMapper;

    /**
     * 新增用户
     * @param user
     * @return
     */
    public int addUser(User user){
        return userMapper.addUser(user);
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    public int updateUser(User user){
        return userMapper.updateUser(user);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    public int deleteUser(Integer id){
        return userMapper.deleteUser(id);
    }

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    public User getUserById(Integer id){
        return userMapper.getUserById(id);
    }

    /**
     * 查询用户列表
     * @return
     */
    public List getUserList(){
        return userMapper.getUserList();
    }
}

(10)在controller下创建UserController

package com.example.controller;

import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 用户controller
 */
@RestController
public class UserController {
    @Autowired
    UserService userService;

    /**
     * mybatis测试
     */
    @GetMapping("/userOptions")
    public void userOptions(){
        //查询所有用户
        List userList = userService.getUserList();
        System.out.println("查询所有用户=============>" + userList);

        User user = new User();
        user.setName("张三");
        user.setAge(18);
        user.setSex("男");

        //新增用户
        int i = userService.addUser(user);
        System.out.println("新增用户=============>" + i);

        User user1 = new User();
        user1.setId(1);
        user1.setName("张三1");
        user1.setAge(181);
        user1.setSex("男1");

        //更新id等于1的用户
        int j = userService.updateUser(user1);
        System.out.println("更新用户=============>" + j);

        //查询id等于1的用户
        User user2 = userService.getUserById(1);
        System.out.println("根据id查询用户=============>" + user2);

        //删除id等于2的用户
        int k = userService.deleteUser(2);
        System.out.println("删除用户=============>" + k);

        //查询所有用户
        List userList1 = userService.getUserList();
        System.out.println("查询所有用户=============>" + userList1);
    }
}

(11)在启动类中添加mapper扫描注解

package com.example;

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

@SpringBootApplication
/*添加mybatis的mapper全局扫描*/
@MapperScan(basePackages = {"com.example.mapper"})
public class DemoApplication {

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

}

(12)测试

springBoot学习笔记十一:Mybatis_第2张图片

springBoot学习笔记十一:Mybatis_第3张图片

springBoot学习笔记十一:Mybatis_第4张图片

转载于:https://my.oschina.net/tij/blog/3057359

你可能感兴趣的:(springBoot学习笔记十一:Mybatis)