Mybitas入门使用

创建如下项目结构

项目目录结构如下:

创建数据库和数据表:

CREATE DATABASE mybatis;

CREATE TABLE tb_user(
 id INT(11) PRIMARY KEY AUTO_INCREMENT,
 username VARCHAR(255),
 password VARCHAR(255),
);

INSERT INTO tbl_employee VALUES('tom','tom@qq.com');

编写实体类 entity.User

import lombok.Data;

import java.io.Serializable;
@Data
public class User implements Serializable {
    private Integer id;//编号
    private String username;//用户名
    private String password;//密码
    //省略get set方法
}

编写接口mapper.UserMapper
注意:需要使用@Mapper注解,不然SpringBoot无法扫描

@Mapper//指定这是一个操作数据库的mapper
public interface UserMapper {
    List<User> findAll();
    User selectByid(Integer id);
    Integer addUser(User user);
    Integer deleteUserByid(Integer id);
    Integer update( User user);
    Integer updateTest( ArrayList<Integer> id);
}

编写在resources文件中创建 mapper/UserMapper.xml文件
注意:
1.namespace中需要与使用@Mapper的接口对应
2.UserMapper.xml文件名称必须与使用@Mapper的接口一致
3.标签中的id必须与@Mapper的接口中的方法名一致,且参数一致

<?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 namespace="com.dj.launch.mapper.UserMapper">
    <select id="findAll" resultType="User">
        SELECT * FROM tb_user
    </select>
    <select id="selectByid" resultType="User">
        select * from tb_user where id=#{id}
    </select>
    <insert id="addUser" >
    insert into tb_user(username,password)  values(#{username},#{password})
    </insert>
    <delete id="deleteUserByid">
        delete from tb_user where id=#{id}
    </delete>
    <update id="update">
        update tb_user
        <set>
            <if test="username != null">`username` = #{username}, </if>
        </set>
        where id in #{id}
    </update>

编写接口service.UserService

public interface UserService {
    List<User> findAll();
    User selectByid(Integer id);
    Integer addUser(User user);
    Integer deleteUserByid(Integer id);
    Integer update(User user);
    Integer updateTest(ArrayList<Integer> id);
//    User updateUserByid();
}

编写实现类service.impl.UserServiceimpl
注意:需要在接口实现类中使用@Service注解,才能被SpringBoot扫描,在Controller中使用@Authwired注入

@Service
public class UserServiceimpl implements UserService {

    @Autowired(required = false)
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }
    public  User selectByid(Integer id){
        return userMapper.selectByid( id);
    }
    public Integer addUser(User user){
        return userMapper.addUser(user);
    }
    public  Integer deleteUserByid(Integer id){
        return userMapper.deleteUserByid(id);
    }
    public Integer update(User user){
        return userMapper.update(user);
    }
    public Integer updateTest(ArrayList<Integer> id){
        return userMapper.updateTest(id);
    }

}

编写api接口controller.UserController

@RestController
//@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @RequestMapping("hello")
    public  String hello(){
        return "Hello";
    }

    @RequestMapping("findall")
    @ResponseStatus(HttpStatus.OK)
    public List<User> findAll(){
        return userService.findAll();
    }

    @GetMapping("selectbyid/{id}")
    public User selectByid(@PathVariable("id") Integer id){
        String str = String.format("id----%s",id);
        System.out.println(str);
        return userService.selectByid(id);
    }
    @PostMapping("add")
    @ResponseStatus(HttpStatus.CREATED)
    public   Integer addUser(@RequestBody User user){
        System.out.println(user);
        return  userService.addUser(user);

    }
    @DeleteMapping("delete/{id}")
    public  Integer deleteUserByid(@PathVariable("id") Integer id){
        return userService.deleteUserByid(id);
    }

    @PutMapping("update/{id}")
    public Integer update(@PathVariable("id") Integer id ,@RequestBody User user ){
        System.out.println("put----");
        System.out.println(user);
        System.out.println(user.getClass().getName());
        user.setId(id);
        return userService.update(user);
    }
    @PutMapping("updatetest")
    public Integer updateTest(@RequestBody ArrayList<Integer> id){
        return userService.updateTest(id);
    }
}

在启动类中添加对@MapperScan的扫描

@SpringBootApplication
@MapperScan("com.dj.launch.mapper")//使用MapperScan批量扫描所有的Mapper接口;
public class SpringbootmybitasCurdApplication {

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

}

配置文件

在resources中创建application.yml文件,并编写配置

server:
  port: 8081
spring:
  #数据库连接配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf-8&useSSL=false
    username: root
    password: 123456

#mybatis的相关配置
mybatis:
  #mapper配置文件
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.dj.launch.entity
  #开启驼峰命名
  configuration:
    map-underscore-to-camel-case: true

注意:
1.mybatis中的mapper-locations是mapper的xml文件位置
2.mybatis中的type-aliases-package是为了配置xml文件中resultType返回值的包位置,如果未配置请使用全包名如下:

<select id="findAll" resultType="com.zhg.demo.mybatis.entity.User">
        SELECT * FROM tb_user
</select>

创建数据库和数据表

-- ----------------------------
-- Table structure for tb_user
-- ----------------------------
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
  `id` int(11) NOT NULL,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tb_user
-- ----------------------------
INSERT INTO `tb_user` VALUES ('1', 'laowang', '112233');
INSERT INTO `tb_user` VALUES ('2', 'laoli', '123456');

参考链接:https://www.jianshu.com/p/541874714907
https://mp.weixin.qq.com/s/eQpexQL7Thc6DUh9gP-_TA
https://www.jb51.net/article/113582.htm

posted @ 2021-03-03 17:18  离人怎挽_wdj  阅读(188)  评论(0编辑  收藏  举报