轉載自:www.javaman.cn
在 Spring Boot 項目中使用 MyBatis-Plus 處理 longblob
字段時,我們可以按照以下步驟進行操作。假設 longblob
存儲的是字符串數據。以下是完整的示例代碼:
- 添加依賴:在你的項目的
pom.xml
文件中添加 MyBatis-Plus 的依賴:
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>最新版本號</version>
</dependency>
- 創建 MyLongBlobTypeHandler 類:創建一個自定義的類型處理器
MyLongBlobTypeHandler
來處理longblob
字段的數據。這個處理器會將longblob
轉換為字符串。
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;@Component
public class MyLongBlobTypeHandler extends BaseTypeHandler<String> {@Overridepublic void setNonNullParameter(PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType) throws SQLException {preparedStatement.setBytes(i, s.getBytes(StandardCharsets.UTF_8));}@Overridepublic String getNullableResult(ResultSet resultSet, String s) throws SQLException {byte[] bytes = resultSet.getBytes(s);return new String(bytes, StandardCharsets.UTF_8);}@Overridepublic String getNullableResult(ResultSet resultSet, int i) throws SQLException {byte[] bytes = resultSet.getBytes(i);return new String(bytes, StandardCharsets.UTF_8);}@Overridepublic String getNullableResult(CallableStatement callableStatement, int i) throws SQLException {byte[] bytes = callableStatement.getBytes(i);return new String(bytes, StandardCharsets.UTF_8);}
}
? 2.定義實體類:創建一個實體類,用于映射數據庫表。在實體類中,使用 @TableField
注解來指定數據庫字段和類型處理器。例如下面文章的content內容字段就是longblob字段,通過@TableField
注解指定類型處理
@Data
@TableName("blog_article")
public class Article extends BaseEntity {private String name;private String url;private String tag;private Long channelId;private String channelName;@TableField(value = "content", typeHandler = MyLongBlobTypeHandler.class)private String content;private Integer orderNum;//是否啟用,Y啟用,N禁用private String enabled;//瀏覽數private Integer views;//descriptionprivate String description;//keywordsprivate String keywords;
}
? 3.使用 MyBatis-Plus 正常插入即可:sevice層中正常使用,處理器會默認轉成longblob插入數據庫
@Service
public class ArticleService extends ServiceImpl<ArticleMapper, Article> {/*** 添加文章* @param article*/public void add(@NotNull Article article){this.save(article);}
}