【问题标题】:Flyway Java Migrations: insert BLOB into PostgresqlFlyway Java 迁移:将 BLOB 插入 Postgresql
【发布时间】:2022-01-20 00:21:55
【问题描述】:

我正在使用 Flyway 进行所有数据库迁移。是时候在迁移时处理二进制数据(图像)了。我正在使用 Postgresql 和 Spring Data JPA。

首先我有这个字段导致使用 Postgresql 的 db 列 photo oid

@Entity
public class Person {
  // omitted 

  @Lob
  private byte[] photo;
}

我的迁移脚本看起来像这样

V1__CREATE_DB.sql
V2__INSERT_PERSON.sql
V3__INSERT_PHOTO.java

起初我没有成功地使用JdbcTemplate 迁移(更新)一个有照片的人。后来发现这样可以把oid的类型改成bytea

@Lob
@Type(type = "org.hibernate.type.BinaryType")
private byte[] photo;

然后我使迁移代码看起来像这样

public void migrate(Context context) throws IOException {
  JdbcTemplate template = ...
  List<String> locations = ... // photo physical locations/paths

  for(String location: locations) {
    InputStream image = ... // from location
    Long id = ... // get id from image name

    template.update("UPDATE person SET photo = ? where id = " + id,
      new Object[] { new SqlLobValue(image.readAllBytes(), new DefaultLobHandler()) },
      new int[] { Types.BLOB }
    );
  }
}

此 V3__ 迁移按预期工作

  • 是否有更好的方法来实现此迁移,我是否也可以为 oid 执行此操作,在这种情况下如何操作?

  • 除了明显的存储容量差异之外,是否有理由不选择bytea 而不是oid

【问题讨论】:

    标签: java postgresql migration blob flyway


    【解决方案1】:

    在几乎破坏了 Google 之后,我终于找到了一个解决方案,如何使用 JdbcTemplate 更新列 photo oid

    DefaultLobHandler lobHandler = new DefaultLobHandler();
    lobHandler.setWrapAsLob(true);
    
    jdbcTemplate.execute("UPDATE person SET photo = ? where id = ?", new AbstractLobCreatingPreparedStatementCallback(lobHandler) {                                                       
      protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException {     
        lobCreator.setBlobAsBinaryStream(ps, 1, image, image.available());                                        
        ps.setLong(2, id);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-10
      • 2016-12-12
      • 2017-12-23
      • 2016-09-24
      • 2021-08-29
      • 2012-07-16
      • 1970-01-01
      • 2023-03-13
      • 2015-01-02
      相关资源
      最近更新 更多