0

To store images I'm using Spring Content JPA strategy. My test profile has HSQLDB in-memory implementation. Is there a more convenient way to populate DB with images? For now, I have a solution to create a folder with images and then upload them manually on startup. As I understand, to get rid of the image folder I can upload them to SQLite and then fetch data from it, but maybe there is a better way?

CarrentalApplication

@SpringBootApplication
@EnableJpaRepositories
@EnableJpaStores
public class CarrentalApplication {
    private static final String IMAGE_FOLDER = "classpath:static/img/test-cars/";
    private final Map<Integer, String> cars = new HashMap<>() {{
        put(100010, "merc_benz");
        put(100011, "volvo_s60");
        put(100012, "suz_swift");
        put(100013, "volks16v");
        put(100014, "ford150");
        put(100015, "lambo610");
        put(100016, "bmvx5");
        put(100017, "audis6");
    }};

    public static void main(String[] args) {
        SpringApplication.run(CarrentalApplication.class, args);
    }

    @Bean
    public CommandLineRunner uploadImages(CarService carService, CarRepository carRepository,
                                          CarImageStore imageStore) {
        return (args) -> cars.forEach((carId, name) -> {
            try {
                Car car = carService.get(carId);
                File file = ResourceUtils.getFile(IMAGE_FOLDER + name + ".jpg");
                FileInputStream input = new FileInputStream(file);
                imageStore.setContent(car, input);
                carRepository.save(car);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}

CarImageStore

@StoreRestResource(path = "data")
@Repository
public interface CarImageStore extends ContentStore<Car, String> {
}

Car content fields:

@ContentId
private String contentId;

@ContentLength
private Long contentLength = 0L;

@MimeType
private String mimeType = "text/plain";
leonaugust
  • 186
  • 1
  • 4
  • 15

1 Answers1

1

Another way to do this is move the images onto the classpath; i.e. into /src/test/resources (assuming maven) and load them from there with:

imageStore.setContent(car, this.getClass().getResourceAsStream("/" + name + ".jpg"));

Paul Warren
  • 2,411
  • 1
  • 15
  • 22