Spring R2DBC Multi Datasource with Spring Boot - spring

I created a service that connects to two schemas (ex. fo_pgdb, if_pgdb) My issue is when the service queries the table in the if_pgdb schema it looks as though it is querying the table in the fo_pgdb schema. I have checked and hard coded the database URLs in both class attributes (shown in code examples below) look fine. What could be the issue?
example:
query on table in fo_pgdb schema is "select * from bid_lines where bidlinseqnumber in (123, 345) returns a result set. because ids 123 and 345 have records in the table.
query on table in if_pgdb schema is "select * from bid_lines where bidlinseqnumber in (567, 8910) returns empty result set. But ids 567 and 8910 those records with those ids are in the table.
test: when I use the ids 123 and 345 in the query on the table in the if_pgdb schema I get the same records that are in the table that are in the fo_pgdb table. That should not happen.
#Configuration
#EnableR2dbcRepositories(entityOperationsRef = "foEntityTemplate", basePackages = "com.r2dbc.poc.repository")
public class FODatabaseConfig {
//#Value("${spring.r2dbc.fo.connection.url}")
private String url = "r2dbc:postgresql://username:password#database-dev-fo-css-rr-db.corp.com:1200/fo_pgdb";
#Bean
#Qualifier("foConnectionFactory")
public ConnectionFactory foConnectionFactory() {
return ConnectionFactories.get(url);
}
#Bean
public R2dbcEntityOperations foEntityTemplate(#Qualifier("foConnectionFactory") ConnectionFactory connectionFactory) {
DefaultReactiveDataAccessStrategy strategy = new DefaultReactiveDataAccessStrategy(PostgresDialect.INSTANCE);
DatabaseClient databaseClient = DatabaseClient.builder()
.connectionFactory(connectionFactory)
.bindMarkers(PostgresDialect.INSTANCE.getBindMarkersFactory())
.build();
return new R2dbcEntityTemplate(databaseClient, strategy);
}
}
#Configuration
#EnableR2dbcRepositories(entityOperationsRef = "ifEntityTemplate")
public class IFDatabaseConfig {
//#Value("${spring.r2dbc.if.connection.url}")
private String url = "r2dbc:postgresql://username:password#database-blue-if-CSS-db.corp.com:1200/if_pgdb";
#Bean
#Qualifier("ifConnectionFactory")
public ConnectionFactory ifConnectionFactory() {
return ConnectionFactories.get(url);
}
#Bean
public R2dbcEntityOperations ifEntityTemplate(#Qualifier("ifConnectionFactory") ConnectionFactory connectionFactory) {
DefaultReactiveDataAccessStrategy strategy = new DefaultReactiveDataAccessStrategy(PostgresDialect.INSTANCE);
DatabaseClient databaseClient = DatabaseClient.builder()
.connectionFactory(connectionFactory)
.bindMarkers(PostgresDialect.INSTANCE.getBindMarkersFactory())
.build();
return new R2dbcEntityTemplate(databaseClient, strategy);
}
}
#Service
#RequiredArgsConstructor
public class CrewMemberSchedulePeriodPaymentService {
private final FOCrewMemberBidLineRepository foCrewMemberBidlineRepository;
private final IFCrewMemberBidLineRepository ifCrewMemberBidLineRepository;
public Flux<FOCrewMemberBidLine> getFOBidLines(List<Long> id) {
return foCrewMemberBidlineRepository.findAllById(id);
}
public Flux<IFCrewMemberBidLine> getIFBidLines(List<Long> id) {
return ifCrewMemberBidLineRepository.findAllById(id);
}
}
#Repository
public interface FOCrewMemberBidLineRepository extends R2dbcRepository<FOCrewMemberBidLine, Long> {
#Override
Flux<FOCrewMemberBidLine> findAllById(Iterable<Long> longs);
}
#Repository
public interface IFCrewMemberBidLineRepository extends R2dbcRepository<IFCrewMemberBidLine, Long> {
#Override
Flux<IFCrewMemberBidLine> findAllById(Iterable<Long> longs);
}
#Table(value = "BID_LINES")
#Builder
#NoArgsConstructor
#AllArgsConstructor
#Data
public class FOCrewMemberBidLine {
#Id
#Column(value = "bidlinseqnumber")
private Long bidlinseqnumber;
#Column(value = "bidlinschedperiod")
private String bidlinschedperiod;
}
#Table(value = "BID_LINES")
#Builder
#NoArgsConstructor
#AllArgsConstructor
#Data
public class IFCrewMemberBidLine {
#Id
#Column(value = "bidlinseqnumber")
private Long bidlinseqnumber;
#Column(value = "bidlinschedperiod")
private String bidlinschedperiod;
}

