Reputation: 31
I have started with JPA and I have question about why we need to annotate the class with @Entity
. The only reason why I could think of doing it was that auto-generating tools can see that it is an entity an then if wanted make a corresponding table in the database.
public class Book {
//Fields
}
vs.
@Entity
public class Book {
//Fields
}
I know the first code-snippet will throw an exception if I try to persist etc with entitymanager....but I wonder why we make add @Entity
in the first place.
Upvotes: 3
Views: 1526
Reputation: 10700
From the Java Persistence API FAQ:
The Java Persistence API is a POJO persistence API for object/relational mapping. It contains a full object/relational mapping specification supporting the use of Java language metadata annotations and/or XML descriptors to define the mapping between Java objects and a relational database.
Having a @Entity
annotation is all about adding metadata (configuration) to a Pojo. A different approach would be let it implement a certain interface and/or xml configuration. But annotations are much closer at the actual code and can be checked by the Java compiler.
You can read more about this here: The Java Persistence API - A Simpler Programming Model for Entity Persistence.
Upvotes: 3
Reputation: 6969
I think John is asking this because we are annotating the POJO with other annotation apart from the @Entity (@Id etc). The thing is if the class is annotated the JPA implementation can check and then go into the class to get the rest of the mapping, instead of going through all the classes in a project to try to scan for metadata that doesn't exist.
This is just my idea, I may or may not be correct so... :-D
Upvotes: 0
Reputation: 15577
The JPA implementation needs to know which classes are to be persisted/persistable (as per the JPA spec). But then you don't have to annotate anything ... you could use orm.xml to define what is persistable.
Upvotes: 3