【问题标题】:How to solve Hibernate mapping exception for Set<Path> in java?如何解决 java 中 Set<Path> 的 Hibernate 映射异常?
【发布时间】:2018-03-11 13:53:45
【问题描述】:

我想为我的文件路径树将目录保存到数据库中,但在初始化 Hibernate 时出现此错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [hibernate-config.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: Could not determine type for: java.nio.file.Path, at table: BasePlan_selectedPaths, for columns: [org.hibernate.mapping.Column(selected_paths)]

Here 是我的文件路径树:

@Column(name = "selected_paths")
@ElementCollection(targetClass = Path.class)
private Set<Path> selectedPaths;

【问题讨论】:

    标签: java spring hibernate hibernate-mapping


    【解决方案1】:

    我创建了一个转换器类。之后我修改了我的字段。 Hibernate 创建一个将像字符串一样保存路径的表。

    public class PathConverter implements AttributeConverter<Path, String> {
    
        @Override
        public String convertToDatabaseColumn(Path path) {
            return path.toString();
        }
    
        @Override
        public Path convertToEntityAttribute(String path) {
            return Paths.get(path);
        }
    }
    
    @Column(name = "selected_paths")
    @ElementCollection(targetClass = Path.class)
    @Convert(converter = PathConverter.class)
    private Set<Path> selectedPaths;
    
    @Column(name = "unselected_paths")
    @ElementCollection(targetClass = Path.class)
    @Convert(converter = PathConverter.class)
    private Set<Path> unSelectedPaths;
    

    【讨论】:

      【解决方案2】:

      您可以将该字段声明为 String 并在 getter 中使用 Path

      @Column(name = "selected_paths")
      @ElementCollection(targetClass = Path.class)
      private Set<String> selectedPaths;
      
      public Set<Path> getSelectedPaths() {
          return selectedPaths.stream().map(Paths::get).collect(Collectors.toSet());
      }
      

      【讨论】:

        【解决方案3】:

        您是否要保存目录和子目录的路径? 列的数据类型是什么:selected_pa​​ths。我的猜测是 varchar

        在这种情况下,您可以将路径映射为 Java 中的 String 类型。

        我认为(如果我错了,请纠正我),Java 无法确定 nio 路径与 DB 中相应数据类型之间的映射。

        在从数据库中取回数据时,您可以将其作为 String 并轻松将其用作 Path

        【讨论】:

        • 还没有任何数据库。
        • 好吧,如果您没有配置任何数据库并且没有表,它无法将字段映射到列。 @Column 注解放在一个@Entity 类中,代表DB 的表。
        猜你喜欢
        • 2017-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-11
        • 2018-02-24
        • 2020-04-01
        相关资源
        最近更新 更多