使用MybatisPlus连接mysql并获取数据
    		       		warning:
    		            这篇文章距离上次修改已过440天,其中的内容可能已经有所变动。
    		        
        		                
                要使用MyBatis-Plus连接MySQL并获取数据,你需要完成以下步骤:
- 添加MyBatis-Plus依赖到你的项目中。
- 配置MyBatis-Plus连接MySQL的数据源和事务管理器。
- 创建实体类映射数据库表。
- 创建Mapper接口继承BaseMapper,MyBatis-Plus会提供基本的CRUD方法。
- 使用MyBatis-Plus提供的方法来查询数据。
以下是一个简单的例子:
步骤1:添加依赖
在pom.xml中添加MyBatis-Plus和MySQL驱动的依赖:
<dependencies>
    <!-- MyBatis-Plus -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>最新版本</version>
    </dependency>
    <!-- MySQL 驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>最新版本</version>
    </dependency>
</dependencies>步骤2:配置数据源
在application.properties或application.yml中配置数据源:
# application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/数据库名?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=数据库用户名
spring.datasource.password=数据库密码
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver步骤3:创建实体类
import com.baomidou.mybatisplus.annotation.TableName;
 
@TableName("表名")
public class Entity {
    // 字段和数据库表列对应
}步骤4:创建Mapper接口
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
 
@Mapper
public interface EntityMapper extends BaseMapper<Entity> {
    // MyBatis-Plus会提供基本的CRUD方法
}步骤5:查询数据
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
@Service
public class EntityService {
 
    @Autowired
    private EntityMapper entityMapper;
 
    public Entity getById(Long id) {
        return entityMapper.selectById(id);
    }
 
    // 其他业务逻辑
}以上步骤构成了一个简单的MyBatis-Plus使用示例。记得替换实体类名、表名、数据库URL、用户名和密码为你的实际配置。
评论已关闭