第一步:导入maven依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 编译时的依赖,提供get、set、tostring、构造函数...-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.4.3</version>
</dependency>
第二步:配置myBatis (这里使用yml文件)
spring:
datasource:
username: root
password: gyxz123
url: jdbc:mysql://127.0.0.1:3306/mybatis?serverTimezone=Hongkong&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.cj.jdbc.Driver
第三步:创建实体类和mapper。
@Data
@TableName("user")
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
private int age;
private String email;
}
public interface UserMapper extends BaseMapper<User> {
}
第四步:注入Been
在Application中,扫描整个mapper 包
@MapperScan("com.hgp.mysql_plus.mapper")
@SpringBootApplication
public class MysqlPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MysqlPlusApplication.class, args);
}
}
最后测试:
@Resource
private UserMapper userMapper;
@Test
void contextLoads() {
User user = userMapper.selectById(1);
System.out.println(user);
}