mybatis-plus orm框架使用
时间: 2023-11-28 22:43:33 浏览: 89
Mybatis-Plus是Mybatis的增强工具,在Mybatis的基础上只做增强不做改变,简化了CRUD操作,提供了代码生成器等功能,使得开发更加高效。下面是使用Mybatis-Plus的步骤:
1.添加依赖
在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
```
2.配置文件
在application.yml文件中添加以下配置:
```yaml
mybatis-plus:
mapper-locations: classpath*:mapper/*.xml # mapper文件的位置
type-aliases-package: com.example.demo.entity # 实体类的位置
```
3.编写实体类
```java
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
```
4.编写Mapper接口
```java
public interface UserMapper extends BaseMapper<User> {
}
```
5.编写Mapper XML文件
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.demo.entity.User">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
<result column="email" property="email"/>
</resultMap>
</mapper>
```
6.使用Mybatis-Plus进行CRUD操作
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(Long id) {
return userMapper.selectById(id);
}
@Override
public List<User> 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 deleteUserById(Long id) {
return userMapper.deleteById(id);
}
}
```
阅读全文