springboot整合mybatis

依赖pom.xml

<properties>
    <mybatis-spring-boot-starter.version>1.3.2</mybatis-spring-boot-starter.version>
</properties>
<dependency>    <groupId>org.mybatis.spring.boot</groupId>    <artifactId>mybatis-spring-boot-starter</artifactId>    <version>${mybatis-spring-boot-starter.version}</version></dependency>

application.properties

# 实体类包路径
mybatis.type-aliases-package=com.combo.bean
mybatis.mapper-locations=classpath:com.combo.mapper/*.xml

实体类bean

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    @NonNull
    private int id;
    private String name;
    private String age;
    private String gender;
    private String address;
}

mapper接口

@Mapper
public interface UserMapper {
    //@Select("select * from user")   //配置的话就不用下面的xml了
    List<User> allUsers();
}

mapper.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 namespace="com.combo.mapper.UserMapper">
    <select id="allUsers" resultType="com.combo.bean.User">
        SELECT * FROM user
    </select>
</mapper>

service接口

public interface UserService {
    String allUsers();
}

serviceimpl实现类

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public String allUsers() {
        List<User> users = userMapper.allUsers();
        return users.toString();
    }
}

controller类

@RestController
public class TestController {
    @Autowired
    private UserService userService;

    @RequestMapping("hello")
    public String hello(){
        return "hello world";
    }

    @RequestMapping("allUsers")
    public String allUsers() {
        return userService.allUsers();
    }
}

启动类

@SpringBootApplication
//@MapperScan(value = "com.combo.mapper")       加入之后可以不用在mapper接口上加@mapper注解  必须有其一,否则会提示报错,找不到mapper的bean注入
@ComponentScan(value = {"com.combo.controller","com.combo.service"})    //扫描注解
public class TestDruidApplication {

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

}

可能的报错和解决:

1.org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)

在pom.xml加入

<build>  <resources>        <resource>            <directory>src/main/java</directory>            <includes>                <include>**/*.xml</include>            </includes>        </resource>    </resources></build>

http://localhost/allUsers   若下图则成功了

springboot整合mybatis

相关推荐