mybatisPlus中postgreSql数组字段类型处理
在MyBatis Plus中处理PostgreSQL数组字段类型,可以通过自定义TypeHandler来实现。以下是一个简单的例子,展示了如何处理字符串数组类型(text[]
)。
首先,创建一个自定义TypeHandler:
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.postgresql.util.PGobject;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
public class StringArrayTypeHandler extends BaseTypeHandler<List<String>> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
PGobject pgObject = new PGobject();
pgObject.setType("text[]");
pgObject.setValue(arrayToString(parameter));
ps.setObject(i, pgObject);
}
@Override
public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
return stringToArray(rs.getString(columnName));
}
@Override
public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return stringToArray(rs.getString(columnIndex));
}
@Override
public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return stringToArray(cs.getString(columnIndex));
}
private String arrayToString(List<String> list) {
return "{" + String.join(",", list) + "}";
}
private List<String> stringToArray(String str) {
if (str == null) {
return null;
}
return Arrays.asList(str.substring(1, str.length() - 1).split(","));
}
}
然后,在MyBatis Plus的配置中注册这个TypeHandler:
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
@Configuration
public class MyBatisPlusConfig {
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
MybatisSqlS
评论已关闭