InterviewSolution
| 1. |
How to configure Hibernate Second Level Cache using EHCache? |
|
Answer» Validating data is an integral part of any application and HAPPENS in all the application layers. Most of the time, the same validations are replicated across the layers making it error-prone and time-consuming. To avoid duplication of the validation logic, JSR 380 DEFINES a metadata model and API for data validation i.e. entity and method validation. Hibernate Validator is the reference implementation of JSR380. When Hibernate Validator is used in an application, it will also require an implementation of the Unified Expression Language (JSR341) for evaluating dynamic expressions as well as the Hibernate Validator dependencies. Let us understand the Hibernate Validator with an example: <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.1.1.Final</version> </dependency>Let us create an Employee class: import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.CreditCardNumber; import org.hibernate.validator.constraints.Email; public class Employee { @Min(value=1, groups=EmpIdCheck.class) private int id; @NotNull(message="NAME cannot be null") @Size(min=5, max=30) private String name; @Email private String email; @CreditCardNumber private String creditCardNumber; //default no-args constructor public Employee(){} public Employee(int id, String name, String email, String ccNum){ this.id=id; this.name=name; this.email=email; this.creditCardNumber=ccNum; } public int getId() { return id; } public VOID setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getCreditCardNumber() { return creditCardNumber; } public void setCreditCardNumber(String creditCardNumber) { this.creditCardNumber = creditCardNumber; } }Hibernate validator provides very good validation annotations like @Email and @CreditCardNumber which avoids usage of implementation specific annotations which lead to loose coupling. Hibernate Validator also ALLOWS us to define Custom Error Messages which we can configure in the ValidationMessages.properties file in the classpath. The file looks like: #Hibernate Bug for @CreditCardNumber Workaround - https://hibernate.atlassian.net/browse/HV-881 org.hibernate.validator.constraints.LuhnCheck.message=The check digit for ${validatedValue} is invalid, Luhn Modulo 10 checksum failed. org.hibernate.validator.constraints.Email.message=Invalid email address |
|