Getting Entity Class in JPA and Repository Interface - java

I am applying repository similar to Spring Data JPA where I would only create an interface of an entity repository:
public interface AuthorRepository extends Repository<Author, Long> {
}
I have this also Repository interface:
public interface Repository <T, ID extends Serializable> {
List<T> findAll() throws Exception;
}
And its implementation, which I find it difficult to get the class name passed in as parameterized (T) to Repository :
public class RepositoryImpl implements Repository {
#Inject
private EntityManager em;
#Override
public List<Object> findAll() throws Exception {
try {
String namedQuery = "SELECT a FROM " + <How do I get the entity here as Author?> + " a";
TypedQuery<Object> query = em.createNamedQuery(namedQuery, <How do I get the entity class as Author.class?>);
return query.getResultList();
} catch (Exception e) {
System.out.println(e.getMessage());
throw new ApplicationException();
}
}
}
I can't find way how to dynamically generate the entity class (ex. Author) to be created as part of NamedQuery string and an argument for em.createNamequery().
Thanks for any help.

In the RepositoryImpl you can inject the entityInformation like this:
#Autowired
private JpaEntityInformation<T, ID> entityInformation;
and then use it for example like:
String entityName = entityInformation.getEntityName();
Class<T> entityType = entityInformation.getJavaType();
Custom RepositoryFragments sadly can't autowire the JpaEntityInformation because they are singletons, so for generic fragments one would either need to pass the entity class with each method call and use JpaEntityInformationSupport.getEntityInformation(clazz, entityManager) or modify the BeanDefinition of the fragments and get the clazz using the injection point.

Searching world wide web gave me similar approach and codes but none worked but TypeTools works like a charm.

Related

Any way to use the `#Procedure` annotation without an entity?

