Hibernate Mapping Exception Could not determine type for: java.nio.file.Path

I have an entity Photo as below

@Entity
class Photo {

Path imagePath;

public Path getImagePath(){
return imagePath;
// setter
}

In this entity i have to nio.Path how can i solve thiss problem or make the table in db to accept strings as path the error stack is below

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)

2 answers

  • answered 2018-11-08 00:53 Taf

    Path is not an Entity, so if you want the db to store it as String, you will have to change the type to String and use the following Paths.get(String path) to return the Path

    @Entity
    class Photo {
    
         String imagePathStr;
    
    public String getImagePathStr(){
         return imagePath;
    // setter
    }
    
    @Transient
    public Path getImagePath(){
         return Paths.get(imagePathStr);
    }
    

  • answered 2018-11-08 03:02 Slaw

    You could use an 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);
        }
    
    }
    

    This converter example will only store the path part of the Path. It won't maintain any other information such as what FileSystem it belongs to (and will assume the default FileSystem when converting from String to 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;
    
    }
    

    See the documentation of the following for more information: