Multiple ManyToMany relationships using "mappedBy" with Super class member - java

I am developing an application using Hibernate and am trying to model the following scenario:
I have an Activity Abstract class, defined as follows:
#Entity
#Inheritance(strategy=InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name="activityType")
#Table(name = "BF_ACTIVITY")
public abstract class Activity extends PersistableObject {
#ManyToOne
#JoinColumn(name = "ASSIGNED_TO")
protected Contactable assignedTo;
#ManyToOne
#JoinColumn(name = "RAISED_BY")
protected Contactable raisedBy;
Note I am using Single Table inheritance (so all implementing objects will use the same table) and have set a DiscriminatorColumn.
Now I have two objects that extend Activity: ToDo and Status:
#Entity
#Table(name = "BF_TODO")
#DiscriminatorValue("Todo")
public class ToDo extends Activity {
...
#Entity
#Table(name = "BF_STATUS")
#DiscriminatorValue("Status")
public class Status extends Activity {
...
Again note that for both implementations i have set a DiscriminatorValue.
Finally, I want to have a Person object, and the person can have a list of Status and a list of ToDo - I also want to capture the bi-directional relationship, so am modelling it using the mappedBy configuration, but in both cases using the "raisedBy" field that exists in the super class "Activity":
public abstract class Person {
#ManyToMany(mappedBy="raisedBy", targetEntity=Activity.class)
private List<ToDo> todoItems = new ArrayList<ToDo>();
As i am using mappedBy with the member variable "raisedBy" from the super class I have also specified the targetEntity (otherwise it is not able to find the field in the ToDo object).
The problem is when I try to call getTodoItems() - it is actually just returning all "Activity" objects linked by "raisedBy" to the current person. e.g. it throws a cast exception because it is expecting the list of ToDos but Hibernate is returning Status objects in the list as well.
I was hoping the mappedBy config along with DiscriminatorValue would be enough to make this work - has anyone come across this or resolved it?
Thanks
EDIT
I have just found this post:
Can someone point me in the direction of a good #Where overview and example? could I just update my person as follows to use #Where with the discriminator column?
public abstract class Person {
#ManyToMany(mappedBy="raisedBy", targetEntity=Activity.class)
#Where(clause="activityType=Todo")
private List<ToDo> todoItems = new ArrayList<ToDo>();

Add the annotation :
#Where(clause = "activityType= 'Todo'")
But it's a hibernate annotation, not JPA

Related

Spring-Data Jpa Inheritance: Keeping Entity Id's in Children Entity

I'm dealing with a couple of Entities with Tree like structures that were getting more complicated so I decided to create an abstract class for it so code was a bit more mainainable:
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class TreeStructure<T extends TreeStructure>
{
#ManyToOne
protected T parent;
#OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
protected Set<T> children = new HashSet<>();
//...
Then I have two Entities which extend it:
#Entity(name = "TreeStructureOne")
public class TreeStructureOne extends TreeStructure<TreeStructureOne>
{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#JsonProperty("TreeStructureOne_id")
private long id;
And I basically want the database to be completely unaware of this TreeStructure abstraction and save all of the fields in each Entities tableand expected InheritanceType.TABLE_PER_CLASS to deal with that. But it seems I need to define the Id in the TreeStructure Entity at least or I get:
Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: TreeStructure
And I don't want to add an ID into the abstract class since this makes three tables in the database called: HT_TREE_STRUCTURE, HT_TREE_STRUCTURE_ONE and HT_TREE_STRUCTURE_TWO with one field ID each one.
Is there any solution to that?
Since TreeStructure is not an #Entity use only #MappedSuperclass
#MappedSuperclass
public abstract class TreeStructure<T extends TreeStructure> {
instead of #Entity and #Inheritance for the parent class.
You can find #MappedSuperclass in the Oracle JEE API documentation.

#AssociationOverride does not create #JoinColumn from scratch

I have a group of tables, that are all identical apart from their owner table, and the corresponding foreign keys to that table. I made it all generic thanks to Hibernate/JPA, but cannot pass the #JoinColumn information via #AssociationOverride since the name value for it is ignored, or not overridden at all.
For example;
#Data
#Entity
#Table(name = "etc")
#AssociationOverride(name = "parent", joinColumns = #JoinColumn(name = "id"))
public class RealEntity extends BaseEntity<ParentEntity, String> {
}
with;
#Data
#MappedSuperClass
public class BaseEntity<K, P> implements Serializable {
#EmbeddedId
protected Key<K> key = new Key<>();
#MapsId("fk")
#ManyToOne
#JsonBackReference
protected P parent;
#Data
#Embeddable
public static class Key<K> implements Serializable {
protected K fk;
#Column(name = "sub_id")
protected String subId;
}
}
parent:
#Data
#Entity
#Table(name = "parentc")
public class ParentEntity implements Serializable {
#Column(name = "id")
protected String parentId;
}
So as you see, it works well except for the parent's fk reference definition, I get mapping error since Hibernate tries to find a parent_id, rather than just id for the foreignKey, since #JoinColumn override is ignored. It works if I put the parent information in the RealEntity directly (obviously), or if I put #JoinColumn(name = "id") on parent in BaseEntity but I want to keep it as generic as possible. Is there any solution to this issue? Or should I just give up?
edit: it seems when I put a proper #JoinColumn with acceptable mapping for joining on parent in BaseEntity, that does get overridden, so it needs something valid to override. I cannot just add an association from nothingness is that the case? I've seen many examples on the web where they were putting associations from scratch, my usage of #MapsId, might be breaking the usage I guess. But I cannot change my current structure, since it is necessary to be able to represent composite foreign key definition for dependent child tables... I feel like there is a very simple solution, or some hacky way to achieve what I want, and I cannot seem to find it!

JPA OneToMany Association from superClass

I’m trying to map the inheritance from the superclass LendingLine and the subclasses Line and BlockLine. LendingLine has an ManyToOne association with Lending.
When I try to get the LendingLines from the database without the inheritance it works fine. The association works also. But when i add the inheritance, lendingLines in Lending is empty. I also can't get any LendingLines from the DB with the inheritance.
Can anybody help me?
(Sorry for the bad explanation)
Thanks in advance!
LendingLine:
#Entity
#Inheritance(strategy=InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name="TYPE")
#DiscriminatorValue(value="Line")
#Table(name = "LendingLine")
public class LendingLine {
...
public LendingLine(){}
#ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER, targetEntity=Lending.class)
#JoinColumn(name = "LendingId")
private Lending lending;
...
Lending:
#Entity
#Table(name = "Lending")
public class Lending {
...
public Lending(){}
#OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER, mappedBy = "lending")
private List<LendingLine> lendingLines;
...
BlockDate:
#Entity
#DiscriminatorValue(value = "BlockLine")
public class BlockLine extends LendingLine {
public BlockLine(){
}
}
LendingLineRepository:
This class only reads from the db because the db was created by another application ( C#) where the objects are added to the db.
public class LendingLineRepository extends JpaUtil implement LendingLineRepositoryInterface {
#Override
protected Class getEntity() {
return LendingLine.class;
}
#Override
public Collection<LendingLine> findAll() {
Query query = getEm().createQuery("SELECT l FROM LendingLine l");
System.out.println(query.getResultList().size());
return (Collection<LendingLine>) query.getResultList();
}
Table LendingLine:
Choose your type of superclass according to your needs:
Concrete Class
public class SomeClass {}
Define your superclass as a concrete class, when you want to query it and when you use a new operator for further logic. You will always be able to persist it directly. In the discriminator column this entity has it's own name. When querying it, it returns just instances of itself and no subclasses.
Abstract Class
public abstract class SomeClass {}
Define your superclass as an abstract class when you want to query it, but don't actually use a new operator, because all logic handled is done by it's subclasses. Those classes are usually persisted by its subclasses but can still be persisted directly. U can predefine abstract methods which any subclass will have to implement (almost like an interface). In the discriminator column this entity won't have a name. When querying it, it returns itself with all subclasses, but without the additional defined information of those.
MappedSuperclass
#MappedSuperclass
public abstract class SomeClass {}
A superclass with the interface #MappedSuperclass cannot be queried. It provides predefined logic to all it's subclasses. This acts just like an interface. You won't be able to persist a mapped superclass.
For further information: JavaEE 7 - Entity Inheritance Tutorial
Original message
Your SuperClass LendingLine needs to define a #DiscriminatorValue as well, since it can be instantiated and u use an existing db-sheme, where this should be defined.

org.hibernate.WrongClassException on saving an entity via Hibernate

In this question I am working with Hibernate 4.3.4.Final and Spring ORM 4.1.2.RELEASE.
I have an User class, that holds a Set of CardInstances like this:
#Entity
#Table
public class User implements UserDetails {
protected List<CardInstance> cards;
#ManyToMany
public List<CardInstance> getCards() {
return cards;
}
// setter and other members/methods omitted
}
#Table
#Entity
#Inheritance
#DiscriminatorColumn(name = "card_type", discriminatorType = DiscriminatorType.STRING)
public abstract class CardInstance<T extends Card> {
private T card;
#ManyToOne
public T getCard() {
return card;
}
}
#Table
#Entity
#Inheritance
#DiscriminatorOptions(force = true)
#DiscriminatorColumn(name = "card_type", discriminatorType = DiscriminatorType.STRING)
public abstract class Card {
// nothing interesting here
}
I have several types of cards, each extending the Card base class and the CardInstance base class respectivly like this:
#Entity
#DiscriminatorValue("unit")
public class UnitCardInstance extends CardInstance<UnitCard> {
// all types of CardInstances extend only the CardInstance<T> class
}
#Entity
#DiscriminatorValue("leader")
public class LeaderCardInstance extends CardInstance<LeaderCard> {
}
#Entity
#DiscriminatorValue("unit")
public class UnitCard extends Card {
}
#Entity
#DiscriminatorValue("leader")
public class LeaderCard extends AbilityCard {
}
#Entity
#DiscriminatorValue("hero")
public class HeroCard extends UnitCard {
// card classes (you could call them the definitions of cards) can
// extend other types of cards, not only the base class
}
#Entity
#DiscriminatorValue("ability")
public class AbilityCard extends Card {
}
If I add a UnitCardInstance or a HeroCardInstance to the cards collection and save the entity everything works fine.
But if I add a AbilityCardInstance to the collection and save the entity it fails with a org.hibernate.WrongClassException. I added the exact exception + message at the bottom of the post.
I read through some questions, and lazy loading seems to be a problem while working with collections of a base class, so here is how I load the User entity before adding the card and saving it:
User user = this.entityManager.createQuery("FROM User u " +
"WHERE u.id = ?1", User.class)
.setParameter(1, id)
.getSingleResult();
Hibernate.initialize(user.getCards());
return user;
The database entries for "cards"
The database entries for "cardinstances"
org.hibernate.WrongClassException: Object [id=1] was not of the specified subclass [org.gwentonline.model.cards.UnitCard] : Discriminator: leader
Thanks in advance for any clues how to fix this problem. If you need additional information I will gladly update my question!
According to the first paragraph of the JavaDocs for #ManyToOne:
It is not normally necessary to specify the target entity explicitly since it can usually be inferred from the type of the object being referenced.
However, in this case, #ManyToOne is on a field whose type is generic and generic type information gets erased at the type of compilation. Therefore, when deserializing, Hibernate does not know the exact type of the field.
The fix is to add targetEntity=Card.class to #ManyToOne. Since Card is abstract and has #Inheritance and #DiscriminatorColumn annotations, this forces Hibernate to resolve the actual field type by all possible means. It uses the discriminator value of the Card table to do this and generates the correct class instance. Plus, type safety is retained in the Java code.
So, in general, whenever there is the chance of a field's type not being known fully at runtime, use targetEntity with #ManyToOne and #OneToMany.
I solved the problem.
The root cause lies in this design:
#Table
#Entity
#Inheritance
#DiscriminatorColumn(name = "card_type", discriminatorType = DiscriminatorType.STRING)
public class CardInstance<T extends Card> {
protected T card;
}
#Entity
#DiscriminatorValue("leader")
public class LeaderCardInstance extends CardInstance<LeaderCard> {
}
At runtime information about generic types of an class are not present in java. Refer to this question for further information: Java generics - type erasure - when and what happens
This means hibernate has no way of determining the actual type of the CardInstance class.
The solution to this is simply getting rid of the generic type and all extending (implementing) classes and just use one class like this:
#Table
#Entity
#Inheritance
#DiscriminatorColumn(name = "card_type", discriminatorType = DiscriminatorType.STRING)
public class CardInstance {
Card card;
}
This is possible (and by the way the better design) because the member card carries all the information about the card type.
I hope this helps folk if they run into the same problem.

hibernate collections with inheritance

My case is a form, with categories, questions, answers... A form has different categories, each of one have different questions and this questions one or more possible answers.
In my imnplementation of java, I hava an object called TreeObject that implements all relationship between elements (and other common properties as creation date...). This object has a list of childs and a parent to follow the hierarchy of the form. Then, Category, Form and other elements extends this class and add some extra functionality.
The database will be a table with all common data (tree object) and childs and parent relationship, and some other tables (forms, categories, ...) with specific data for each one. For this I use InheritanceType.JOINED
The code of the Tree Object class (UPDATED to include #kostja comments):
#Entity
#Table(name = "TREE_OBJECTS")
#Inheritance(strategy = InheritanceType.JOINED)
public abstract class TreeObject implements ITreeObject {
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
#Column(name = "ID", unique = true, nullable = false)
private Long id;
#OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
#JoinTable(name = "CHILDRENS_RELATIONSHIP")
private List<TreeObject> children;
#ManyToOne(fetch = FetchType.EAGER)
private TreeObject parent;
//More parameters, getters and setters.
}
For example the Form class is:
#Entity
#Table(name = "FORMS")
public class Form extends TreeObject {
private String name;
//setters, getters and other stuff.
}
And the DAO has this method (I am using generics for simplifying the code but the code can be read):
public T makePersistent(T entity) {
setCreationInfo(entity);
setUpdateInfo(entity);
Session session = getSessionFactory().getCurrentSession();
session.beginTransaction();
try {
session.saveOrUpdate(entity);
session.flush();
session.getTransaction().commit();
return entity;
} catch (RuntimeException e) {
session.getTransaction().rollback();
throw e;
}
}
Category, Questions and other elements are very similar to the Form class. The I skip them.
The problem is that the children list is not persisted correctly. For example the next test fails because getChildren().size() is 0 and not 1 (but other forms values are retrieved correctly, only the child list is empty):
#Test
public void storeFormWithCategory() throws NotValidChildException {
Form form = new Form();
form.setName("Test Form");
Category category = new Category();
form.addChild(category);
formDao.makePersistent(form);
Form retrievedForm = formDao.read(form.getId());
Assert.assertEquals(retrievedForm.getId(), form.getId());
Assert.assertEquals(retrievedForm.getChildren().size(), 1);
}
If I move the code of the child list into the Form class, it works correctly and the test is passed. But the list inside the parent class is not working. I cannot understand why, the only difference is the use of the inheritance.
The problem was solved removing the Interface. I have read that hibernate cannot work with intefaces, and this is the reason why children parameter is not implemented with interfaces. Removing the interface implementation and changing some setters and getters methods (as getChildren) to use TreeObject solve the issue. I have thinked that not using the interface with the DAO was enought to solve this issue. But seems that the getters and setters of the object also must not use the inteface.
Probably, when I have copied to Form object I haven't use the interface as a quick copy paste, and this is the reason why has worked correctly in this case.

Categories