springboot整合mybatis

依赖pom.xml


    1.3.2

org.mybatis.spring.boot
mybatis-spring-boot-starter
${mybatis-spring-boot-starter.version}

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 allUsers();
}

mapper.xml




    

service接口

public interface UserService {
    String allUsers();
}

serviceimpl实现类

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public String allUsers() {
        List 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加入


  

src/main/java

**/*.xml



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

springboot整合mybatis_第1张图片

你可能感兴趣的:(springboot整合mybatis)