Maybe be you can add the connection factory invkoing the method, like this:
#Bean
#Qualifier("foConnectionFactory")
public ConnectionFactory foConnectionFactory() {
return ConnectionFactories.get("r2dbc:postgresql://username:password#database-dev-fo-css-rr-db.corp.com:1200/fo_pgdb");
}
#Bean
#Qualifier("ifConnectionFactory")
public ConnectionFactory ifConnectionFactory() {
return ConnectionFactories.get("r2dbc:postgresql://username:password#database-blue-if-CSS-db.corp.com:1200/if_pgdb");
}
#Bean
public R2dbcEntityOperations ifEntityTemplate() {
DefaultReactiveDataAccessStrategy strategy = new DefaultReactiveDataAccessStrategy(PostgresDialect.INSTANCE);
DatabaseClient databaseClient = DatabaseClient.builder()
.connectionFactory(ifConnectionFactory()) //<-- change
.bindMarkers(PostgresDialect.INSTANCE.getBindMarkersFactory())
.build();
return new R2dbcEntityTemplate(databaseClient, strategy);
}
#Bean
public R2dbcEntityOperations foEntityTemplate() {
DefaultReactiveDataAccessStrategy strategy = new DefaultReactiveDataAccessStrategy(PostgresDialect.INSTANCE);
DatabaseClient databaseClient = DatabaseClient.builder()
.connectionFactory(foConnectionFactory()) //<-- change
.bindMarkers(PostgresDialect.INSTANCE.getBindMarkersFactory())
.build();
return new R2dbcEntityTemplate(databaseClient, strategy);
}
You can have all of your beans in the same class and each bean will be created with the connection factory that you need.
Cheers.

Related

Why does MongoRepository save return an empty json and save empty value when a variable is not empty?

I have a simple document:
#Document
#NoArgsConstructor
#AllArgsConstructor
#Builder
#ToString
public class ProductUnit {
#Id
String id;
private String name;
private Integer price;
private LocalDateTime localDateTime;
}
Simple MongoRepository :
public interface productRepo extends MongoRepository<ProductUnit,String> {
ProductUnit deleteByName(String name);
List<ProductUnit> findByPrice(Integer price);
}
and Service :
#Service
public class productServiseImpl implements productServise {
#Autowired
productRepo repository;
#Override
public ProductUnit saveOrUpdate(ProductUnit productUnit) {
System.out.println("inside save or update");
return repository.save(productUnit);
}
#Override
public List<ProductUnit> findAll() {
return repository.findAll();
}
#Override
public ProductUnit deleteUnitByPrice(String name) {
return repository.deleteByName(name);
}
#Override
public List<ProductUnit> findByPrice(Integer price) {
return repository.findByPrice(price);
}
}
Now , inside RestController , I pass id through a post request and use a random class to generate a random value of the price and name .At this stage everything is fine, i.e. all values were initialized correctly, but when it comes to service.saveOrUpdate(forSave) It stores the value incorrectly, i.e. the request returns an empty json and the findAll method returns a list of empty json.Can you tell me what the error is? thanks
#RestController
public class productUnitRestController {
#Autowired
productServise service;
#Autowired
Supplier<MetaInfGenerator> generatorSupplier;
#GetMapping(path = "/all")
public List<ProductUnit> getAllProoduct(){
return service.findAll();
}
#PostMapping(path = "/products")
public ProductUnit createProoduct(#RequestParam("id") Optional<String> newId){
System.out.println("***** iside PostMapping ******");
MetaInfGenerator generator = generatorSupplier.get();
System.out.println("***** supplier PostMapping ******");
ProductUnit forSave = ProductUnit.builder()
.id(newId.get())
.name(generator.getRandomString())
.price(generator.getRandomInteger())
.localDateTime(LocalDateTime.now()).build();
System.out.println(forSave);
return service.saveOrUpdate(forSave);
}
}

Trying to insert Json into Neo4j

