Spring Data provides a store-independent way to populate repositories. It is similar to populating DataSource via SQL scripts in Spring JDBC module, but instead of using SQL scripts it supports XML and JSON (Jackson) formats. In following example we will see how to populate JPA entities via JSON data.
Example
Entities
@Entity
public class Employee {
private @Id
@GeneratedValue
Long id;
private String name;
private String dept;
.............
}
JSON Data
src/main/resources/employee-data.json[
{
"_class": "com.logicbig.example.Employee",
"name" : "Lara",
"dept" : "IT"
},
{
"_class": "com.logicbig.example.Employee",
"name" : "Wayne",
"dept" : "Admin"
},
{
"_class": "com.logicbig.example.Employee",
"name" : "Mira",
"dept" : "Sales"
}
]
JavaConfig
@EnableJpaRepositories
@ComponentScan
@Configuration
public class AppConfig {
@Bean
public Jackson2RepositoryPopulatorFactoryBean repositoryPopulator() {
Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean();
factory.setResources(new Resource[] { new ClassPathResource("employee-data.json")});
return factory;
}
@Bean
EntityManagerFactory entityManagerFactory() {
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("example-unit");
return emf;
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
}
Repository
public interface EmployeeRepository extends CrudRepository<Employee, Long> {
}
Example Client
@Component
public class ExampleClient {
@Autowired
private EmployeeRepository repo;
public void run() {
System.out.println(" -- finding all employees --");
Iterable<Employee> all = repo.findAll();
all.forEach(System.out::println);
}
}
Main class
public class ExampleMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
ExampleClient exampleClient = context.getBean(ExampleClient.class);
exampleClient.run();
EntityManagerFactory emf = context.getBean(EntityManagerFactory.class);
emf.close();
}
} -- finding all employees -- Employee{id=1, name='Lara', dept='IT'} Employee{id=2, name='Wayne', dept='Admin'} Employee{id=3, name='Mira', dept='Sales'}
Example ProjectDependencies and Technologies Used: - spring-data-jpa 2.0.8.RELEASE: Spring Data module for JPA repositories.
Uses org.springframework:spring-context version 5.0.7.RELEASE - hibernate-core 5.3.1.Final: Hibernate's core ORM functionality.
Implements javax.persistence:javax.persistence-api version 2.2 - h2 1.4.197: H2 Database Engine.
- jackson-databind 2.9.6: General data-binding functionality for Jackson: works on core streaming API.
- JDK 1.8
- Maven 3.5.4
|