我有一个实体照片如下
@Entity
class Photo {
Path imagePath;
public Path getImagePath(){
return imagePath;
// setter
}
Run Code Online (Sandbox Code Playgroud)
在这个实体中,我必须使用 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)
Run Code Online (Sandbox Code Playgroud)
你可以使用一个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);
}
}
Run Code Online (Sandbox Code Playgroud)
此转换器示例将仅存储Path. 它不会维护任何其他信息,例如FileSystem它属于什么(并且FileSystem在从Stringto转换时将采用默认值Path)。
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;
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅以下文档: