SpringBoot整合Mybatis

文章目录

  • 实体类
  • Mapper接口
  • Mapper.xml
  • Application.properties
  • Controller类
  • 错误

实体类

package lyr.pojo;
import lombok.Data;
/**
 * @author lei
 * @date 2020/5/21 14:26
 */
@Data//lombok
public class User {
    int id;
    String name;
    String username;
    String password;
}

Mapper接口

package lyr.mapper;
package lyr.mapper;

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

import java.util.List;

/**
 * @author lei
 * @date 2020/5/21 14:28
 */
@Repository
public interface UsersMapper {
    List<User> findAll();
    User find(int id);
}

Mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="lyr.mapper.UsersMapper">
    <select id="findAll" resultType="lyr.pojo.User">
        select * from users;
    </select>
    <select id="find" resultType="lyr.pojo.User">
        select * from users where id =1;
    </select>
</mapper>

Application.properties

#数据库配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/learn?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
#端口
server.port=8081
#mybatis配置
mybatis.mapperLocations=classpath:mapper/*.xml

Controller类

package lyr.controller;
import lyr.mapper.UsersMapper;
import lyr.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
 * @author lei
 * @date 2020/5/21 14:36
 */
@RestController
public class UserController {
    @Autowired
    UsersMapper usersMapper;

    @RequestMapping("findAll")
    public List<User> findAll(){
        return usersMapper.findAll();
    }
}

错误

**Error1**
java.lang.IllegalArgumentException: Result Maps collection does not contain value for lyr.pojo.User

解决:使用resultMap时,必须要有<resultMap></resultMap>标签指明id和返回类型以及表字段的对应关系。

如果是直接返回一个用户定义的实体类型,则要使用resultType,弄混淆就会报错。

**Error2**
IDEA存入数据库数据中文乱码

解决:连接数据库是添加字符编码 characterEncoding=UTF-8

**Error3**
 No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.

importRegistry' available

解决:数据库连接的配置有错误

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读