SpringBoot 2.x (9):整合Mybatis註解實戰

SSM框架再熟悉不過了,不過之前一般是使用XML寫SQL語句java

這裏用SpringBoot整合Mybatis而且使用註解進行開發mysql

 

依賴:web

        <!-- Mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- Druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.6</version>
        </dependency>

 

配置:不須要指定驅動類,SpringBoot會自動掃描:com.mysql.cj.jdbc.Driverspring

spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=xuyiqing
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

 

user表:sql

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(128) DEFAULT NULL,
  `phone` varchar(16) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  `age` int(4) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

對應實體類:apache

package org.dreamtech.springboot.domain;

import java.util.Date;

public class User {
    private int id;
    private String name;
    private String phone;
    private int age;
    private Date createTime;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public int getAge() {
        return age;
    }

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

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", phone=" + phone + ", age=" + age + ", createTime=" + createTime
                + "]";
    }
}

 

添加用戶的Demo作整合springboot

Mapper:mybatis

package org.dreamtech.springboot.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.dreamtech.springboot.domain.User;

public interface UserMapper {
    @Insert("INSERT INTO user(name,phone,create_time,age) VALUES(#{name},#{phone},#{createTime},#{age})")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    int insert(User user);
}

 

Service:app

package org.dreamtech.springboot.service;

import org.dreamtech.springboot.domain.User;

public interface UserService {
    int add(User user);
}
package org.dreamtech.springboot.service.impl;

import org.dreamtech.springboot.domain.User;
import org.dreamtech.springboot.mapper.UserMapper;
import org.dreamtech.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

    @Override
    public int add(User user) {
        userMapper.insert(user);
        int id = user.getId();
        return id;
    }

}

 

Controller:框架

package org.dreamtech.springboot.controller;

import java.util.Date;

import org.dreamtech.springboot.domain.User;
import org.dreamtech.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/add")
    private Object add() {
        User user = new User();
        user.setAge(18);
        user.setCreateTime(new Date());
        user.setName("admin");
        user.setPhone("100000");
        userService.add(user);
        return user;
    }
}

 

最後別忘了一個細節:在啓動類加上Mapper掃描註解

package org.dreamtech.springboot;

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

@SpringBootApplication
@MapperScan("org.dreamtech.springboot.mapper")
public class SpringbootApplication {

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

}

 

啓動後訪問localhost:8080/user/add

測試成功!

 

繼續完成增刪改查

有時候,開發者但願可以在控制檯打印SQL語句,須要加一行配置文件

mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

 

CRUD完整實現:

package org.dreamtech.springboot.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.dreamtech.springboot.domain.User;

public interface UserMapper {
    /**
     * 插入對象
     * 
     * @param user 對象
     * @return int
     */
    @Insert("INSERT INTO user(name,phone,create_time,age) VALUES(#{name},#{phone},#{createTime},#{age})")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    int insert(User user);

    /**
     * 查找所有
     * 
     * @return
     */
    @Select("SELECT * FROM user")
    @Results({ @Result(column = "create_time", property = "createTime", javaType = java.util.Date.class) })
    List<User> getAll();

    /**
     * 根據ID找對象
     * 
     * @param id ID
     * @return
     */
    @Select("SELECT * FROM user WHERE id=#{id}")
    @Results({ @Result(column = "create_time", property = "createTime", javaType = java.util.Date.class) })
    User findById(Long id);

    /**
     * 更新對象
     * 
     * @param user 對象
     * @return
     */
    @Update("UPDATE user SET name=#{name} WHERE id=#{id}")
    int update(User user);

    /**
     * 根據ID刪除對象
     * 
     * @param id ID
     * @return
     */
    @Delete("DELETE FROM user WHERE id=#{id}")
    int delete(Long id);
}
package org.dreamtech.springboot.service;

import java.util.List;

import org.dreamtech.springboot.domain.User;

public interface UserService {
    int add(User user);

    List<User> getAll();

    User findById(Long id);

    int update(User user);

    int delete(Long id);
}
package org.dreamtech.springboot.service.impl;

import java.util.List;

import org.dreamtech.springboot.domain.User;
import org.dreamtech.springboot.mapper.UserMapper;
import org.dreamtech.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

    @Override
    public int add(User user) {
        userMapper.insert(user);
        int id = user.getId();
        return id;
    }

    @Override
    public List<User> getAll() {
        return userMapper.getAll();
    }

    @Override
    public User findById(Long id) {
        return userMapper.findById(id);
    }

    @Override
    public int update(User user) {
        return userMapper.update(user);
    }

    @Override
    public int delete(Long id) {
        return userMapper.delete(id);
    }

}
package org.dreamtech.springboot.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dreamtech.springboot.domain.User;
import org.dreamtech.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    private Map<String, Object> modelMap = new HashMap<String, Object>();

    @GetMapping("/add")
    private Object add() {
        User user = new User();
        user.setAge(18);
        user.setCreateTime(new Date());
        user.setName("admin");
        user.setPhone("100000");
        userService.add(user);
        return user;
    }

    @GetMapping("/getall")
    private Object getAll() {
        modelMap.clear();
        List<User> list = userService.getAll();
        if (list.size() > 0) {
            modelMap.put("users", list);
            modelMap.put("success", true);
        } else {
            modelMap.put("success", false);
        }
        return modelMap;
    }

    @GetMapping("/findbyid")
    private Object findById(Long id) {
        if (id == null || id < 0) {
            modelMap.put("success", false);
        }
        modelMap.clear();
        User user = userService.findById(id);
        if (user != null) {
            modelMap.put("success", true);
            modelMap.put("user", user);
        } else {
            modelMap.put("success", false);
        }
        return modelMap;
    }

    @GetMapping("/update")
    private Object update() {
        modelMap.clear();
        User user = new User();
        user.setId(1);
        user.setName("newAmdin");
        int effectedNum = userService.update(user);
        if (effectedNum > 0) {
            modelMap.put("success", true);
        } else {
            modelMap.put("success", false);
        }
        return modelMap;
    }

    @GetMapping("/delete")
    private Object delete(Long id) {
        if (id == null || id < 0) {
            modelMap.put("success", false);
        }
        modelMap.clear();
        int effectedNum = userService.delete(id);
        if (effectedNum > 0) {
            modelMap.put("success", true);
        } else {
            modelMap.put("success", false);
        }
        return modelMap;
    }
}

 

 事務:

 若是用到事務相關的內容,須要在Service層加入一個註解@Transactional

    @Transactional(propagation = Propagation.REQUIRED)
相關文章
相關標籤/搜索