我使用spring数据jpa和hibernate从DB表中检索实体。其中一个实体字段是位于文件系统上的图像的路径。是否可以将图像作为字节数组加载到实体中? e.g
@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,但字节数组图像字段始终为空,而其他一切都很好。
答案 0 :(得分:1)
是的,这是可能的,但您必须映射具有图片名称的任何列,以便Hibernate可以填充它。
因此,如果您有一个名为“picture_name”的列,那么您的实体应该具有:
@Column(name="picture_name")
private String pictureName;
然后,当Hibernate加载实体时,它将调用setPictureName
方法并运行代码将文件加载到字节数组中。