gpt4 book ai didi

java - MyBatis - 如何在保存到数据库表之前转换数据

转载 作者:行者123 更新时间:2023-12-02 02:31:46 27 4
gpt4 key购买 nike

我正在使用 MyBatis 在简单的 Java 应用程序中将数据保存到 SQLite 数据库。是否可以配置MyBatis在Java类和DB表之间的通信中进行数据转换?

例如,我的 Java 类中有 java.util.Date 对象,我想将其保存为数字(Unix 时间)。另一个例子:在 Java 类中,我有一个 BigDecimal 数字,我想将其存储为文本(我不想丢失任何精度)。

在 Java 对象中,我使用适当的 getter 和 setter 来转换此类数据,但我看不到在 MyBatis .xml 文件中指定它们的任何可能性。

总而言之,我的问题:
1. 我可以在MyBatis结果映射中使用Java getter和setter吗?如果是,那么如何?
2. 如何通过MyBatis在DB中正确存储复杂数据(例如Dates和BigDecimals)?

最佳答案

我已经成功使用 TypeHandler 开始工作类(class)。以下是将 BigDecimal 映射到 TEXT 数据库列的示例代码:

public class BigDecimalTypeHandler implements TypeHandler<BigDecimal> {
public BigDecimal getResult(ResultSet rs, int columnIndex) throws SQLException{
String str_val = rs.getString(columnIndex);
BigDecimal res;

if( str_val == null || str_val.equals("") )
res = new BigDecimal(0);
else
res = new BigDecimal(str_val);

return res;
}
public BigDecimal getResult(ResultSet rs, String columnName) throws SQLException{
String str_val = rs.getString(columnName);
BigDecimal res;

if( str_val == null || str_val.equals("") )
res = new BigDecimal(0);
else
res = new BigDecimal(str_val);

return res;
}
public BigDecimal getResult(CallableStatement cs, int columnIndex) throws SQLException{
String str_val = cs.getString(columnIndex);
BigDecimal res;

if( str_val == null || str_val.equals("") )
res = new BigDecimal(0);
else
res = new BigDecimal(str_val);

return res;
}
public void setParameter(PreparedStatement ps, int i, BigDecimal parameter, JdbcType jdbcType) throws SQLException{
if( parameter != null )
ps.setString(i, parameter.toString());
else
ps.setString(i, "0");
}
}

在 MyBatis 配置文件中:

<configuration>
(...)
<typeHandlers>
<typeHandler javaType="BigDecimal" jdbcType="VARCHAR" handler="example.com.BigDecimalTypeHandler"/>
</typeHandlers>
(...)
</configuration>

关于java - MyBatis - 如何在保存到数据库表之前转换数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46984076/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com