Everyone I am new to neo4j and I am trying to enter Json into Neo4j but I am getting Match statement instead of create. Earlier I tried something myself and when When I inserted Json message only as
{"name":"john","dept":"Science"}
it went without a glitch but everytime I want try to add numeric data it gets error.
2020-03-10 13:21:59.793 INFO 94817 --- [ntainer#0-0-C-1] o.n.o.drivers.http.request.HttpRequest : Thread:
29, url: http://localhost:7474/db/data/transaction/92, request: {"statements":[{"statement":"UNWIND {rows}
as row **MATCH** (n) WHERE ID(n)=row.nodeId SET n:`UsersInfo` SET n += row.props RETURN row.nodeId as ref,
ID(n) as id, {type} as type","parameters":{"type":"node","rows":[{"nodeId":23,"props":{"name":"raj",
"dept":"science","age":11}}]},"resultDataContents":["row"],"includeStats":false}]}
These are my classes
KafkaConfiguration
#EnableKafka
#Configuration
public class KafkaConfiguration {
#Bean
public ConsumerFactory<String, Users> userConsumerFactory(){
Map<String, Object> config = new HashMap<>();
config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092");
config.put(ConsumerConfig.GROUP_ID_CONFIG, "group_json");
config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);
return new DefaultKafkaConsumerFactory<>(config, new StringDeserializer(),
new JsonDeserializer<>(Users.class));
}
#Bean
public ConcurrentKafkaListenerContainerFactory<String, Users> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, Users> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(userConsumerFactory());
return factory;
}
}
KafkaConsumer class
Service
public class KafkaConsumer {
#Autowired
public Neo4jservice neo4jService;
#KafkaListener(topics = "UsersJson", groupId = "group_id", containerFactory = "kafkaListenerContainerFactory")
public void consume(Users users) {
System.out.println("Consumed message: " + users);
UsersInfo usern = new UsersInfo();
usern.setAge(users.getAge());
usern.setDept(users.getDept());
usern.setId(users.getId());
usern.setName(users.getName());
neo4jService.saveIntoStudentsTable(usern);
}
}
Neo4jService
#Service
public class Neo4jservice {
#Autowired
private UsersRepo userRepo;
public UsersInfo saveIntoStudentsTable(UsersInfo users) {
UsersInfo usern = userRepo.save(users);
return (usern);
}
}
UsersRepo
#Repository
public interface UsersRepo extends Neo4jRepository<UsersInfo, Long>{
}
Users class
public class Users {
private Long id;
private String name;
private String dept;
private Integer age;
**getters,setters and toString method here**
}
Likewise UsersInfo class
#NodeEntity
public class Users {
#Id
private Long id;
private String name;
private String dept;
private Integer age;
**getters,setters and toString method here**
}
Any help will be greatly appreciated. Thanks
You are setting also the id value of the User class.
This will make Spring Data Neo4j and the Neo4j Object Graph Mapper that is used for the persistence think that the entity already exists.
In this case it will MATCH on an existing id(n) and update the properties as you can see in the logs instead of CREATE a new node.

Spring Batch - How to make two queries or pass two objects to the Processor or writer?

