Spring-data-jpa storing blob

后端 未结 6 911
梦如初夏
梦如初夏 2021-02-04 14:17

What is \"best\" or canonical way to store entity with blob using spring-data-jpa?

@Entity
public class Entity {
  @Id
  private Long id;
  @Lob()
  private Blob         


        
6条回答
  •  粉色の甜心
    2021-02-04 15:06

    You can also create Blob right from DataSource:

    @Component
    public class LobHelper {
    
        private final DataSource ds;
    
        public LobHelper(@Autowired DataSource ds){
             this.ds = ds;
        }
    
        public Blob createBlob(byte[] content) {
            try (Connection conn = ds.getConnection()) {
                Blob b = conn.createBlob();
                try (OutputStream os = b.setBinaryStream(1);
                     InputStream is = new ByteArrayInputStream(content)) {
                    byte[] buffer = new byte[500000];
                    int len;
                    while ((len = is.read(buffer)) > 0) {
                        os.write(buffer, 0, len);
                    }
                    return b;
                }
            } catch (Exception e) {
                log.error("Error while creating blob.", e);
            }
            return null;
        }
    
    }
    

提交回复
热议问题