So I'd like a "Void-Repository" through which to gain access to stored procedures that are not necessarily operation on entities.
#Repository
public interface StoredProceduresRepository extends CrudRepository<Void, Long> {
#Procedure("my_answer_giver")
String getMyAnswer(#Param("input") String input);
}
But that does, of course, not work because the CrudRepository expects Void to be an entity.
Is there a way to use the #Procedure annotation without having to create dummy entities or am I stuck with an implemented class that makes use of the EntityManager to query via prepared statements?
Because let's be honest, that's fugly:
#Repository
public class StoredProceduresRepository {
#PersistenceContext
EntityManager em;
public String getMyAnswer(String input) {
Query myAnswerGiver = em
.createStoredProcedureQuery("my_answer_giver")
.registerStoredProcedureParameter("input", String.class, ParameterMode.IN)
.setParameter("input", input);
Object result = ((Object[]) myAnswerGiver.getSingleResult())[0];
return (String) result;
}
}
If it is ok for you you can use any Entity you have, in place of this Void. The Entity provided there should not matter.
public interface StoredProceduresRepository extends JpaRepository<SomeUnrelatedEntity, Long> {
#Procedure("my_answer_giver")
String getMyAnswer(#Param("input") String input);
}
I have been using it like this with database views.

Customize a Spring MongoRepository - filter by class

I´ve got several Java documents that are stored in the same collection "app" in mongodb. My intention is use it for the common persistence actions (insert, find, delete...). The problem comes when I try to define repositories for only one of the classes as the repository that I´ve defined will search all the entities, and what I need is a repository where I can call to all the mongorepository standard functions (find, findAll, findby...). My explanation can be hard to understand, this is what I have now:
Base document:
#Document(collection = "app")
#NoRepositoryBean
public abstract class AbstractApplicationDocument {
#Id
public String mongoId;
// more variables, getters, setters...
}
One of the subdocuments (there will be many).
#EqualsAndHashCode(callSuper=true)
public class ClientApplicationDocument extends AbstractApplicationDocument
{
#Id
public String mongoId;
}
Base Repository
#NoRepositoryBean
public interface ApplicationRepository<T, ID extends Serializable> extends MongoRepository<T, ID> {
}
Extended repository (where I want to filter by class)
public interface HttpClientRepository extends ApplicationRepository<HttpClientDocument, String> {
}
Sample of temporary solution that I'd like to avoid if I can reuse the MongoDb utilities
#Component
public class HttpClientRepositoryImpl {
#Autowired
private HttpClientRepository clientRepo;
#Autowired
private MongoTemplate mongo;
public List<HttpClientDocument> findAll() {
Query query = new Query();
query.addCriteria(Criteria.where("_class").is(HttpClientDocument.class.getName()));
mongo.getConverter();
return mongo.find(query, HttpClientDocument.class,"app");
}
}
Relevant information in gradle. I add this because I've seen some solutions that are not valid for me. Probably because they are using different libraries:
compile("org.springframework.boot:spring-boot-starter-data-mongodb:${springBootVersion}")
compile ("org.springframework:spring-context-support:4.1.8.RELEASE");
Is there any simple solution?
You can customize Spring Data repositories in many ways. You can provide custom repository base classes or provide custom implementation classes.
For your question in particular, SimpleMongoRepository does not restrict query on the _class field. You can see below an example for a custom repository base class that restricts the findAll query method to use only the declared entity type.
You would be required to apply that pattern also for other methods which are declared on the MongoRepository level that you want to restrict to the particular class type.
#EnableMongoRepositories(repositoryBaseClass = MyMongoRepository.class)
static class Config {
}
static class MyMongoRepository<T, ID extends Serializable> extends SimpleMongoRepository<T, ID> {
private final MongoEntityInformation<T, ID> metadata;
private final MongoOperations mongoOperations;
public MyMongoRepository(MongoEntityInformation<T, ID> metadata, MongoOperations mongoOperations) {
super(metadata, mongoOperations);
this.metadata = metadata;
this.mongoOperations = mongoOperations;
}
#Override
public List<T> findAll() {
Query query = new Query();
query.restrict(this.metadata.getJavaType());
return this.mongoOperations.find(query, this.metadata.getJavaType(), this.metadata.getCollectionName());
}
}
findAll queries restrict now the class type and queries for a e.g. ModelRepository extends MongoRepository<Model, String> would look like:
{ "_class" : { "$in" : [ "com.example.Model"]}}
Query methods with #Query can be used to pass in the class type (#Query("{'_class': ?0}")) but there's no way to contrain the class type for derived query methods (List<Model> findByFirstnameAndLastname(…)).
There's an open ticket in our Jira related to restricting types of the repository. That particular ticket is related to polymorphic queries but in its essence, it's related to type restrictions on query methods.

Spring get generic type class

I know this question has been asked often but I'm unable to find a solution.
How can I get a generic type class name in a Spring injected repository?
Here it is my base repository
public interface UserRepository extends JpaRepository<User, Long>, IUserRepository<User>{
User findByUsername(String username);
}
this is the interface
public interface IUserRepository<T> {
public List<T> findAllValidEtSiteAndStructure();
}
and finally here it is the implementation
public class UserRepositoryImpl<T> implements IUserRepository<T> {
#PersistenceContext
private EntityManager em;
private Class< T > type;
#Override
public List<T> findAllValidEtSiteAndStructure() {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication instanceof UserAuthentication) {
final User currentUser = ((UserAuthentication) authentication).getDetails();
return (List<T>) em.createQuery("FROM " + type.getName()+ " WHERE site=:site AND structure=:structure AND valid=:valid")
.setParameter("site", currentUser.getInstallation().getSite())
.setParameter("structure", currentUser.getInstallation().getStructure())
.setParameter("valid", true)
.getResultList();
}
return null;
}
}
how can I get type.name?
Thanks in advance
Considering that you're using Spring Framework, use the code snippet bellow, I've tested and it worked just fine:
ResolvableType resolvableType = ResolvableType.forClass(UserRepository.class).as(JpaRepository.class);
System.out.println(resolvableType.getGeneric(0));//User
System.out.println(resolvableType.getGeneric(1));//Long
Basically you can't get the generic type because of type erasure.
What I would do is add an abstract method to UserRepositoryImpl that returns the relevant type:
public abstract Class getType();
And then I would create specific instances for UserRepositoryImpl for which the type is already known at compile time. For example:
public class StudentRepository extends UserRepositoryImpl<Student> {
public Class getType() {
return Student.class;
}
}
The general answer to you question can be seen in the documentation -> http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations in the chapter Custom implementations for Spring Data repositories
But I think that should not be necessary in your case. You should be able to do it in the following way.
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
List<User> findByStructureAndSiteAndValid(Structure structure, Site site, boolean valid);
}

