Search code examples
javaspringhibernatehibernate-mapping

How to solve Hibernate mapping exception for Set<Path> in java?


I want to save directories to the DB for my file path tree, but I got this error when initializing 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 is my filePathTree:

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

Solution

  • I created a converter class. After that I modified my fields. Hibernate create a table that will save paths like a string.

    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;