JPA - 没有关系的持久化实体

JPA - Persisting entities without relations

这是一个非常基本的问题,但我没有找到文档中正确的部分来解决它。我正在编写一个简单的 POC 来学习 Spring/JPA,以便重写一个应用程序。我的一个 POJO 看起来像这样:

@Entity
@Table(name = "Image")
public class EntityImage {

/**
 * The id of the image.
 */
@Id
@NotNull
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;

/**
 * Path to the image.
 */
@Column(name = "path")
private Path path;

/**
 * Type of the image.
 */
private ImageType type;
...

如何指定如何保​​留路径属性?如果它是一个字符串,那将是显而易见的,但此刻,我得到一个例外。我明白为什么,但不确定如何解决它。

org.hibernate.MappingException: Could not determine type for: java.nio.file.Path, at table: image, for columns: [org.hibernate.mapping.Column(path)]

我写的持久化小测试如下(改编自springboot快速入门示例)

public static void main(final String[] args) {
    SpringApplication.run(EntityImagePersister.class);
}

@Bean
public CommandLineRunner demo(final EntityImageRepository repository) {
    return (args) -> {
        // save a couple of customers
        final File file = new File("H:\ZModel.png");
        final Path p = file.toPath();

        repository.save(new EntityImage(1L, p, ImageType.AVATAR));

存储库如下:

import org.springframework.data.repository.CrudRepository;

public interface EntityImageRepository extends CrudRepository<EntityImage, Long> {

}

为此使用带有 javax.persistence.Convert-注释的自定义转换器。

您的转换器可能如下所示:

class PathConverter extends javax.persistence.AttributeConverter<Path, String>{

     @Override 
     public String convertToDatabaseColumn(Path path){
         return /* your convert operation from path to string */;
     }

     @Override 
     public Path convertToEntityAttribute(String string){
         return /* your convert operation from string to path */;
     }
}

你的 POJO 中的字段是这样的:

@Column(name = "path")
@javax.persistence.Convert(converter = PathConverter.class)
private Path path;

使用此设置,每次您坚持使用 POJO 时,都会调用转换器以从路径获取字符串,反之亦然,当从数据库加载时,字符串会转换为路径