springBoot学习笔记十一:Mybatis

一、项目说明

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

源代码github地址:

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

二、整合说明

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

e326dfd232f9a68d4233c3000e53a4b3736.jpg

(2)在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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--mybatis依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!--mysql依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--druid连接池依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.28</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

</project>

(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<User> getUserList();
}

(7)在config下创建sqlMapConfig.xml

<?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>
    <typeAliases>
    </typeAliases>
</configuration>

(8)在mapper下创建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-->
<mapper namespace="com.example.mapper.UserMapper" >
    <!--新增用户-->
    <insert id="addUser" parameterType="com.example.entity.User">
        insert into user(name, sex, age) values(#{name}, #{sex}, #{age})
    </insert>

    <!--修改用户-->
    <update id="updateUser" parameterType="com.example.entity.User">
        update user set name = #{name}, sex = #{sex}, age = #{age} where id = #{id}
    </update>

    <!--删除用户-->
    <delete id="deleteUser" parameterType="int">
        delete from user where id = #{id}
    </delete>

    <!--根据id查询用户-->
    <select id="getUserById" parameterType="int" resultType="com.example.entity.User">
        select * from user where id = #{id}
    </select>

    <!--查询用户列表-->
    <select id="getUserList" resultType="com.example.entity.User">
        select * from user
    </select>

</mapper>

(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<User> 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<User> 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<User> 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)测试

ad5356a544aae42ebd17267d0967f4cc42c.jpg

d7c6ad0a869283c8d8279663f7c5e602560.jpg

b138fbd6374a962a5d09029743e7c6b130b.jpg

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值