简体   繁体   中英

JPA to not persist to database but filesystem

I am trying to save a byte[] field to local filesystem instead of the database.

I have tried the JPA annotation @Transient

@Entity
@Table(name = "screenshot")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Screenshot implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

    @Lob
    @Transient
    @Column(name = "image", nullable = false)
    private byte[] image;

    @Column(name = "otherField", nullable = false)
    private String otherField;

    @Column(name = "otherField2", nullable = false)
    private String otherField2;
}

But after I persist the entity, for eg The returnedEntity image property will not be returned due to @Transient annotation.

Screenshot returnedEntity = screenshotRepository.save(entity);

But I need to persist it in the database first in-order to get an unique ID and use this ID as part of the file path to persist only the image(binary) field in my local filesystem.

I run into a situation that before I save the entity into the database, I do not have an unique ID. But after I save the entity, I lost the binary byte[] data to save the file in the local filesystem.

Can't seems to figure a good way to link the saved ID to the binary byte[].

Your problem is that you want the field to be Transiented and Included (serialized) at the sametime. Some people suggest to use @JsonInclude annotation, like what is mentioned here .

However, from my point of view, the idea is in the logic of your app and its not related to JPA . So, I would copy the object before presisting it, or at least copy the image field alone. After presistance, assigning the ID of the presisted object to the ID of the copied object.

Or, another solution, you can add a string field to your database that will hold a path to your image; You start by writing the image to the 'heart content' or wherever, and then assign the path of the image to the entity and persist that path in the database.

Or, another solution, you can add another data model layer to your system above the entity layer, which contains the JSON classes, so you dont need to have a transient fields in your entity nor JSON annotations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM