【问题标题】:JPA - Persisting entities without relations [duplicate]JPA - 没有关系的持久实体[重复]
【发布时间】:2018-04-09 02:29:43
【问题描述】:

这是一个非常基本的问题,但我找不到文档的正确部分来解决它。我正在编写一个简单的 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> {

}

【问题讨论】:

  • 这取决于你的 Path 类是什么。可以展示一下吗?
  • @Lu55 你链接的那个问题比这个更年轻,但我还是把它作为一个副本关闭了,因为链接的那个实际上提到了错误,这可能对未来的读者更有帮助跨度>

标签: java hibernate jpa spring-data-jpa persistence


【解决方案1】:

使用带有javax.persistence.Convert-Annotation 的自定义转换器。

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

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 时,都会调用转换器以从路径获取字符串,反之亦然,当从数据库加载时,字符串会转换为路径

【讨论】:

  • 效果很好。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-10
  • 2012-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-25
相关资源
最近更新 更多