在之前的项目基础上继续整合Mybatis,上一讲我们通过Mybatis的逆向工程生成了Bean,映射文件和DAO接口,这一讲我们要用这些生成的类
首先我们创建一个Controller
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("test")
public @ResponseBody AdminUser getUserById(Integer id){
return userService.getUserById(id);
}
}
这个看到代码里面有用到Servcie,我们并没有这个Service,所以我们需要创建一个Service接口
public interface UserService {
AdminUser getUserById(Integer id);
}
创建实现类:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private AdminUserMapper adminUserMapper;
@Override
public AdminUser getUserById(Integer id) {
return adminUserMapper.selectByPrimaryKey(id);
}
}
这时候还不需要,因为AdminUserMapper 接口并不是一个Bean,所以有两种方式解决
1、直接在AdminUserMapper加注解@Mapper
2、我们有很多类的时候这种方式有点繁琐,所以我们可以直接使用扫描的方式
在SpringBoot的启动类中添加注解@MapperScan
@SpringBootApplication
@MapperScan(basePackages = "com.drondea.springboot.dao")
public class SpringbootmybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootmybatisApplication.class, args);
}
}
这样就不需要注解@Mapper了
经过上面的一些列配置,我们是不是认为可以了,其实还不行,还需要添加插件
在pom文件的中添加
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
配置文件中需要增加连接数据库的配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.1.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8 spring.datasource.username=root spring.datasource.password=123
现在就可以了,启动springBoot服务,通过浏览器访问,可以返回json,说明集成mybatis可以了。 访问地址:http://localhost:8080/test?id=1