Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

hibernate

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)
like image 983
valik Avatar asked Mar 05 '23 02:03

valik


1 Answers

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:

  • AttributeConverter
  • Converter
  • Convert
like image 79
Slaw Avatar answered May 10 '23 19:05

Slaw