简体   繁体   中英

JPA - Persisting entities without relations

This is a very basic question, but I fail to find the correct part of the documentation to solve it. I am writing a simple POC to learn Spring/JPA, in order to rewrite an application. One of my POJO looks like this:

@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;
...

How do I specify how to persist the path attribute ? If it was a string, it would be obvious, but at the moment, I get an exception. I understand why, but not sure how to go around it.

org.hibernate.MappingException: Could not determine type for: java.nio.file.Path, at table: image, for columns: [org.hibernate.mapping.Column(path)]

The small test I wrote to do the persistance is as follow (adapted from the springboot quick start example)

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));

And the repository is as follow:

import org.springframework.data.repository.CrudRepository;

public interface EntityImageRepository extends CrudRepository<EntityImage, Long> {

}

Use a custom converter for this with the javax.persistence.Convert -Annotation.

Your Converter could look like this:

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 */;
     }
}

And the field in your POJO like that:

@Column(name = "path")
@javax.persistence.Convert(converter = PathConverter.class)
private Path path;

With this setup, everytime you perstist your POJO the converter gets called to get the string from path and vice versa when loading from the database string gets converted to path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM