Spring Boot JPA repositories custom query - spring-boot

http://spring.io/guides/gs/accessing-data-jpa/
Referred the above link to define a custom query.
We have a developed a Spring boot web service CRUD application but we are facing the following exception when we add a custom query.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'EmployeeController': Unsatisfied dependency expressed through field 'EmployeeService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'EmployeeServiceImpl': Unsatisfied dependency expressed through field 'EmployeeRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'EmployeeRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'EmployeeServiceImpl': Unsatisfied dependency expressed through field 'EmployeeRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'EmployeeRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'EmployeeRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77) ~[spring-data-commons-1.13.4.RELEASE.jar:naat org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:309) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:272) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
This was the repository interface that I have defined. Defined a custom query.
package com.example.rest.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.rest.model.Employee;
#Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
Employee findByName(String employeeName);}
This is my service interface
package com.example.rest.service;
import java.util.List;
import com.example.rest.model.Employee;
public interface EmployeeService {
Employee save(Employee employee);
Employee getById(Long employeeId);
void delete(Long employeeId);
List<Employee> findAll();
Employee findByName(String employeeName); }
This is my Service Implementation class
package com.example.rest.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.rest.model.Employee;
import com.example.rest.repository.EmployeeRepository;
#Service
public class EmployeeServiceImpl implements EmployeeService {
#Autowired
EmployeeRepository employeeRepository;
#Override
public Employee save(Employee employee) {
// TODO Auto-generated method stub
return employeeRepository.save(employee);
}
#Override
public Employee getById(Long employeeId) {
// TODO Auto-generated method stub
return employeeRepository.getOne(employeeId);
}
#Override
public void delete(Long employeeId) {
// TODO Auto-generated method stub
employeeRepository.delete(employeeId);
}
#Override
public List<Employee> findAll() {
// TODO Auto-generated method stub
return employeeRepository.findAll();
}
#Override
public Employee findByName(String employeeName) {
// TODO Auto-generated method stub
return employeeRepository.findByName(employeeName);
}}
Without custom query my application works fine.
Let me know where I have made a mistake.
I have added the model class
package com.example.rest.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="testF")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(nullable=false, unique=true)
private Long employeeId;
#Column(nullable=false, unique=true)
private String employeeName;
#Column(nullable=false)
private String emailId;
#Column(nullable=false)
private Long salary;
public Employee() {
}
public Employee(Long employeeId, String employeeName, String emailId, Long salary) {
this.employeeId = employeeId;
this.employeeName = employeeName;
this.emailId = emailId;
this.salary = salary;
}
public Long getEmployeeId() {
return employeeId;
}
public void setEmployeeId(Long employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public Long getSalary() {
return salary;
}
public void setSalary(Long salary) {
this.salary = salary;
}
#Override
public String toString() {
return "Employee [employeeId=" + employeeId + ", employeeName=" + employeeName + ", emailId=" + emailId
+ ", salary=" + salary + "]";
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((employeeId == null) ? 0 : employeeId.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (employeeId == null) {
if (other.employeeId != null)
return false;
} else if (!employeeId.equals(other.employeeId))
return false;
return true;
}}

you don't have field 'name' in class Employee.
spring data try created query for search Employee with field name.
Employee findByName(String employeeName);}

Your model doesn't have name property, you have employeeName, so your query should look like this:
Employee findByEmployeeName(String employeeName);
Please see reference for more info on how to build Spring Data queries. In short, when you want to create a query you have to specify full field name how it is written in your Entity.

u can't write findByName in your custom query because u don't have a name field however u can write EmployeeName

Related

Builder Pattern and Dependecy Injection - how to fix problem