How to extract "find or create" method to abstract class? (Spring Data Jpa)

I'm using Spring Data JPA and I have a bunch of repositories like this one:
public interface CustomerRepository extends JpaRepository<Customer, Long> {}
Under repositories I have services and a lot of them need to have implemented method findOrCreate(String name) like this one:
#Override
#Transactional
public List<Customer> findOrCreate(final String name) {
checkNotNull(name);
List<Customer> result = this.customerRepository.findByName(name);
if (result.isEmpty()) {
LOGGER.info("Cannot find customer. Creating a new customer. [name={}]", name);
Customer customer = new Customer(name);
return Arrays.asList(this.customerRepository.save(customer));
}
return result;
}
I would like to extract method to the abstract class or somewhere to avoid implementing it for each services, testing and so on.
Abstract class can be look like this:
public abstract class AbstractManagementService<T, R extends JpaRepository<T, Serializable>> {
protected List<T> findOrCreate(T entity, R repository) {
checkNotNull(entity);
checkNotNull(repository);
return null;
}
}
And the problem is it due to the fact that I need to find object by name as a string before creating a new one. Of course interface JpaRepository doesn't offer this method.
How can I solve this problem?
Best Regards
Create a custom JpaRepository implementation that includes this behaviour. See this post for an example of writing a custom JpaRepository implementation.

Using generics in Spring Data JPA repositories

I have a number of simple object types that need to be persisted to a database. I am using Spring JPA to manage this persistence. For each object type I need to build the following:
import org.springframework.data.jpa.repository.JpaRepository;
public interface FacilityRepository extends JpaRepository<Facility, Long> {
}
public interface FacilityService {
public Facility create(Facility facility);
}
#Service
public class FacilityServiceImpl implements FacilityService {
#Resource
private FacilityRepository countryRepository;
#Transactional
public Facility create(Facility facility) {
Facility created = facility;
return facilityRepository.save(created);
}
}
It occurred to me that it may be possible to replace the multiple classes for each object type with three generics based classes, thus saving a lot of boilerplate coding. I am not exactly sure how to go about it and in fact if it is a good idea?
First of all, I know we're raising the bar here quite a bit but this is already tremendously less code than you had to write without the help of Spring Data JPA.
Second, I think you don't need the service class in the first place, if all you do is forward a call to the repository. We recommend using services in front of the repositories if you have business logic that needs orchestration of different repositories within a transaction or has other business logic to encapsulate.
Generally speaking, you can of course do something like this:
interface ProductRepository<T extends Product> extends CrudRepository<T, Long> {
#Query("select p from #{#entityName} p where ?1 member of p.categories")
Iterable<T> findByCategory(String category);
Iterable<T> findByName(String name);
}
This will allow you to use the repository on the client side like this:
class MyClient {
#Autowired
public MyClient(ProductRepository<Car> carRepository,
ProductRepository<Wine> wineRepository) { … }
}
and it will work as expected. However there are a few things to notice:
This only works if the domain classes use single table inheritance. The only information about the domain class we can get at bootstrap time is that it will be Product objects. So for methods like findAll() and even findByName(…) the relevant queries will start with select p from Product p where…. This is due to the fact that the reflection lookup will never ever be able to produce Wine or Car unless you create a dedicated repository interface for it to capture the concrete type information.
Generally speaking, we recommend creating repository interfaces per aggregate root. This means you don't have a repo for every domain class per se. Even more important, a 1:1 abstraction of a service over a repository is completely missing the point as well. If you build services, you don't build one for every repository (a monkey could do that, and we're no monkeys, are we? ;). A service is exposing a higher level API, is much more use-case drive and usually orchestrates calls to multiple repositories.
Also, if you build services on top of repositories, you usually want to enforce the clients to use the service instead of the repository (a classical example here is that a service for user management also triggers password generation and encryption, so that by no means it would be a good idea to let developers use the repository directly as they'd effectively work around the encryption). So you usually want to be selective about who can persist which domain objects to not create dependencies all over the place.
Summary
Yes, you can build generic repositories and use them with multiple domain types but there are quite strict technical limitations. Still, from an architectural point of view, the scenario you describe above shouldn't even pop up as this means you're facing a design smell anyway.
This is very possible! I am probably very late to the party. But this will certainly help someone in the future. Here is a complete solution that works like a charm!
Create BaseEntity class for your entities as follows:
#MappedSuperclass
public class AbstractBaseEntity implements Serializable{
#Id #GeneratedValue
private Long id;
#Version
private int version;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
public AbstractBaseEntity() {
this.createdAt = LocalDateTime.now();
this.updatedAt = LocalDateTime.now();
}
// getters and setters
}
Create a generic JPA Repository interface for your DAO persistence as follows:
NB. Remember to put the #NoRepositoryBean so that JPA will not try to find an implementation for the repository!
#NoRepositoryBean
public interface AbstractBaseRepository<T extends AbstractBaseEntity, ID extends Serializable>
extends JpaRepository<T, ID>{
}
Create a Base Service class that uses the above base JPA repository. This is the one that other service interfaces in your domain will simply extend as follows:
public interface AbstractBaseService<T extends AbstractBaseEntity, ID extends Serializable>{
public abstract T save(T entity);
public abstract List<T> findAll(); // you might want a generic Collection if u prefer
public abstract Optional<T> findById(ID entityId);
public abstract T update(T entity);
public abstract T updateById(T entity, ID entityId);
public abstract void delete(T entity);
public abstract void deleteById(ID entityId);
// other methods u might need to be generic
}
Then create an abstract implementation for the base JPA repository & the basic CRUD methods will also be provided their implementations as in the following:
#Service
#Transactional
public abstract class AbstractBaseRepositoryImpl<T extends AbstractBaseEntity, ID extends Serializable>
implements AbstractBaseService<T, ID>{
private AbstractBaseRepository<T, ID> abstractBaseRepository;
#Autowired
public AbstractBaseRepositoryImpl(AbstractBaseRepository<T, ID> abstractBaseRepository) {
this.abstractBaseRepository = abstractBaseRepository;
}
#Override
public T save(T entity) {
return (T) abstractBaseRepository.save(entity);
}
#Override
public List<T> findAll() {
return abstractBaseRepository.findAll();
}
#Override
public Optional<T> findById(ID entityId) {
return abstractBaseRepository.findById(entityId);
}
#Override
public T update(T entity) {
return (T) abstractBaseRepository.save(entity);
}
#Override
public T updateById(T entity, ID entityId) {
Optional<T> optional = abstractBaseRepository.findById(entityId);
if(optional.isPresent()){
return (T) abstractBaseRepository.save(entity);
}else{
return null;
}
}
#Override
public void delete(T entity) {
abstractBaseRepository.delete(entity);
}
#Override
public void deleteById(ID entityId) {
abstractBaseRepository.deleteById(entityId);
}
}
How to use the above abstract entity, service, repository, and implementation:
Example here will be a MyDomain entity. Create a domain entity that extends the AbstractBaseEntity as follows:
NB. ID, createdAt, updatedAt, version, etc will be automatically be included in the MyDomain entity from the AbstractBaseEntity
#Entity
public class MyDomain extends AbstractBaseEntity{
private String attribute1;
private String attribute2;
// getters and setters
}
Then create a repository for the MyDomain entity that extends the AbstractBaseRepository as follows:
#Repository
public interface MyDomainRepository extends AbstractBaseRepository<MyDomain, Long>{
}
Also, Create a service interface for the MyDomain entity as follows:
public interface MyDomainService extends AbstractBaseService<MyDomain, Long>{
}
Then provide an implementation for the MyDomain entity that extends the AbstractBaseRepositoryImpl implementation as follows:
#Service
#Transactional
public class MyDomainServiceImpl extends AbstractBaseRepositoryImpl<MyDomain, Long>
implements MyDomainService{
private MyDomainRepository myDomainRepository;
public MyDomainServiceImpl(MyDomainRepository myDomainRepository) {
super(myDomainRepository);
}
// other specialized methods from the MyDomainService interface
}
Now use your `MyDomainService` service in your controller as follows:
#RestController // or #Controller
#CrossOrigin
#RequestMapping(value = "/")
public class MyDomainController {
private final MyDomainService myDomainService;
#Autowired
public MyDomainController(MyDomainService myDomainService) {
this.myDomainService = myDomainService;
}
#GetMapping
public List<MyDomain> getMyDomains(){
return myDomainService.findAll();
}
// other controller methods
}
NB. Make sure that the AbstractBaseRepository is annotated with #NoRepositoryBean so that JPA does not try to find an implementation for the bean.
Also the AbstractBaseServiceImpl must be marked abstract, otherwise JPA will try to autowire all the children daos of the AbstractBaseRepository in the constructor of the class leading to a NoUniqueBeanDefinitionException since more than 1 daos (repository) will be injected when the bean is created!
Now your service, repository, and implementations are more reusable. We all hate boilerplate!
Hope this helps someone.
I am working a project to create the generic repository for cassandra with spring data.
Firstly create a repository interface with code.
StringBuilder sourceCode = new StringBuilder();
sourceCode.append("import org.springframework.boot.autoconfigure.security.SecurityProperties.User;\n");
sourceCode.append("import org.springframework.data.cassandra.repository.AllowFiltering;\n");
sourceCode.append("import org.springframework.data.cassandra.repository.Query;\n");
sourceCode.append("import org.springframework.data.repository.CrudRepository;\n");
sourceCode.append("\n");
sourceCode.append("public interface TestRepository extends CrudRepository<Entity, Long> {\n");
sourceCode.append("}");
Compile the code and get the class, I use org.mdkt.compiler.InMemoryJavaCompiler
ClassLoader classLoader = org.springframework.util.ClassUtils.getDefaultClassLoader();
compiler = InMemoryJavaCompiler.newInstance();
compiler.useParentClassLoader(classLoader);
Class<?> testRepository = compiler.compile("TestRepository", sourceCode.toString());
And initialize the repository in spring data runtime. This is a little tricky as I debug the SpringData code to find how it initialize a repository interface in spring.
CassandraSessionFactoryBean bean = context.getBean(CassandraSessionFactoryBean.class);
RepositoryFragments repositoryFragmentsToUse = (RepositoryFragments) Optional.empty().orElseGet(RepositoryFragments::empty);
CassandraRepositoryFactory factory = new CassandraRepositoryFactory(
new CassandraAdminTemplate(bean.getObject(), bean.getConverter()));
factory.setBeanClassLoader(compiler.getClassloader());
Object repository = factory.getRepository(testRepository, repositoryFragmentsToUse);
Now you can try the save method of the repository and you can try other methods such as findById.
Method method = repository.getClass().getMethod("save", paramTypes);
T obj = (T) method.invoke(repository, params.toArray());
A full sample code and implementation I have put in this repo
https://github.com/maye-msft/generic-repository-springdata.
You can extend it to JPA with the similar logic.

Categories