Hibernate映射异常无法确定的类型:java.nio.file.Path
我有一张实体照片如下Hibernate映射异常无法确定的类型:java.nio.file.Path,java,hibernate,Java,Hibernate,我有一张实体照片如下 @Entity class Photo { Path imagePath; public Path getImagePath(){ return imagePath; // setter } 在这个实体中,我必须使用nio.Path。我如何解决这个问题,或者使db中的表接受字符串作为路径 错误堆栈在下面 Caused by: org.hibernate.MappingException: Could not determine type for: java.nio.f
@Entity
class Photo {
Path imagePath;
public Path getImagePath(){
return imagePath;
// setter
}
在这个实体中,我必须使用nio.Path。我如何解决这个问题,或者使db中的表接受字符串作为路径
错误堆栈在下面
Caused by: org.hibernate.MappingException: Could not determine type for: java.nio.file.Path, at table: photo, for columns: [org.hibernate.mapping.Column(image_path)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:431)
Path不是实体,因此如果希望db将其存储为字符串,则必须将类型更改为字符串,并使用以下路径。get(String Path)返回路径
@Entity
class Photo {
String imagePathStr;
public String getImagePathStr(){
return imagePath;
// setter
}
@Transient
public Path getImagePath(){
return Paths.get(imagePathStr);
}
您可以使用
AttributeConverter
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter // may want to set autoApply to true
public class PathConverter implements AttributeConverter<Path, String> {
@Override
public String convertToDatabaseColumn(Path attribute) {
return attribute == null ? null : attribute.toString();
}
@Override
public Path convertToEntityAttribute(String dbData) {
return dbData == null ? null : Paths.get(dbData);
}
}
有关更多信息,请参阅以下文档:
import java.nio.file.Path;
import javax.persistence.Convert;
import javax.persistence.Entity;
@Entity
public class Photo {
@Convert(converter = PathConverter.class) // needed if autoApply isn't true
private Path imagePath;
}