Spring Data Jpa Repository Populators

Spring provides us multiple ways to populate Underlying Database for example Spring JDBC module support SQL scripts to populate a DataSource. Spring Data Jpa provides same functionality. Spring Data Jpa Supports both SQL and NoSQL, so SQL scripts cannot be used, hence either XML (through Spring’s OXM abstraction) or JSON (through Jackson) is used to populate the repositories.

Repository Populators using JSON

drop database if exists AppleDb;
create database AppleDb;
use AppleDb;
create table apple ( apple_id bigint not null, apple_name varchar(255) default null, taste varchar(255) default null, primary key (apple_id)) engine=innodb;
create table hibernate_sequence (next_val bigint) engine=innodb;

data.json

[
  {
    "_class": "com.sujan.example.jpa.entity.Apple",
    "appleId": 1,
    "appleName": "Macintosh",
    "taste": "tangy"
  },
  {
    "_class": "com.sujan.example.jpa.entity.Apple",
    "appleId": 2,
    "appleName": "Fuji",
    "taste": "sweet"
  },
  {
    "_class": "com.sujan.example.jpa.entity.Apple",
    "appleId": 3,
    "appleName": "Gala",
    "taste": "juicy"
  },
  {
    "_class": "com.sujan.example.jpa.entity.Apple",
    "appleId": 4,
    "appleName": "Jonagold",
    "taste": "firm sweet"
  },
  {
    "_class": "com.sujan.example.jpa.entity.Apple",
    "appleId": 5,
    "appleName": "GrannySmith",
    "taste": "sharp"
  }
]
package com.sujan.example.jpa.controller;

import com.sujan.example.jpa.entity.Apple;
import com.sujan.example.jpa.repository.AppleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class AppleController {
    @Autowired
    private AppleRepository appleRepository;

    @GetMapping
    List<Apple> findAll() {
        List<Apple> appleList = appleRepository.findAll();
        appleList.forEach(System.out::println);
        return appleList;
    }
}
package com.sujan.example.jpa.entity;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import javax.persistence.Entity;
import javax.persistence.Id;

@Data
@ToString
@Entity
@NoArgsConstructor
public class Apple {
    @Id
    private Long appleId;
    private String appleName;
    private String taste;
}
package com.sujan.example.jpa.repository;

import com.sujan.example.jpa.entity.Apple;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface AppleRepository extends JpaRepository<Apple, Long> {
}
package com.sujan.example.jpa;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.repository.init.Jackson2RepositoryPopulatorFactoryBean;

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

    @Bean
    public Jackson2RepositoryPopulatorFactoryBean getRespositoryPopulator() {
        Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean();
        factory.setResources(new Resource[]{new ClassPathResource("data.json")});
        return factory;
    }
}
spring.datasource.url=jdbc:mysql://localhost:3306/AppleDb
spring.datasource.username=root
spring.datasource.password=root
plugins {
    id 'org.springframework.boot' version '2.3.3.RELEASE'
    id 'io.spring.dependency-management' version '1.0.10.RELEASE'
    id 'java'
}
group = 'com.sujan'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}
repositories {
    mavenCentral()
}
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    annotationProcessor 'org.projectlombok:lombok'
    compileOnly 'org.projectlombok:lombok'
    compile 'com.fasterxml.jackson.core:jackson-databind'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    runtimeOnly 'mysql:mysql-connector-java'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}
test {
    useJUnitPlatform()
}
curl --location --request GET 'http://localhost:8080/'
select apple0_.apple_id as apple_id1_0_, apple0_.apple_name as apple_na2_0_, apple0_.taste as taste3_0_ from apple apple0_
Apple(appleId=1, appleName=Macintosh, taste=tangy)
Apple(appleId=2, appleName=Fuji, taste=sweet)
Apple(appleId=3, appleName=Gala, taste=juicy)
Apple(appleId=4, appleName=Jonagold, taste=firm sweet)
Apple(appleId=5, appleName=GrannySmith, taste=sharp)

Repository Populators using XML

drop database if exists AppleDb;
create database AppleDb;
use AppleDb;
create table apple ( apple_id bigint not null, apple_name varchar(255) default null, taste varchar(255) default null, primary key (apple_id)) engine=innodb;
create table hibernate_sequence (next_val bigint) engine=innodb;
data.xml
<apple>
    <appleId>1</appleId>
    <appleName>apple</appleName>
    <taste>red</taste>
</apple>
package com.sujan.example.jpa.controller;

import com.sujan.example.jpa.entity.Apple;
import com.sujan.example.jpa.repository.AppleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class AppleController {
    @Autowired
    private AppleRepository appleRepository;

    @GetMapping
    List<Apple> findAll() {
        List<Apple> appleList = appleRepository.findAll();
        appleList.forEach(System.out::println);
        return appleList;
    }
}
package com.sujan.example.jpa.entity;

import lombok.Data;
import lombok.ToString;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@Data
@ToString
@Entity
public class Apple {
    @Id
    private Long appleId;
    private String appleName;
    private String taste;
}
package com.sujan.example.jpa.repository;

import com.sujan.example.jpa.entity.Apple;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface AppleRepository extends JpaRepository<Apple, Long> {
}
package com.sujan.example.jpa;

import com.sujan.example.jpa.entity.Apple;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.repository.init.UnmarshallerRepositoryPopulatorFactoryBean;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;

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

    @Bean
    public UnmarshallerRepositoryPopulatorFactoryBean repositoryPopulator() {
        Jaxb2Marshaller unmarshaller = new Jaxb2Marshaller();
        unmarshaller.setClassesToBeBound(Apple.class);
        UnmarshallerRepositoryPopulatorFactoryBean factory = new UnmarshallerRepositoryPopulatorFactoryBean();
        factory.setUnmarshaller(unmarshaller);
        factory.setResources(new Resource[]{new ClassPathResource("data.xml")});
        return factory;
    }
}
spring.datasource.url=jdbc:mysql://localhost:3306/AppleDb
spring.datasource.username=root
spring.datasource.password=root
plugins {
    id 'org.springframework.boot' version '2.3.3.RELEASE'
    id 'io.spring.dependency-management' version '1.0.10.RELEASE'
    id 'java'
}
group = 'com.sujan'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}
repositories {
    mavenCentral()
}
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    annotationProcessor 'org.projectlombok:lombok'
    compileOnly 'org.projectlombok:lombok'
    compile 'org.springframework:spring-oxm'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    runtimeOnly 'mysql:mysql-connector-java'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}
test {
    useJUnitPlatform()
}
curl --location --request GET 'http://localhost:8080/'
select apple0_.apple_id as apple_id1_0_, apple0_.apple_name as apple_na2_0_, apple0_.taste as taste3_0_ from apple apple0_
Apple(appleId=1, appleName=Macintosh, taste=tangy)
Apple(appleId=2, appleName=Fuji, taste=sweet)
Apple(appleId=3, appleName=Gala, taste=juicy)
Apple(appleId=4, appleName=Jonagold, taste=firm sweet)
Apple(appleId=5, appleName=GrannySmith, taste=sharp)

follow us on