Spring Boot入门教程-集成Mybatis

Spring Boot 入门教程继续,这里写一下Mybatis 的集成。废话不多说。

1.加入依赖,如果项目创建时已勾选Mybatis 和MySQL,这里可一省略。没有勾选的在pom.xml中加入以下代码:

		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.1</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
2.application.proeperties加入数据源配置(根据数据库自行修改)
########################################################
###datasource
########################################################
spring.datasource.url = jdbc:mysql://localhost:3306/dabase_name?characterEncoding=utf8&useSSL=true
spring.datasource.username = root
spring.datasource.password = 0000
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10

 

3.创建表

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(40) DEFAULT NULL COMMENT '用户名',
  `password` varchar(40) DEFAULT NULL COMMENT '密码',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

随便加几条数据:


4.创建实体类

 

public class User {
    private int id;
    private String username;
    private String password;
    ...
    setter /getter 省略


5.创建Mapper

public interface UserMapper {

    @Select("select * from User where id = #{id}")
    User getById(long id);

}


6.创建service 接口

public interface  IUserService {
    User getById(int id);
}


7.创建service实现类

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User getById(int id) {
        return userMapper.getById(id);
    }
}

8.在User Controller 中添加

 @Autowired
    private IUserService userService;

    @RequestMapping("get")
    @ResponseBody
    public User getUser(int id) {
        System.out.println(id);
        return userService.getById(id);
    }

9.在SpringBootDemoApplication 中加入

@MapperScan("com.example.demo.mapper")

项目结构如图:

 

10.浏览器中请求  http://localhost:8080/get?id=1


得到了我们想要的结果。

这种方式在实际项目中使用不太灵活,所以点到为止,后续博客会将传统的Mybatis 配置文件加入进来,那样畅快的书写SQL了。

Myatis xml配置方式 播客已发,欢迎点击

Spring boot 入门教程-mybatis xml方式集成

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值