2015-06-04 38 views
2

我使用spring數據jpa和hibernate從數據庫表中檢索實體。其中一個實體字段是位於文件系統上的映像的路徑。是否有可能將圖像作爲字節數組加載到實體中?例如將圖像加載到實體bean中的字節數組中

@Entity 
@Table(name="Users") 
public class User 
{ 
    @Id 
    @GeneratedValue 
    int id; 
    String name; 
    String pictureName; 

    @Transient 
    byte[] image; 

    // other properties 
    public void setPictureName(String pictureName) 
    { 
     String path="D:\\images\\"; 
     File f = new File(path + pictureName); 
     this.image = new byte[(int)f.length()]; 

     FileUtility.toByteArray(f,this.image); //custom class 

     this.picture = picture; 
    } 
//other stuff 
} 

我試圖用JPA,但字節數組圖像字段總是作爲空,而其他一切都很好。

回答

1

是的,這是可能的,但你必須映射任何具有圖片名稱的列,以便Hibernate可以填充它。

因此,如果你有一個名爲「picture_name」欄,然後你的實體應該有:

@Column(name="picture_name") 
private String pictureName; 

然後,當Hibernate加載實體,它會調用setPictureName方法和運行代碼加載的文件到字節數組中。

+0

謝謝鄧肯。它像一個魅力。 – Ashken