在spring boot项目引入mybatis plus后的的案例实践
在Spring Boot项目中引入MyBatis Plus后,可以通过以下步骤进行配置和使用:
- 在
pom.xml
中添加MyBatis Plus的依赖:
<dependencies>
<!-- 其他依赖... -->
<!-- MyBatis Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.x.x</version> <!-- 替换为实际版本号 -->
</dependency>
<!-- 数据库驱动,以MySQL为例 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.x.x</version> <!-- 替换为实际版本号 -->
</dependency>
</dependencies>
- 在
application.properties
或application.yml
中配置数据库信息:
# application.properties 示例
spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- 创建实体类对应数据库表:
import com.baomidou.mybatisplus.annotation.TableName;
@TableName("user")
public class User {
private Long id;
private String name;
private Integer age;
private String email;
// 省略getter和setter方法...
}
- 创建Mapper接口:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {
// MyBatis Plus会自动处理CRUD操作
}
- 使用MyBatis Plus提供的服务:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final UserMapper userMapper;
@Autowired
public UserService(UserMapper userMapper) {
this.userMapper = userMapper;
}
public boolean saveUser(User user) {
return userMapper.insert(user) > 0;
}
// 更多业务方法...
}
- 在Spring Boot启动类上添加
@MapperScan
注解,指定Mapper接口所在的包:
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.yourpackage.mapper")
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
以上步骤展示了如何在Spring Boot项目中引入MyBati
评论已关闭