I am developing Spring Boot Spring Batch code. Reading data from the Oracle DB and loading all the data into the MongoDB (NOSQL DB). Modelling of MongoDB is developed as de-normalized way as per the standard way of implementing mongo relations/modelling.
I've TableA and TableB table and Join Table TableAB between them which is 3rd Table. When I read TableA Table via JdbcCursorItemReader<TableA> that time for each PK Id of TableA I need to Query to SubDivision Table to get all the SubDivision for the TableA's PK and populate SubDivision Data set it into model of TableA. TableA model has list Of SubDivisions.
The only way I see making the query from TableAProcessor and set data into the model of TableA, its easy to implement, but issue is that its making 100K calls to DB from TableAProcess if I've 100K TableA records.
How can I achieve this and set the SubDivision data to the model of TableA from either using Tasklet or any other way?
How to avoid calling so many query from Processor ?
I cant make a single query due to some limitations hence I need to query one more query to DB to get SubDivision Data.
#Slf4j
public class TableAProcessor implements ItemProcessor<TableA, TableA>{
#Autowired
private TableADao tableADao;
#Override
public TableA process(TableA tableA) throws Exception {
log.debug("TableA DETAILS : "+tableA);
List<SubDivision> subDivisions = tableADao.getSubDivision(tableA.getPKId());
tableA.setSubDivisions(subDivisions);
return tableA;
}
}
Model
public class TableA {
#Transient
private Integer Id;
#Field
private String mongoId;
........
.......
#Field
private List<SubDivision> subDivisions;
}
TableABatchConfig.java
#Configuration
public class TableABatchConfig {
private static final String sql = "SELECT * FROM TABLEA";
#Autowired
#Qualifier(value="oracleDataSource")
private DataSource dataSource;
#Bean(destroyMethod = "")
#StepScope
public JdbcCursorItemReader<TableA> TableAReader() throws Exception {
JdbcCursorItemReader<TableA> reader = new JdbcCursorItemReader<TableA>();
reader.setDataSource(this.dataSource);
reader.setSql(sql);
reader.setRowMapper(new TableARowMapper());
reader.afterPropertiesSet();
return reader;
}
#Bean
public ItemProcessor<TableA, TableA> TableAProcessor() {
return new TableAProcessor();
}
#Bean
public TableAWriter TableAWriter() {
return new TableAWriter();
}
}
TableAJob.java
#Configuration
#PropertySource("classpath:application.properties")
public class TableAJob {
#Value( "${spring.chunk.size}")
private String chunkSize;
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private StepBuilderFactory stepBuilderFactory;
#Autowired
private JdbcCursorItemReader<TableA> TableAReader;
#Autowired
private ItemProcessor<TableA, TableA> TableAProcessor;
#Autowired
private TableAWriter TableAWriter;
#Bean
public TableAStepExecuListner TableAStepExecuListner() {
return new TableAStepExecuListner();
}
#Bean("readTableAJob")
#Primary
public Job readTableAJob() {
return jobBuilderFactory.get("readTableAJob")
.incrementer(new RunIdIncrementer())
.start(TableAStepOne())
.build();
}
#Bean
public Step TableAStepOne() {
return stepBuilderFactory.get("TableAStepOne")
.<TableA, TableA>chunk(Integer.parseInt(chunkSize))
.reader(TableAReader)
.processor(TableAProcessor)
.writer(TableAWriter)
.listener(TableAStepExecuListner())
.build();
}
}
dao
#Service
public class TableADao {
private static final String SQL = "COMPLEX JOIN QUERY";
#Autowired
private JdbcTemplate jdbcTemplate;
public List<SubDivision> getSubDivision(Integer pkId){
List<Map<String, Object>> results = jdbcTemplate.queryForList(SQL,new Object[] { pkId });
List<SubDivision> divisions = new ArrayList<>();
for (Map<String, Object> row : results) {
divisions.add(SubDivision.builder().subDivisionCd((String)row.get("SUBDIVISION_CD"))
......
.........
.........
......
.build());
}
return divisions;
}
}
TableAWriter.java
public class TableAWriter implements ItemWriter<TableA>{
#Autowired
private TableARepository TableARepository;
#Override
public void write(List<? extends TableA> items) throws Exception {
TableARepository.saveAll(items);
}
}

Ignite : select query returns null

