I need to have a List of clasess that are Persistence Entities, I need have Entity Information, using Reflection API of JPA
I have the EntityManager, But I do not know if that is the way.
I want to do a generic logging for my Entities using a EntityListener. That works well, but I do not have the way to register the listener to all my entities.
Use the JPA2 MetaModel? It has assorted methods to see the entities (or managed types).
Set<javax.persistence.metamodel.EntityType<?>> entityTypes = entityManagerFactory.getMetamodel().getEntities();
for (javax.persistence.metamodel.EntityType entityType : entityTypes){
logger.info(entityType.getName());
logger.info(entityType.getJavaType().getCanonicalName());
logger.info("******************************");
}
Take a look at Configuration#getClassMappings()
Returns: Iterator of the entity mappings currently contained in the configuration.
Related
I have models with nested entity inside them. Is it necessary to write annotation #Embedded and #Embedeable or it's not necessary in actual Spring version?
Yes you still need to use these in Spring, since these are JPA annotations and are necessary when you are embedding a given type within another entity.
I am working for now with JPA/Static metamodel and appeared to me a doubt.
Is there any many manner to verify on an SingularAttribute/PluralAttribute if the relation is required (e.g. the annotation OneToOne, OneToMany, ManyToOne was annotated with optional=false).
for example
i have this
#OneToOne (optional=false,mappedBy = "recordingIsrc")
public Recording<?> recording;
I tried to check on API, but always the only alternative is go back to the annotation to check the attribute, but this seems to be a workaround instead to be a model verification.
Kind Regards,
This information is not contained in the MetaModel API.
The meta model is not created for your purpose. It's just there for making Criteria API type safe.
I have an entity holding a collection (#OneToMany) which loads lazily. So far so good. If I load the entire list of entity objects (findAll()) I don't want the collection loaded at all. I don't access the collection therefore I assumed it will not be loaded before returning it from a REST endpoint, but it seems like Jackson accesses it when parsing it into JSON.
Currently I iterate over the entire entity list and set the collection to NULL. This seems like a very poor way of doing it, is there a way to ONLY manually load the collection with a specially prepared #Query and not load it automatically (either LAZY no EAGER) at all? Are #JsonViews the correct way to go or should I remove the #OneToMany annotation (I guess then I lose the mapping for the queries that actually do load the collection)? Any other suggestions?
Examplecode
#Entity
#Entity
public class Entity {
#OneToMany(targetEntity = Child.class)
private List<Child> children;
}
Jersey Resource
#GET
#Produces({MediaType.APPLICATION_JSON})
public List<Entity> getAllEntities() {
List<Entity> entities = entityService.findAll();
entities.forEach(e-> e.setChildren(null));
return entities ;
}
Repository = JpaRepository with default findAll() implementation.
thanks
Since you mentioned 'suggestion', I faced the same problem myself and I decided to implement custom DTOs to be sent in the API response. So I ommitted these collection fields and all other I did not want the json processors to touch.
I did implement my set of DTOs mirroring actual persisted entities, but there might be some other mappers to do the job
A few time ago, I asked a question about designing model classes for a REST API. There might be some information there useful for you.
Instead of reusing the same model classes for persistence and for the REST API, I've realized the best approach was creating different models. In some situations you don't want the persistence model to be the same as the model you use in your API. So, defining different models is the way to go.
And I chose MapStruct to map from one model to other.
I'd like to wrap/unwrap my Entity each time it's loaded or persisted. I got to know that I cannot do it using JPA listeners since they can only perform an action on the object and not swap it with the other. The natural solution would be to use an Aspect. But are there particular methods that I can pointcut? The thing is that the entity to be wrapped/unwrapped can be a field of another entity...
EDIT:
I found out that you cannot do this using Spring AOP because EntityManager is not spring-managed (why?) - see here. To make it work I would have to define EntityManager bean explicitely but it is not recommended in that post - again, why? How to do that anyway? On the other hand why does they state that created EntityManager is application-managed? See spring API documentation
Try to pointcut the getters and setter that use the entity class. Methods that retrieve entities from EntityManager, best way to achieve this is create new annotation and put over all the methods that could retrieve a instance for that class, then use the #annotation support pointcut:
#annotation - limits matching to join points where the subject of the
join point (method being executed in Spring AOP) has the given
annotation
Also to obtain the modifying entity you could do something like this.
Get method arguments using spring aop?
Sometimes you need access in the advice body to the actual value that was returned. You can use the form of #AfterReturning that binds the return value
For a project I am working on, I need to persist a number of POJOs to a database. The POJOs class definitions are sometimes highly nested, but they should flatten okay, as the nesting is tree-like and contains no cycles (and the base elements are eventually primitives/Strings). It is preferred that the solution used create one table per data type and that the tables will have one field per primitive member in the POJO. Subclassing and similar problems are not issues for this particular project.
Does anybody know of any existing solutions that can:
Automatically generate a CREATE TABLE definition from the class definition
Automatically generate a query to persist an object to the database, given an instance of the object
Automatically generate a query to retrieve an object from the database and return it as a POJO, given a key.
Solutions that can do this with minimum modifications/annotions to the class files and minimum external configuration are preferred.
Example:
Java classes
//Class to be persisted
class TypeA {
String guid;
long timestamp;
TypeB data1;
TypeC data2;
}
class TypeB {
int id;
int someData;
}
class TypeC {
int id;
int otherData;
}
Could map to
CREATE TABLE TypeA (
guid CHAR(255),
timestamp BIGINT,
data1_id INT,
data1_someData INT,
data2_id INt,
data2_otherData INT
);
Or something similar.
I would use the standardized Java Persistence API (JPA), preferably with annotations. Regarding your requirements:
This is not required by the specification but most JPA providers (all major implementations do) support DDL generation from the mapping metadata.
EntityManager#persist(Object entity) does that.
<T> T EntityManager#find(Class<T> entityClass, Object primaryKey) does that.
As hinted, JPA is an API, you need an implementation to use it. My preference goes to Hibernate Entity Manager or EclipseLink (see this previous question).
Hibernate can help you solve all the three problems you listed.
(1) You need to annotate your entity classes so Hibernate is able to map between classes/objects to tables/rows. Hibernate uses a convention over configuration approach so it is possible to use just a few annotations and have a complete o/r mapping ready for use. You could use the hibernate.hbm2ddl.auto configuration option to instruct Hibernate to automatically validate/export and schema DDL when the session factory is first created.
(2) / (3) Hibernate has enough information about classes, database schema and mappings to allow it generate SQL statements for simple CRUD operations with minimal effort. You can fine tune how Hibernate loads and persists a tree of objects. Association mapping annotations have the fetch and cascade options that let you specify how associated objects are fetched (lazy / eager) and how operations are propagated through the object tree. Please refer to the Hibernate documentations for the details about these options.
If you are new to Hibernate, I recommend the good Hibernate documentation as reference and the book Java Persistence with Hibernate for the deeper understanding about the framework (it has very good sections about fetching and cascading).
In a typical scenario, Hibernate requires just a bit of configuration (one hibernate.cfg.xml file). You can define the mappings using XML files (no good) or annotations (the "default" option for new projects).
You tagged your question as Hibernate. Have you tried using Hibernate for this?
As long as you define well how collections should be mapped (e.g., one-to-many), I've found it generally very effective for this kind of thing.
The Hibernate tutorials provide a lot of examples for situations that are similar to the code you provided.
A highly recommended framework is JPersist, an extremely simple Database-to-POJO framework. No XML or annotations needed. I use it it my project because if I want a new table object, I simply create a bean.
The issue though in your situation is your wanting something to setup the database for you. Doing that would be very hard and your asking alot from a framework. With JPersist, you should be able to create a db table from class name and columns from fields, and then use phpMyAdmin's designer to resolve references.
5 min of reading the documentation for JPersist now will save hours in development time later.
JPA provides sufficient options to do this. For example you can use #Embeddable and #Embedded:
#Embeddable
class TypeB {
int id;
int someData;
}
class TypeA {
....
#Embedded
TypeB data1;
}
You can either manually create the underlying schema, or let something like hbm2ddl.auto=update to create it for you.