创建模块Springboot_05_mybaits_plus
步骤如下
勾选Driver即可,由于没有默认选项Mybatisplus框架可选(希望国人的东西能够更受关注和尊重)
在pom.xml中添加mybatis-plus的依赖坐标推荐网站,可以去查找想要的依赖坐标https://mvnrepository.com/https://mvnrepository.com/
最后的pom.xml如下:
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.6.7
com.example
springboot_05_mybatis_plus
0.0.1-SNAPSHOT
11
org.springframework.boot
spring-boot-starter
com.baomidou
mybatis-plus-boot-starter
3.4.2
org.projectlombok
lombok
true
1.18.4
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
然后可以把配置文件改成yml格式,加入dataSource相关信息
#相关配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC
username: root
password: root
编写User类和相关的UserDao接口
我这里直接使用lombok注解快速生成相关方法
注意要加上@TableName("account")注解,我数据库的表名为account, 不加上这条注解会出现找不到表的错误。
package com.example.domain;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("account")
public class User {
private Integer id;
private String name;
private double money;
}
package com.example.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserDao extends BaseMapper {
}
ok,编写测试代码
package com.example;
import com.example.dao.UserDao;
import com.example.domain.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Springboot05MybatisPlusApplicationTests {
@Autowired
private UserDao userDao;
@Test
void contextLoads() {
User user = userDao.selectById(2);
System.out.println(user);
}
}
account的内容如下
运行,成功
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)