I am new to ignite , I am trying to fetch data using ignite repository but below query returns 'null'.
my repository
#Component
#RepositoryConfig(cacheName = "UserCache")
#Repository
public interface UserRepository extends IgniteRepository<UserEntity, Long> {
#Query("select a.* from UserEntity a where a.lastname=? ")
UserEntity selectUserlastName(String plastName);
My cache configuration as
CacheConfiguration<Long, UserEntity> lUserCacheConfig =
createCacheConfigurationStore("UserCache", UserCacheStore.class);
CacheJdbcPojoStoreFactory<Long, UserEntity> lUserJdbcStoreFactory = new
CacheJdbcPojoStoreFactory<>();
UserJdbcPojoStoreFactory<? super Long, ? super UserEntity>
lUserJdbcPojoStoreFactory = new UserJdbcPojoStoreFactory<>();
lUserJdbcStoreFactory.setDataSource(datasource);
lUserJdbcStoreFactory.setDialect(new OracleDialect());
lUserJdbcStoreFactory.setTypes(lUserJdbcPojoStoreFactory.
configJdbcContactType());
lUserCacheConfig.setCacheStoreFactory(lUserJdbcStoreFactory);
// Configure Cache..
cfg.setCacheConfiguration(lUserCacheConfig);
My PojoStore is as below:
public class UserJdbcPojoStoreFactory<K, V> extends
AnstractJdbcPojoStoreFactory<Long, UserEntity> {
private static final long serialVersionUID = 1L;
#Autowired
DataSource datasource;
#Override
public CacheJdbcPojoStore<Long, UserEntity> create() {
// TODO Auto-generated method stub
setDataSource(datasource);
return super.create();
}
#Override
public JdbcType configJdbcContactType() {
JdbcType jdbcContactType = new JdbcType();
jdbcContactType.setCacheName("UserCache");
jdbcContactType.setKeyType(Long.class);
jdbcContactType.setValueType(UserEntity.class);
jdbcContactType.setDatabaseTable("USER");
jdbcContactType.setDatabaseSchema("ORGNITATION");
jdbcContactType.setKeyFields(new JdbcTypeField(Types.INTEGER, "id",
Long.class, "id"));
jdbcContactType.setValueFields(
new JdbcTypeField(Types.VARCHAR, "NAME", String.class, "NAME"), //
new JdbcTypeField(Types.VARCHAR, "LASTNAME", String.class, "lastname"),
//
return jdbcContactType;
}
}
Please suggest ..
Please check that #Query annotation imported from ignite-spring-data library and test your query using SqlFieldsQuery.

Spring boot application with EnableCaching How to retrieve guava cache content

It'm using a spring boot application with cache enabled.
Environment (pom.xml):
Spring:
org.springframework.boot:spring-boot-starter-amqp:jar:1.3.3.RELEASE
org.springframework:spring-messaging:jar:4.2.5.RELEASE
org.springframework.amqp:spring-rabbit:jar:1.5.4.RELEASE
org.springframework.retry:spring-retry:jar:1.1.2.RELEASE
org.springframework:spring-core:jar:4.2.5.RELEASE:compile
org.springframework.cloud:spring-cloud-aws-context:jar:1.0.4.RELEASE
org.springframework:spring-context:jar:4.2.5.RELEASE
org.springframework.data:spring-data-jpa:jar:1.9.4.RELEASE
org.springframework:spring-context-support:jar:4.2.5.RELEASE
Hibernate
org.hibernate:hibernate-validator:jar:5.2.2.Final
org.hibernate.javax.persistence:hibernate-jpa-2.1-api:jar:1.0.0.Final
com.fasterxml.jackson.datatype:jackson-datatype-hibernate4:jar:2.6.5
org.hibernate:hibernate-entitymanager:jar:5.1.0.Final
org.hibernate.common:hibernate-commons-annotations:jar:5.0.1.Final
org.hibernate:hibernate-java8:jar:5.1.0.Final
org.hibernate:hibernate-envers:jar:5.1.0.Final
Configuration Cache (on Spring boot application):
#Configuration
#EnableCaching
public class ApplicationCacheConfig extends CachingConfigurerSupport {
/**
* Configuration Table Cache
*/
public static final String CONFIGURATION_TABLE_FIND_BY_ID_CACHE_NAME = "CONFIGURATION_TABLE_FIND_BY_ID_CACHE";
public static final String CONFIGURATION_TABLE_FIND_SERVICE_ID_CACHE_NAME = "CONFIGURATION_TABLE_FIND_SERVICE_ID_CACHE";
#Bean
#Override
public CacheManager cacheManager() {
SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
Collection<Cache> caches = Lists.newArrayList();
caches.addAll(buildConfigurationCache());
simpleCacheManager.setCaches(caches);
return simpleCacheManager;
}
private Collection<Cache> buildConfigurationCache() {
List<Cache> caches = Lists.newArrayList();
// This cache never expires and don't have a maximum size because the table Configuration is not transactional
GuavaCache cacheFindById = new GuavaCache(CONFIGURATION_TABLE_FIND_BY_ID_CACHE_NAME,
CacheBuilder.newBuilder().build());
caches.add(cacheFindById);
// This cache never expires and don't have a maximum size because the table Configuration is not transactional
GuavaCache cacheFindByService = new GuavaCache(CONFIGURATION_TABLE_FIND_SERVICE_ID_CACHE_NAME,
CacheBuilder.newBuilder().build());
caches.add(cacheFindByService);
return caches;
}
}
Hibernate entity:
#Entity
#Table(name = Configuration.TABLE_NAME)
#DynamicUpdate
public class Configuration implements Serializable {
public static final String TABLE_NAME = "configuration";
private static final long serialVersionUID = 1L;
#Id
#Column(name = "id")
#Convert(converter = ConfigurationConverter.class)
private ConfigurationEnum id;
#Column(name = "service", nullable = false)
#NotNull
#Convert(converter = ServiceConverter.class)
private ServiceEnum service;
}
Repository (Spring-data):
public interface ConfigurationRepository extends PagingAndSortingRepository<Configuration, Integer>,
JpaSpecificationExecutor<Configuration> {
#Cacheable(ApplicationCacheConfig.CONFIGURATION_TABLE_FIND_BY_ID_CACHE_NAME)
Configuration findById(ConfigurationEnum configurationEnum);
#Cacheable(ApplicationCacheConfig.CONFIGURATION_TABLE_FIND_SERVICE_ID_CACHE_NAME)
List<Configuration> findByService(ServiceEnum service);
}
Configuration Enum:
#Getter
#AllArgsConstructor
public enum ConfigurationEnum {
CONFIG_1(1),
CONFIG_2(2);
private int id;
}
Configuration Converter:
#Converter
public class ConfigurationConverter implements AttributeConverter<ConfigurationEnum, Integer> {
#Override
public Integer convertToDatabaseColumn(ConfigurationEnum key) {
return key == null ? null : (int) key.getId();
}
#Override
public ConfigurationEnum convertToEntityAttribute(Integer key) {
return key == null ? null : Stream.of(ConfigurationEnum.values())
.filter(step -> key.equals(step.getId()))
.findFirst()
.orElse(null);
}
}
Test IT:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = ApplicationIT.class)
#WebAppConfiguration
#Transactional
public class ConfigurationCacheIT {
#Autowired
ConfigurationRepository configurationRepository;
#Autowired
protected CacheManager cacheManager;
#Test
public void configuration_findById_cache_success() {
Configuration config = configurationRepository.findById(ConfigurationEnum.CONFIG_1);
// An ORM request is performed - CHECK
Assert.assertNotNull(step); // TEST OK
Cache.ValueWrapper entry = getCacheEntry(ApplicationCacheConfig.CONFIGURATION_TABLE_FIND_BY_ID_CACHE_NAME, ConfigurationEnum.CONFIG_1.getId());
Assert.assertNull(entry); OK
config = configurationRepository.findById(ConfigurationEnum.CONFIG_1);
// No ORM request is performed - CHECK
Assert.assertNotNull(step); // TEST OK
entry = getCacheEntry(ApplicationCacheConfig.CONFIGURATION_TABLE_FIND_BY_ID_CACHE_NAME, ConfigurationEnum.CONFIG_1.getId());
Assert.assertNotNull(entry); **// TEST FAIL !!!**
entry = getCacheEntry(ApplicationCacheConfig.CONFIGURATION_TABLE_FIND_BY_ID_CACHE_NAME, ConfigurationEnum.CONFIG_1.name());
Assert.assertNotNull(entry); **// TEST FAIL !!!**
entry = getCacheEntry(ApplicationCacheConfig.CONFIGURATION_TABLE_FIND_BY_ID_CACHE_NAME, ConfigurationEnum.CONFIG_1);
Assert.assertNotNull(entry); **// TEST FAIL !!!**
}
protected Cache.ValueWrapper getCacheEntry(String cacheName, Object key) {
return cacheManager.getCache(cacheName).get(key);
}
#Test
public void configuration_findByAll_without_cache_success() {
ArrayList<Configuration> list1 = Lists.newArrayList(configurationRepository.findAll());
// An ORM request is executed
Assert.assertNotNull(list1);
Assert.assertEquals(ConfigurationEnum.values().length, list1.size());
ArrayList<Configuration> list2 = Lists.newArrayList(configurationRepository.findAll());
// Another ORM request is executed
Assert.assertNotNull(list2);
Assert.assertEquals(ConfigurationEnum.values().length, list2.size());
}
}
My question is why my tests are failing?
Actually this was a non issue.
I'm using the fallowing architecture:
App-mdw (Middleware layer) (Spring boot App with #EnableCaching annotation)
App-ws (WebServices layer) (Spring boot App without #EnableCaching annotation)
The above tests were executed on the application App-ws and the annotation is not inherited that's why the caching was not working.
The right assert was:
entry = getCacheEntry(ApplicationCacheConfig.CONFIGURATION_TABLE_FIND_BY_ID_CACHE_NAME, ConfigurationEnum.CONFIG_1);
Assert.assertNotNull(entry)

Resources