Here I will describe about some common problems as faced by Developers while implementing Spring Data with Spring Boot.
Q-1). If I define a method in the Repository interface without following the basic Spring Data Convention. Then will I need to do the implementation?
A-1). Yes, you have to do the implementation. Let’s take an example. You have an entity named as User.java which consists of 3 properties as name, mobileNo and email. And you have attached this entity with the Repository Interface. Then according to Spring Data concept, you will get 3 default methods as findByName(), findByMobileNo() and findByEmail(). But now you have a business logic, where you want to show data by providing only the firstName of an User. And this is not possible because, you have a name property which holds both the first and last name separated by spaces. Then you define a method as fetchUserByFirstName() in the Repository interface. Obviously for this, you need an implementation method in the RepositoryImpl class. As, Spring Data doesn’t know anything about this method. It will throw an exception as “No property fetchUserByFirstName found for type User!”. And the exception is known as org.springframework.data.mapping.PropertyReferenceException. PFB the screenshot attached.
Q-2). If I want to use more than one property of an Entity in a single method of Repository Interface. What naming convention I have to follow?
A-2). Yes, you can define more than one property of an entity in a single method of Repository Interface. There is only one naming convention, you have to put And. As for example, I have defined one entity named as User.java and it has 5 properties like name, mobileNo and email. Now I want to define a method in interface which will fetch results based on mobileNo and name. The method definition will be as :
List<User> findByNameAndMobileNo(String name, String mobileNo);
If you need more details and examples on different types of derived queries examples of Spring Data. Check out this link, it holds a good volume of Derived Query Methods in Spring Data JPA Repositories.
Q-3). How to use OR concept in Spring Data?
A-3). The best way to implement the OR concept in Query language for Spring Data is to use method naming convention as findByNameOrEmail(). Another way is to use @Query annotation. Using this annotation you can write Hibernate Query Language (HQL) as well as Native Query Language like SQL. But remember one thing the arguments that you use to serve the query dynamically should be included as the parameter in the defined method. I have provided both scenarios. As for example:
1st Scenario - Using Spring Data Method naming convention
User findByNameOrEmail(String name, String email);
2nd Scenario - Using @Query annotation
@Query("from User where name = ?1 OR email = ?2")
User findByNameNotStartWithA(String name, String email);
If you want more details and clarifications on the Custom Query example. Then check out this link on Custom Queries with Spring Data JPA’s @Query Annotation.
Q-4). How will I integrate Spring Data with MySQL or any RDBMS using Spring Boot?
A-4). I will let you know on this. If you are using Maven then you need to add 1 dependency as spring-boot-starter-data-jpa. And if you use MySQL as RDBMS then another dependency is required named as mysql-connector-java.
I have a blog for this. Please refer to that blog. It consists of a source code and a brief understanding of Spring Data with MySQL using Spring Boot. Please refer to this Spring Data – JPA blog.
Q-5). How will I integrate Spring Data with NoSQL DB using Spring Boot?
A-5). If you want to integrate Spring Data with any NoSQL DB using Spring Boot, then you need only one dependency named as spring-boot-starter-data-mongodb.
I have a blog for this. Please refer to this Spring Data – Mongo blog.
Q-6). How will I integrate Spring Data with any GraphQL DB using Spring Boot?
A-6). GraphQL DB is the new addition to this New Technology World. And it is booming very fast. To integrate Spring Data with a GraphQL DB using Spring Boot you need one dependency named as spring-boot-starter-data-neo4j and if you use Neo4j as database then you need another dependency named as neo4j-ogm-core.
Please refer to this blog. It consists of the implementation of Spring Data using Neo4j as database using Spring Boot. Also this blog provides a little bit of understanding on the GraphQL Queries. Please refer to this blog as Spring Data – Neo4j.
Q-7). What will be the request and response type while implementing Spring Data?
A-7). You are implementing Spring Data with Spring REST using Spring Boot. Spring REST will provide you the REST APIs by which an end user will communicate with the underlying database. By default, Spring REST Supports the json data type. While you can also use, different other data types as xml, html, text, etc, both for request and response objects.
Q-8). Is the authentication is required for Mongo DB after installation in local machine?
A-8). Yes, obviously authentication is required. It will provide an extra level of security to your locally installed database. And when you want to connect Mongo DB from your application, specify the username and password property in either application.properties file or in application.yml file.
Q-9). I have installed Neo4j Database. But when I am trying to connect it is throwing me error as ‘Provide valid Username and Password’. How will I get the default username and password?
A-9). If you don’t keep the earlier Username and Password of your Neo4j database. Then in such scenario, the best option is to reset the password. This option to reset the password is applicable for all other types of databases as well. In case of Neo4j, click on the database as for Neo4j a default Schema is there as the Movie schema. Click on that Movie Schema, a segment will open at the right hand side where you can see the option as Reset DBMS Password. Click on that and reset the password.
Q-10). What is the problem if we don’t use the exact dependency required to connect to Redis from your Spring Boot Application?
A-10). If you don’t use the appropriate dependency for Redis in your Spring Boot Application then you will face connectivity issues with Redis. To avoid this use the dependency named spring-boot-starter-data-redis.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Q-11). What will be the problem if we don’t configure the Redis properties properly?
A-11). If you don’t set the connection properties of Redis properly it will not be able to connect to Redis server. Please find below the properties.
Using application.properties
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=yourpassword
spring.redis.database=0
Using application.yml
spring:
redis:
host: localhost
port: 6379
password: yourpassword
database: 0
Q-12). What are the solutions if I face a problem as Unable to connect to server?
A-12). You need to check that whether Redis server is running and accessible. If you find difficulty while connecting to Redis server then check the network configurations, firewall settings, and ensure that Redis server’s IP and port are correctly specified.
Q-13). What will be the problem if proper serialization/deserialization for key and value is not there?
A-13). You will face problems while inserting, updating, deleting, and reading the data from Redis Cache based on the key as provided. Configure the RedisTemplate bean properly as provided below:
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
Here you can see for key I have used the StringRedisSerializer and for value I have used the GenericJackson2JsonRedisSerializer.
Q-14). What is the problem associated with Spring Cache Configuration?
A-14). You need to ensure proper cache configuration by annotating your configuration class with @EnableCaching and configuring the CacheManager bean. Please find below a sample code snippet.
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.disableCachingNullValues();
return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(config)
.build();
}
}
Q-15). How to resolve the performance related issues?
A-15). To increase the performance, you can use the concept of connection pooling, and ensure that long-running operations are not blocking the Redis connection. Please find below the properties use d for connection pooling.
Using application.properties
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.pool.max-wait=1000ms
Using application.yml
spring:
redis:
lettuce:
pool:
max-active: 8
max-idle: 8
min-idle: 0
max-wait: 1000ms
Q-16). How will I solve the problem of testing Redis Integration through code?
A-16). You need to use embedded Redis for testing purposes or configure a test Redis instance.
A sample code is provided below for profile = test
@Configuration
@Profile("test")
public class EmbeddedRedisConfig {
private RedisServer redisServer;
@PostConstruct
public void startRedis() throws IOException {
redisServer = new RedisServer(6379);
redisServer.start();
}
@PreDestroy
public void stopRedis() {
redisServer.stop();
}
}