I try to use inheritance with Ebean in Play! Framework 2.1.0. The inheritance strategy is "single table", as it is the only one supported by Ebean. I closely follow example from JPA Wikibook
#Entity
#Inheritance
#DiscriminatorColumn(name="price_type")
#Table(name="prices")
public abstract class Price {
#Id
public long id;
// Price value
#Column(precision=2, scale=18)
public BigDecimal value;
}
#Entity
#DiscriminatorValue("F")
public class FixedPrice extends Price {
// NO id field here
...
}
#Entity
#DiscriminatorValue("V")
public class VariablePrice extends Price {
// NO id field here
...
}
This code passes compilation, but I get
RuntimeException: Abstract class with no readMethod for models.Price.id
com.avaje.ebeaninternal.server.deploy.ReflectGetter.create(ReflectGetter.java:33)
com.avaje.ebeaninternal.server.deploy.BeanDescriptorManager.setBeanReflect(BeanDescriptorManager.java:1353)
com.avaje.ebeaninternal.server.deploy.BeanDescriptorManager.createByteCode(BeanDescriptorManager.java:1142)
com.avaje.ebeaninternal.server.deploy.BeanDescriptorManager.readDeployAssociations(BeanDescriptorManager.java:1058)
com.avaje.ebeaninternal.server.deploy.BeanDescriptorManager.readEntityDeploymentAssociations(BeanDescriptorManager.java:565)
com.avaje.ebeaninternal.server.deploy.BeanDescriptorManager.deploy(BeanDescriptorManager.java:252)
com.avaje.ebeaninternal.server.core.InternalConfiguration.<init>(InternalConfiguration.java:124)
com.avaje.ebeaninternal.server.core.DefaultServerFactory.createServer(DefaultServerFactory.java:210)
com.avaje.ebeaninternal.server.core.DefaultServerFactory.createServer(DefaultServerFactory.java:64)
com.avaje.ebean.EbeanServerFactory.create(EbeanServerFactory.java:59)
play.db.ebean.EbeanPlugin.onStart(EbeanPlugin.java:79)
Google search brings only one relevant link which is source code of ReflectGetter.java. The comment there says
For abstract classes that hold the id property we need to use reflection to get the id values some times.
This provides the BeanReflectGetter objects to do that.
If I drop abstract keyword from superclass declaration, exception disappears. I would really prefer not to make superclass concrete though.
Add getter/setter for your id field and it will go away.
Related
PROBLEM: I have read-only data in a table. Its rows have no id - only composite key define its identity. I want it as a Value Object (in DDD terms) in my app.
RESEARCH: But if I put an #Embeddable annotation instead of #Entity with #Id id field, then javax.persistence.metamodel doesn't see it and says Not an embeddable on Metamodel metamodel.embeddable(MyClass.class);. I could wrap it with an #Entity class and autogenerate id, but this is not what I architectually intended to achieve.
QUESTION: Is JPA Embeddable a Value Object? Can Embeddable exist without a parent Entity and represent a Table?
There are many articles on the topic that show this is a real JPA inconvenience:
http://thepaulrayner.com/persisting-value-objects/
https://www.baeldung.com/spring-persisting-ddd-aggregates
https://paucls.wordpress.com/2017/03/04/ddd-building-blocks-value-objects/
https://medium.com/#benoit.averty/domain-driven-design-storing-value-objects-in-a-spring-application-with-a-relational-database-e7a7b555a0e4
Most of them suggest solutions based on normalised relational database, with a header-entity as one table and its value-objects as other separate tables.
My frustration was augmented with the necessity to integrate with a non-normalized read-only table. The table had no id field and meant to store object-values. No bindings with a header-entity table. To map it with JPA was a problem, because only entities with id are mapped.
The solution was to wrap MyValueObject class with MyEntity class, making MyValueObject its composite key:
#Data
#Entity
#Table(schema = "my_schema", name = "my_table")
public class MyEntity {
#EmbeddedId MyValueObject valueObject;
}
As a slight hack, to bypass JPA requirements for default empty constructor and not to break the immutability of Value Object, we add it as private and sacrifice final modifier for fields. Privacy and absence of setters conforms the initial DDD idea of Value Object:
// #Value // Can't use, unfortunately.
#Embeddable
#Immutable
#AllArgsConstructor
#Getter
#NoArgsConstructor(staticName = "private") // Makes MyValueObject() private.
public class MyValueObject implements Serializable {
#Column(name = "field_one")
private String myString;
#Column(name = "field_two")
private Double myDouble;
#Transient private Double notNeeded;
}
Also there is a handful Lombok's #Value annotaion to configure value objects.
I would like to make a method that accept any type of javax.persistence.Entity object.
I tried this.
The Generic Method
import javax.persistence.Entity;
public <T extend Entity> void GenericMethod(T entity) {...}
The Entity Used For Test
#Entity
public class EntityObject {...}
The Test
GenericMethod(new EntityObject());
I am having an error at compilation, The method GenericMethod(T) in the type ... is not applicable for the arguments (EntityObject).
How do you limit the method to only accept object with the #Entity annotaion ???
Short answer is that you can't do this. At least not as a compile time check. T extend Entity would only work if Entity would be an interface or a class; in your case it's an annotation and this is forbidden by the JLS.
The only way to do it would be via a runtime check, something like this:
private static void test(EntityObject entityObject) {
Annotation [] all = entityObject.getClass().getAnnotations();
// filter on the ones you care
}
But this would only work at runtime, of course.
I have an entity:
#Entity
public class Test {
#Embedded
Content content;
// getters setters..
}
This contains an embedded class as you can see:
#Embeddable
public class Content {
#OneToOne
Person person;
#Embedded
Language language;
// getters setters..
}
This contains again an embeddable. 2 times nested embeddable
#Embeddable
public class Language {
String format;
#OneToOne
IdentifierCode identifierCode;
// getters setters..
}
When using the automatic schema generation feature of JPA all columns are generated in the correct way.
I use the #Data annotation on each #Entity and #Embeddable to generate getters, setters, constructors, etc..
When starting the application server (EAP 7), I notice this warning in the logs:
HHH015011: Unable to locate static metamodel field :
org.package.Language_#identifierCode; this may or may not indicate a
problem with the static metamodel
Indeed, when opening the metamodel class Language_; no identifierCode column reference is present:
#Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
#StaticMetamodel(Language.class)
public abstract class Language_ {
public static volatile SingularAttribute<Language, String> format;
}
I don't see what I'm doing wroing. Is it not possible to use #OneToOne in a nested #Embeddable? The metamodel Content_ correctly generates the singular attribute for person!
It seems when using multiple nested embeddables, something goes wrong. When using only one level of embeddables, it works.
I tried other stuff:
Adding Access.Field on the class. Nothing happens.
Instantiation the #Embedded class, like #Embedded Language language = new Language(). Nothing happens.
Replaced the #OneToOne with #ManyToOne. Nothing happens.
This sounds like a bug in your JPA provider, which you should report to them.
The JPA provider I use (DataNucleus) creates a
public static volatile SingularAttribute<Language, mydomain.model.IdentifierCode> identifierCode;
One option you have is to just use the datanucleus-jpa-query.jar in your CLASSPATH to generate the static metamodel and use those generated classes with your existing provider, alternatively use it for persistence too.
Say I have a #MappedSuperClass like this:
#MappedSuperclass
public abstract class Rating
{
#Id
private Long id;
#Column(name="USER_ID")
private Long userId;
private int rating;
...
With a concrete child entity like this
#Entity
#Table(name="ACTIVITY_RATING")
public class ActivityRating extends Rating
{
private Long activitySpecificData;
...
Then there is a Spring Data JPA repository like this:
#NoRepositoryBean
public interface RatingRepository<R extends Rating> extends JpaRepository<R, ID>
{
public List<R> findByUserId(Long userId);
...
and this:
public interface ActivityRatingRepository extends RatingRepository<ActivityRating>
{
}
This all works great and I can call findByUserId() on any of specific rating repositories that extend RatingRepository. I am now wanting to write some JPQL in the RatingRepository that all the child interfaces can inherit. I just don't know what (or if it's even possible) to put after the FROM in the query. For example:
#Query("SELECT NEW com.foo.RatingCountVo(e.rating, COUNT(e.rating)) FROM ??????? e GROUP BY e.rating")
public List<RatingCountVo> getRatingCounts();
I can add this method to each of the individual repositories that extend RatingRepository but everything would be exactly the same except for the specific entity name. If I want to change the query, I'd then have to go to all the child repositories and update them individually. I really want the query to live in the parent class and not be duplicated. Is there any way to accomplish this?
I'm currently using spring-data-jpa 1.7.2 and eclipselink 2.5.2. I'm not necessarily opposed to switching to newer versions if necessary.
Will it work if you will split query into 3 parts: start, entity and end of query? Than, if it'll work, in each interface you define constant like
String ENTITY = "ActivityRating";
And then you can use it like
#Query(RatingRepository.QUERY_START + ENTITY + RatingRepository.QUERY_END)
List<RatingCountVo> getRatingCounts();
BTW, there is no need to define public modifier in interface.
UPDATE: here is described another way:
#Query("SELECT NEW com.foo.RatingCountVo(e.rating, COUNT(e.rating)) FROM #{#entityName} e GROUP BY e.rating
I tried to achieve Generation Gap Pattern with JPA entities.
Here is the solution we choose ( <-- are inheritance)
BaseEntity <-- EntityGenerated <-- Entity
The EntityGenerated type is abstract and mapped with #MappedSuperclass, all field are generated with correct mapping annotation, relation point to the concrete subclass, not the Generated one.
The Entity is a concrete type, generated only if the class doesn't exist, initially there is just the class declaration annotated with #Entity. Other mapping attributes such as the #Table, etc are in a generated orm.xml.
Now, when we generate the jpa static metamodel (using hibernate or openjpa metamodel generator), the generated classes look like :
public class BaseEntity_ {
public static volatile SingularAttribute<PersistentDomainObject,Long> id;
public static volatile SingularAttribute<PersistentDomainObject,Long> timeStamp;
}
public class UserGenerated_ extends BaseEntity_ {
public static volatile SetAttribute<UserGenerated,Group> groups;
}
public class User_ extends UserGenerated_ {
}
If I want to use User_ in a jpa criteria query, I'll do something like :
CriteriaQuery<User> query = criteriaBuilder.createQuery(User.class);
Root<User> root = query.from(User.class);
query.where(root.get(User_.groups).in(paramGroups));
But It won't compile.... User_.groups is of type SetAttribute and the jpa path api for the get method is :
<E, C extends java.util.Collection<E>> Expression<C> get(PluralAttribute<X, C, E> collection);
(In comparaison, the get method for the singular attribute is
<Y> Path<Y> get(SingularAttribute<? super X, Y> attribute)
witch work better)
So, now, the questions are :
Why the metamodel generators generate the class for MappedSuperclass as there is no way to query it directly ?, attribute and relations for superclass should be defined in each subclass (where X is of subclass type)
Why the jpa criteria Path api doesn't define the get method for plural attribut as
get(PluralAttribute<? super X, C, E> collection)
?
How can I achieve the Generation Gap Pattern on JPA entity without giving up criteria query ?
Thanks