mybatis-plus如何实现
时间: 2024-05-28 16:05:02 浏览: 75
根据提供的引用内容,MyBatis-Plus的实现流程如下:
1. 引入MyBatis-Plus依赖,可以通过Maven方式引入,例如:
```xml
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
```
2. 配置MyBatis-Plus,可以在application.yml或application.properties文件中添加如下配置:
```yaml
mybatis-plus:
# mapper文件位置
mapper-locations: classpath:/mapper/*.xml
# 实体类包名
typeAliasesPackage: com.example.entity
```
3. 创建实体类,可以使用Lombok注解简化代码,例如:
```java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
```
4. 创建Mapper接口,可以继承MyBatis-Plus提供的BaseMapper接口,例如:
```java
public interface UserMapper extends BaseMapper<User> {
}
```
5. 创建Mapper.xml文件,可以使用MyBatis-Plus提供的自动填充功能,例如:
```xml
<mapper namespace="com.example.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.entity.User">
<id column="id" property="id" />
<result column="name" property="name" />
<result column="age" property="age" />
<result column="email" property="email" />
</resultMap>
<sql id="Base_Column_List">
id, name, age, email
</sql>
<insert id="insert" parameterType="com.example.entity.User">
<selectKey keyProperty="id" resultType="java.lang.Long" order="BEFORE">
SELECT IFNULL(MAX(id), 0) + 1 FROM user
</selectKey>
INSERT INTO user (id, name, age, email)
VALUES (#{id}, #{name}, #{age}, #{email})
</insert>
<update id="updateById" parameterType="com.example.entity.User">
UPDATE user
SET name = #{name}, age = #{age}, email = #{email}
WHERE id = #{id}
</update>
<select id="selectById" resultMap="BaseResultMap" parameterType="java.lang.Long">
SELECT <include refid="Base_Column_List" />
FROM user
WHERE id = #{id}
</select>
<delete id="deleteById" parameterType="java.lang.Long">
DELETE FROM user
WHERE id = #{id}
</delete>
<select id="selectList" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List" />
FROM user
</select>
</mapper>
```
6. 在Service中调用Mapper接口,例如:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getById(Long id) {
return userMapper.selectById(id);
}
@Override
public List<User> list() {
return userMapper.selectList(null);
}
@Override
public boolean save(User user) {
return userMapper.insert(user) > 0;
}
@Override
public boolean updateById(User user) {
return userMapper.updateById(user) > 0;
}
@Override
public boolean removeById(Long id) {
return userMapper.deleteById(id) > 0;
}
}
```
阅读全文