public Long countByLastName(String lastName){
LoadContext<Person> loadContext = LoadContext.create(Person.class);
loadContext
.setQueryString("select c from sample$Customer c where c.lastName = :lastName")
.setParameter("lastName", lastName);
return dataManager.getCount(loadContext);
}
<!-- Annotation-based beans -->
<context:component-scan base-package="com.company.sample"/>
<repositories:repositories base-package="com.company.sample.core.repositories"/>
</beans:beans>
If you prefer using annotations instead of creating XML config, you can enable query interfaces in the following way:
@Configuration
@EnableCubaRepositories
public class AppConfig {
//Configuration here
}
After enabling query interfaces you can create them in your application. An example of such an interface:
public interface CustomerRepository extends CubaJpaRepository<Customer, UUID> {
long countByLastName(String lastName);
List<Customer> findByNameIsIn(List<String> names);
@CubaView("_minimal")
@JpqlQuery("select c from sample$Customer c where c.name like concat(:name, '%')")
List<Customer> findByNameStartingWith(String name);
}
You can use @CubaView and @JpqlQuery annotations for query interface methods. The first one defines a view for the entities that will be fetched (“_local” is the default view if not specified). The second annotation specifies the exact JPQL query that will be used for this method if the query cannot be expressed with a method name.
Query interfaces application component is attached to “global” CUBA module, so you can define and use query interfaces in both “core” and “web” modules, just don’t forget to enable them in the corresponding configuration files. The interface usage example is below:
@Service(CustomerService.NAME)
public class CustomerServiceBean implements PersonService {
@Inject
private CustomerRepository customerRepository;
@Override
public List<Date> getCustomersBirthDatesByLastName(String name) {
return customerRepository.findByNameStartingWith(name)
.stream().map(Customer::getBirthDate).collect(Collectors.toList());
}
}
Conclusion
CUBA is flexible. If you feel that you need an additional feature for all your application and you don’t want to wait for the new version of CUBA, it is pretty easy to implement and add it not touching CUBA core. By adding query Interfaces to CUBA we hope to help developers work more efficiently delivering reliable code faster. The first version of the library is available at GitHub and supports CUBA version 6.10 and higher.