SpringBoot11 整合MyBatis

官方文档
官方文档
官方文档

启动项目

依赖配置

  • 导入jdbc mysql依赖
  • 导入mybatis-spring-boot-stater依赖
  • 可以导入lombok

		<dependency>
			<groupId>org.projectlombokgroupId>
			<artifactId>lombokartifactId>
			<optional>trueoptional>
		dependency>

		<dependency>
			<groupId>org.mybatis.spring.bootgroupId>
			<artifactId>mybatis-spring-boot-starterartifactId>
			<version>2.1.1version>
		dependency>

		<dependency>
			<groupId>mysqlgroupId>
			<artifactId>mysql-connector-javaartifactId>
			<scope>runtimescope>
		dependency>

		

再配置文件中对数据库进行配置


spring:
  datasource:
    username: root
    password: xxxxx
    url: jdbc:mysql://47.98.144.17:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver

mybatis:
  type-aliases-package: com.zj.pojo  # 这个就是实体类的配置(都需要进行)
  mapper-locations: classpath:Mapper/*.xml # 这个是mapper文件的位置

编写类

编写pojo


package com.zj.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/5/11 0011  16:21
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private Integer id;
    private String name;
    private String pwd;
}

编写mapper

package com.zj.mapper;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/5/11 0011  16:23
 */

import com.zj.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper //表明本类是一个MyBatis的Mapper
@Repository
public interface UserMapper {

    public List<User> findAllUsers();

    public User findUserById(Integer id);

    public void addUser(User user);

    public void deleteUser(Integer id);

    public void update(User user);

}


编写controller(为了方便测试)

package com.zj.controller;

import com.zj.mapper.UserMapper;
import com.zj.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/5/11 0011  16:22
 */
@RestController
public class UserController {

    @Autowired
   private UserMapper userMapper;

    @RequestMapping("/list")
    public List<User> findAllusers(){
        List<User> users = userMapper.findAllUsers();
        return users;
    }
}


映射文件mapper





<mapper namespace="com.zj.mapper.UserMapper">

    <select id="findAllUsers" resultType="user">
        select * from user;
    select>



mapper>

测试

SpringBoot11 整合MyBatis_第1张图片

你可能感兴趣的:(springboot)