I wanted to create a class based on the builder pattern. Using the static method build. Which would return a properly built object based on initial validation checking whether a given object exists in the database.
#Component
#Data
#Builder
public class GetBookedSeatsRequest {
#Autowired
private MovieRepository movieRepository;
#Autowired
public CinemaRepository cinemaRepository;
#Autowired
public PropertiesMovieRepository propertiesMovieRepository;
private String cinemaName;
private String movieName;
private String movieRoom;
#JsonFormat(pattern="yyyy-MM-dd; HH:mm:ss",shape = JsonFormat.Shape.STRING)
private LocalDateTime localDateTime;
private List<Integer> wantedSeats;
public GetBookedSeatsRequest build(ReservationModel reservationModel) throws CinemaNotFoundException, MovieNotFoundException, PropertyMovieNotFoundException {
boolean cinemaExist = cinemaRepository.existsByCinemaName(reservationModel.getCinemaName());
if (!cinemaExist) {
throw new CinemaNotFoundException("Cinema doesn't exist");
}
boolean movieExist = movieRepository.existsByMovieName(reservationModel.getMovieName());
if (!movieExist) {
throw new MovieNotFoundException("Movie doesn't exist");
}
boolean roomExist = movieRepository.existsByMovieRoom(reservationModel.getMovieRoom());
if (!roomExist) {
throw new MovieNotFoundException("Movie Romm doesn't exist");
}
boolean existData = propertiesMovieRepository.existsByStartTimeOfTheMovie(reservationModel.getDateAndTime());
if (!existData) {
throw new PropertyMovieNotFoundException("This data doesn't exist");
}
// boolean existSeats = movieRepository.existsBySeating(reservationModel.getSeatsToBooked());
// if (!existSeats) {
// throw new MovieNotFoundException("This seats doesn't exist");
// }
GetBookedSeatsRequest correct = GetBookedSeatsRequest.builder()
.cinemaName(reservationModel.getCinemaName())
.movieName(reservationModel.getMovieName())
.movieRoom(reservationModel.getMovieRoom())
.localDateTime(reservationModel.getDateAndTime())
.wantedSeats(reservationModel.getSeatsToBooked())
.build();
return correct;
}
}
#Data
#AllArgsConstructor
public class ReservationModel {
private String cinemaName;
private String movieName;
private String movieRoom;
#JsonFormat(pattern="yyyy-MM-dd; HH:mm:ss",shape = JsonFormat.Shape.STRING)
private LocalDateTime dateAndTime;
private List<Integer> seatsToBooked;
}
But I still got some erros. What am I doing wrong, I am learing Spring Boot. Thanks for help
Description:
Parameter 3 of constructor in com.cinema.booking.aop.GetBookedSeatsRequest required a bean of type 'java.lang.String' that could not be found.
Action:
Consider defining a bean of type 'java.lang.String' in your configuration.

Spring Data: Query By Example and Converter

