MyBatisplus 数据库

mybatisplus如何连接数据库

小亿
246
2024-02-02 17:32:32
栏目: 大数据

MyBatis Plus 是一个基于 MyBatis 的 ORM 框架,它可以简化数据库连接和操作的过程。下面是连接数据库的步骤:

1、添加依赖:在项目的 pom.xml 文件中添加 MyBatis Plus 的依赖。可以到 Maven 中央仓库搜索 `mybatis-plus-boot-starter` 并将其添加到项目依赖中。

```xml

com.baomidou

mybatis-plus-boot-starter

最新版本

```

2、配置数据源:在项目的配置文件中配置数据源,可以使用任何符合 JDBC 规范的数据源,比如 Druid、HikariCP 等。

3、配置 MyBatis Plus:在项目的配置文件中添加 MyBatis Plus 的配置项。

```properties

# 数据库类型

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

# 数据库连接信息

spring.datasource.url=jdbc:mysql://localhost:3306/mybatisplus?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false

spring.datasource.username=root

spring.datasource.password=123456

# 数据库驱动

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# MyBatis Plus 配置项

# 指定 MyBatis Plus 的 mapper 扫描路径

mybatis-plus.mapper-locations=classpath*:mapper/**/*.xml

# 实体类扫描路径

mybatis-plus.type-aliases-package=com.example.entity

# MyBatis Plus 日志配置

mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

```

4、编写实体类:创建对应数据库表的实体类,可以使用注解 `@TableName` 指定数据库表名,`@TableField` 指定数据库字段名。

```java

@Data

@TableName("user")

public class User {

@TableId(type = IdType.AUTO)

private Long id;

private String name;

private Integer age;

private String email;

}

```

5、编写 Mapper 接口:创建对应实体类的 Mapper 接口,通过继承 `BaseMapper` 接口,即可获得常用的数据库操作方法。

```java

public interface UserMapper extends BaseMapper {

}

```

6、使用:在需要使用数据库操作的地方注入对应的 Mapper 接口,即可使用 MyBatis Plus 提供的数据库操作方法。

```java

@Service

public class UserServiceImpl implements UserService {

@Autowired

private UserMapper userMapper;

@Override

public User getUserById(Long userId) {

return userMapper.selectById(userId);

}

@Override

public List getUserList() {

return userMapper.selectList(null);

}

@Override

public int addUser(User user) {

return userMapper.insert(user);

}

@Override

public int updateUser(User user) {

return userMapper.updateById(user);

}

@Override

public int deleteUser(Long userId) {

return userMapper.deleteById(userId);

}

}

```

以上就是使用 MyBatis Plus 连接数据库的基本步骤,通过配置数据源和 MyBatis Plus 的相关配置项,然后使用对应的 Mapper 接口即可实现数据库的操作。

0
看了该问题的人还看了