请教各位大佬 ,在使用mybatis-plus查询pg数据库的时候,遇到两个问题
1、localDatetime 无法转换pg数据的日期类型
Cannot convert the column of type TIMESTAMPTZ to requested type timestamp.
手写语句类型转换可以解决
比如created_time::timestamp
但是写的语句太多了每个表都需要这样太麻烦了 有没有统一拦截处理的方法
2、在使用mybatis-plus自带的api insert语句查询时 因为我的表名首字母大写 pg查询时会自动转成小写的 导致报错表名不存在 但是在执行时表名加上“”是可以的
select * from "xxx"
mybtais-plus怎么在执行语句前自动给表名加上双引号呢
承BaseTypeHandler 自定义一个 localDatetime 对象转为pgsql中日期类型
下面这个是用GPT生成的一个demo
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.postgresql.jdbc.TimestampUtils;
import java.sql.*;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final ZoneId zoneId = ZoneId.systemDefault();
@Override
public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
Timestamp timestamp = Timestamp.valueOf(parameter);
ps.setTimestamp(i, timestamp);
}
@Override
public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
Timestamp timestamp = rs.getTimestamp(columnName);
return timestamp != null ? timestamp.toLocalDateTime() : null;
}
@Override
public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
Timestamp timestamp = rs.getTimestamp(columnIndex);
return timestamp != null ? timestamp.toLocalDateTime() : null;
}
@Override
public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
Timestamp timestamp = cs.getTimestamp(columnIndex);
return timestamp != null ? timestamp.toLocalDateTime() : null;
}
}
使用时,
@Data
@TableName(value = "table" ,autoResultMap = true)
public class Table {
@TableField(value = "create_time", typeHandler = LocalDateTimeTypeHandler.class)
private LocalDateTime createTime;
}
可以看下能否解决你第一个问题
第二个问题,你可以试一下 @Select注解 ,看下是否能更方便的解决你的问题
public interface InsertTable {
//sql内容就是insert 语句
@Select(${sql})
int insertSql(Param("sql")String sql);
}
@此木|西贝: 动态表名处理了
这个可以解决 但是我已经处理了 方法也是差不多的 不过还是谢谢你
第二个问题解决了 使用动态表名处理