mysql 存储java对象,Mysql存储java对象

mysql  设置字段为 blob

保存对象,先将对象序列化为byte[]  使用 setObject(byte[] bytes)

ByteArrayOutputStream baos = new ByteArrayOutputStream();

ObjectOutputStream out = null;

try {

out = new ObjectOutputStream(baos);

out.writeObject(java实例对象);

} catch (IOException e) {

logger.error("msg2Bytes error!", e);

}finally{

try {

out.close();

} catch (IOException e) {

logger.error("msg2Bytes error!", e);

}

}

return baos.toByteArray();

获取对象 使用getBytes(),将获取的byte[]反序列化为java 对象

ByteArrayInputStream bais;

ObjectInputStream in = null;

try{

bais = new ByteArrayInputStream(bytes);

in = new ObjectInputStream(bais);

return (java类)in.readObject();

}finally{

if(in != null){

try {

in.close();

} catch (IOException e) {

logger.error("bytes2Msg error!", e);

}

}

}

网上的其他方式会有各类问题,请慎用。

包括:

1.设置url参数 autoDeserialize=true

2.setObject(java实例对象)        查询

ObjectInputStream oips = new ObjectInputStream(rs.getBinaryStream(1));

ArrayList obb = (java类)oips.readObject();//从流中读取对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将 Java 对象存储MySQL 的 JSON 字段中,你可以按照以下步骤进行操作: 1. 首先,确保你的 MySQL 数据库表中有一个 JSON 类型的字段,用于存储 JSON 数据。 2. 将 Java 对象转换为 JSON 字符串。你可以使用 JSON 解析库,如 Jackson、Gson 或 JSON.simple 来实现这一步骤。 - 如果你使用 Jackson 库,可以使用 `ObjectMapper` 对象Java 对象转换为 JSON 字符串。例如: ```java ObjectMapper objectMapper = new ObjectMapper(); String jsonString = objectMapper.writeValueAsString(yourObject); ``` 这里的 `yourObject` 是你想要存储为 JSON 的 Java 对象。 - 如果你使用 Gson 库,可以使用 `Gson` 对象Java 对象转换为 JSON 字符串。例如: ```java Gson gson = new Gson(); String jsonString = gson.toJson(yourObject); ``` 这里的 `yourObject` 是你想要存储为 JSON 的 Java 对象。 - 如果你使用 JSON.simple 库,可以使用 `JSONObject` 和 `JSONArray` 对象Java 对象转换为 JSON 字符串。例如: ```java JSONObject jsonObject = new JSONObject(); jsonObject.put("property", yourObject.getProperty()); // 设置其他属性... String jsonString = jsonObject.toJSONString(); ``` 3. 将生成的 JSON 字符串插入到 MySQL 数据库表的 JSON 字段中。你可以使用 INSERT 语句来实现这一步骤。 ```java String insertQuery = "INSERT INTO your_table (json_column) VALUES (?)"; PreparedStatement statement = connection.prepareStatement(insertQuery); statement.setString(1, jsonString); statement.executeUpdate(); ``` 这里的 `your_table` 是你要插入数据的表名,`json_column` 是 JSON 字段的列名,`connection` 是你的数据库连接对象。 请注意,这只是一种常见的方法,你可以根据自己的需求和使用的 JSON 解析库进行调整。确保将库添加到你的项目依赖中,并按照它们的文档进行配置和使用。同时,还要注意 JSON 字符串的长度限制,确保它不超过 MySQL 中 JSON 字段的最大长度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值