I have an entity:
import javax.persistence.Convert;
#Entity(name = "my_entity")
public class MyEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
#Convert(converter = StringListConverter.class)
private List<String> emails;
// next fields omitted...
}
Converter which is used by emails field in entity (typical implementation like LocalDateTimeConverter):
import javax.persistence.Converter;
#Converter
public class StringListConverter implements AttributeConverter<List<String>, String> {
private static final String SPLIT_CHAR = ";";
#Override
public String convertToDatabaseColumn(List<String> stringList) {
if (CollectionUtils.isNotEmpty(stringList)) {
return String.join(SPLIT_CHAR, stringList);
} else {
return null;
}
}
#Override
public List<String> convertToEntityAttribute(String string) {
if (StringUtils.isNotBlank(string)) {
return Arrays.asList(string.split(SPLIT_CHAR));
} else {
return Collections.emptyList();
}
}
}
(I store emails separated by semicolons in one column. StringListConverter do that conversion.)
And Spring Data repository:
import org.springframework.data.domain.Example;
public interface MyRepository extends JpaRepository<MyEntity, Long> {
default List<MyEntity> findMatchingMyEntity(MyEntity myEntity) {
Example<MyEntity> example = Example.of(myEntity);
return findAll(example);
}
}
I use Query by Example mechanism from Spring Data. When I have fields without #Convert (like String name) it works. But when I have field with #Convert (AttributeConverter) like List<String> emails it causes InvalidDataAccessApiUsageException.
org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [abc#company.com] did not match expected type [java.util.List (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [abc#company.com] did not match expected type [java.util.List (n/a)]
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:374) ~[spring-orm-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:257) ~[spring-orm-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528) ~[spring-orm-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61) ~[spring-tx-5.2.1.RELEASE.jar:5.2.1.RELEASE]
...
Caused by: java.lang.IllegalArgumentException: Parameter value [abc#company.com] did not match expected type [java.util.List (n/a)]
at org.hibernate.query.spi.QueryParameterBindingValidator.validate(QueryParameterBindingValidator.java:54) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
at org.hibernate.query.spi.QueryParameterBindingValidator.validate(QueryParameterBindingValidator.java:27) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
at org.hibernate.query.internal.QueryParameterBindingImpl.validate(QueryParameterBindingImpl.java:90) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
... 146 common frames omitted
(message is weird because I've tried search with that list: ["abc#company.com", "def#company.com"], but in message is only one email)
I've tried to implement transform in ExampleMatcher:
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
public interface MyRepository extends JpaRepository<MyEntity, Long> {
default List<MyEntity> findMatchingMyEntity(MyEntity myEntity) {
ExampleMatcher matcher = ExampleMatcher.matching()
.withMatcher("emails",
match -> match.transform(emailsOptional -> {
if (emailsOptional.isPresent()) {
List<String> emails = (List<String>) emailsOptional.get();
return Optional.ofNullable(new StringListConverter().convertToDatabaseColumn(emails));
}
return emailsOptional;
}));
Example<MyEntity> example = Example.of(myEntity, matcher);
return findAll(example);
}
}
But is causes InvalidDataAccessApiUsageException too, but with different message than previous one (there are two emails that I've set):
org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [abc#company.com;def#company.com] did not match expected type [java.util.List (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [abc#company.com;def#company.com] did not match expected type [java.util.List (n/a)]
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:374) ~[spring-orm-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:257) ~[spring-orm-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528) ~[spring-orm-5.2.1.RELEASE.jar:5.2.1.RELEASE]
Caused by: java.lang.IllegalArgumentException: Parameter value [abc#company.com;def#company.com] did not match expected type [java.util.List (n/a)]
at org.hibernate.query.spi.QueryParameterBindingValidator.validate(QueryParameterBindingValidator.java:54) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
at org.hibernate.query.spi.QueryParameterBindingValidator.validate(QueryParameterBindingValidator.java:27) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
... 146 common frames omitted
It seems that for some reason Hibernate is trying to split the array of emails into multiple conditions just like in IN query in SQL using expandListValuedParameters method.
Note - with your solution doing query like findAllByEmailsIn(List<String> emailsList) also won't work.
Method expandListValuedParameters is deprecated since Hibernate 5.2, so it may contains some problems and for sure will be implemented differently in Hibernate 6.0.
I haven't found a fix for your problem, but there are some workarounds:
Wrap your List<String> emails in another class
Wrapper class:
public class EmailList {
private List<String> emails;
// getters, setters, constructors ommited
}
Updated model class:
import javax.persistence.Convert;
#Entity(name = "my_entity")
public class MyEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
#Convert(converter = StringEmailListConverter.class)
private EmailList emailList;
// next fields omitted...
}
Updated converter class:
import javax.persistence.Converter;
#Converter
public class StringEmailListConverter implements AttributeConverter<EmailList, String> {
private static final String SPLIT_CHAR = ";";
#Override
public String convertToDatabaseColumn(EmailList emailList) {
if (emailList != null && CollectionUtils.isNotEmpty(emailList.getEmails())) {
return String.join(SPLIT_CHAR, emailList.getEmails());
} else {
return null;
}
}
#Override
public EmailList convertToEntityAttribute(String string) {
if (StringUtils.isNotBlank(string)) {
return new EmailList(Arrays.asList(string.split(SPLIT_CHAR)));
} else {
return new EmailList(Collections.emptyList());
}
}
}
And Spring Data repository will work fine with this code - no need for using transform:
import org.springframework.data.domain.Example;
public interface MyRepository extends JpaRepository<MyEntity, Long> {
default List<MyEntity> findMatchingMyEntity(MyEntity myEntity) {
Example<MyEntity> example = Example.of(myEntity);
return findAll(example);
}
}
Use String[] emails instead of List<String> emails
You need to change MyEntity and Converter respectively to use String[]. Of course using String[] sometimes is not an option because you specifically need a List.

How #Autowired Work using Reflection and how invoke appropriate Setter Method

My Main Problem is that i can use Reflection API and i can invoke the setter method in my User bean class.But I have Only have UserBean objects. I does not know which setter method to invoke.i want extract all information in my User bean Object and the invoke appropriate Method using Reflection.
//-->This My User Bean Class
public class User {
private String name;
private int age;
private String getName() {
return name;
}
private void setName(String name) {
this.name = name;
}
private int getAge() {
return age;
}
private void setAge(int age) {
this.age = age;
}
void callMethod() { System.out.println("Name :- "+name+" Age :-"+age); }
#Override
public String toString() { return "User [name=" + name + ", age=" + age + "]";}
}
//--->This My Main Method
public class TestCase {
public static Object getBean(String beanClassName) throws Exception
{
Class klass = Class.forName(beanClassName);
Object obj = klass.newInstance();
Method[] b = klass.getDeclaredMethods();
String MethodName1 = "setName";
String MethodName2 = "setAge";
String name ="sanket";
int age = 21;
for(int i=0;i<b.length;i++)
{
if(b[i].getParameterTypes().toString().equals(MethodName1))
{
b[i].setAccessible(true);
b[i].invoke(obj,name);
}
if(b[i].getName().equals(MethodName2))
{
b[i].setAccessible(true);
b[i].invoke(obj,age);
}
}
return obj;
}
public static void main(String ars[]) throws Exception
{
Object obj1 = getBean("www.Fouth.User");
System.out.println(obj1.toString());
}
}
I my case I can invoke the setter method manually because i can invoke the setter method bases of method name.
I want Extract information in User Bean Class, and identify on the bases of value which setter to invoked.
In spring #AutoWired is does that.How they will identify which setter to invoke and inject dependency.
The Spring identifies which setters to inject dependencies by figuring out which setters are annotated with #Autowired , #Inject , #Resources etc.
Then it figures out which value to inject into the setter by checking the type of the setter arguments and injects the bean that has the same type.
If multiple beans have the same type, it then check the bean name. It will inject the bean that has the same name as configured in the injection point using #Qaulifer or #Resources.
If there are still multiple beans that satisfy to inject , NoUniqueBeanDefinitionException happens.
If there are no beans that satisfy to inject, NoSuchBeanDefinitionException happens.

JPA repository fail with good name of property and works with wrong name

I have a class with property named isChecked with is boolean type. In Jpa repository I wrote a method to find all rows which has isChecked = false;
public interface ReservationReminderRepository extends JpaRepository<ReservationReminder, Integer> {
ReservationReminder findByReservationReminderId(Integer id);
//#Query("select r from ReservationReminder r where r.isChecked = :checked")
List<ReservationReminder> findByChecked(boolean checked);
}
While I tried to call a method findByChecked() in Jpa reporistory everything works, but when I tried to run a method with the proper named of property - as it is in jpa doc findByIsChecked() I got strange fails:
Caused by: java.lang.IllegalArgumentException: Unable to locate Attribute with the the given name [isChecked] on this ManagedType [com.carwash.domains.ReservationReminder]
at org.hibernate.jpa.internal.metamodel.AbstractManagedType.checkNotNull(AbstractManagedType.java:128)
at org.hibernate.jpa.internal.metamodel.AbstractManagedType.getAttribute(AbstractManagedType.java:113)
at org.springframework.data.jpa.repository.query.QueryUtils.toExpressionRecursively(QueryUtils.java:566)
at org.springframework.data.jpa.repository.query.JpaQueryCreator$PredicateBuilder.getTypedPath(JpaQueryCreator.java:334)
at org.springframework.data.jpa.repository.query.JpaQueryCreator$PredicateBuilder.build(JpaQueryCreator.java:277)
at org.springframework.data.jpa.repository.query.JpaQueryCreator.toPredicate(JpaQueryCreator.java:182)
at org.springframework.data.jpa.repository.query.JpaQueryCreator.create(JpaQueryCreator.java:109)
at org.springframework.data.jpa.repository.query.JpaQueryCreator.create(JpaQueryCreator.java:49)
at org.springframework.data.repository.query.parser.AbstractQueryCreator.createCriteria(AbstractQueryCreator.java:109)
at org.springframework.data.repository.query.parser.AbstractQueryCreator.createQuery(AbstractQueryCreator.java:88)
at org.springframework.data.repository.query.parser.AbstractQueryCreator.createQuery(AbstractQueryCreator.java:73)
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$QueryPreparer.<init>(PartTreeJpaQuery.java:118)
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$CountQueryPreparer.<init>(PartTreeJpaQuery.java:241)
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:68)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:103)
... 104 more
Can anyone tell me why I received that kind of fail? How the method name would looks like when I'd like to check with property checkedDate?
package com.carwash.domains;
import javax.persistence.*;
import java.util.Date;
/**
* Created by mbi on 01.03.2017.
*/
#Entity
public class ReservationReminder {
private int reservationReminderId;
private Reservation reservation;
private boolean isChecked;
private Date checkedDate;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public int getReservationReminderId() {
return reservationReminderId;
}
public void setReservationReminderId(int reservationReminderId) {
this.reservationReminderId = reservationReminderId;
}
#OneToOne(mappedBy = "reservationReminder")
public Reservation getReservation() {
return reservation;
}
public void setReservation(Reservation reservation) {
this.reservation = reservation;
}
public boolean getChecked() {
return isChecked;
}
public void setChecked(Boolean checked) {
isChecked = checked;
}
public Date getCheckedDate() {
return checkedDate;
}
public void setCheckedDate(Date checkedDate) {
this.checkedDate = checkedDate;
}
#Override
public String toString() {
return "ReservationReminder{" +
"reviewId=" + reservationReminderId +
", isChecked=" + isChecked +
", checkedDate=" + checkedDate +
'}';
}
public ReservationReminder() {
}
public ReservationReminder(Boolean isChecked, Date checkedDate) {
this.isChecked = isChecked;
this.checkedDate = checkedDate;
}
public ReservationReminder(int reservationReminderId, Reservation reservation, boolean isChecked, Date checkedDate) {
this.reservationReminderId = reservationReminderId;
this.reservation = reservation;
this.isChecked = isChecked;
this.checkedDate = checkedDate;
}
}
It seems that the problem is related to the naming of that property.
As you are telling Spring to look for findByChecked and the property name is isChecked.
You can try to use findByIsChecked and change the getter to isChecked.
But actually i would change the property to checked, getter to isChecked and leave the jpa query method as it is.

CrudRepository Unsatisfied dependency expressed through field folioRepository

I am getting error Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'getFolioService': Unsatisfied dependency expressed through field 'folioRepository': No qualifying bean of type [a.b.c.repository.FolioRepository]
I am running Junit test case for my service, which save document in couchbase.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
public class FolioServiceTest {
#Autowired
private FolioService folioService;
#Test
public void testAddFolioTransaction() {
Folios folios = new Folios();
folios.setUiid("user123");
List<Order> orders = new ArrayList<Order>();
Order order = new Order();
order.set__type("type1");
order.set__version("version1");
order.setCreatedDate("09/02/2016");
order.setCreatedUser("test user");
OrderPayload orderPayload = new OrderPayload();
orderPayload.set__type("type payload type");
orderPayload.set__version("version payload type");
order.setOrderPayload(orderPayload);
orders.add(order);
folios.getOrder().addAll(orders);
boolean flag= folioService.addFolioTransaction(folios);
assertTrue(flag == true);
}
#Configuration
public class AppConfig {
#Bean
public FolioService getFolioService() {
return new FolioService();
}
}
}
#Service
public class FolioService {
private final static Logger LOGGER = LoggerFactory.getLogger(FolioService.class);
#Autowired
FolioRepository folioRepository;
/**
* Method will save the folio to the couchbase
*
* #param folios
*/
public boolean addFolioTransaction(Folios folios){
LOGGER.debug("Adding transaction details to folio.");
Folios newFolio = folioRepository.save(folios);
if (newFolio != null) {
return true;
}
return false;
}
public Folios getFolioDetailsByUiid(String uiid){
LOGGER.debug("Get folio details by uiid.");
Folios folios = folioRepository.findOne(uiid);
return folios;
}
}
#Repository
public interface FolioRepository extends CrudRepository{
}

Resources