Search code examples
javajpaeclipselink

Map static field from different table in JPA


Our application is using a table to store application wide settings in a property table like this (using JPA):

public class Property {
    String key; // primary key
    String value;
}

One of our entities needs to have one of those properties, a base directory for file storage, (same one for ALL entities of this type) in a static field (it doesn't need to be static, but it would make sense).

public class FileEntity {
     public static String BASE_DIR;
     ...
}

There is no mapped relationship between those to entites yet and there is nothign to be used as a foreign key from any side. Is it possible anyway, to define a mapping which inserts the value of the Property with key="basedir" into the BASE_DIR attribute of the FileEntity?

BASE_DIR not being static would be kind of ok, but the content would still be the same for all instances of FileEntity.


Solution

  • Possibly not as elegant as you would have wished:

    @Entity
    public class FileEntity {
    
        private static String BASE_DIR;
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private long id;
    

    Have a property service with a @PostConstruct to initialise all your entities

    @PostConstruct
    public void init() {
        FileEntity.setBaseDir(propertyRepository.findByKey("key1").getValue());
    }
    

    After all the beans have been loaded the static fields on your entities will be set and belong to the class.