I am trying to Map the following data structure in hibernate:
#OneToMany(fetch = FetchType.EAGER,cascade=Array(CascadeType.REMOVE,CascadeType.REFRESH,CascadeType.MERGE,CascadeType.PERSIST))
#JoinTable(name = "links", joinColumns = Array(new JoinColumn(name = "link_id")))
#MapKey(name="id")
#Fetch(value = FetchMode.SELECT)
#Access(AccessType.PROPERTY)
def getLinksMapNative:java.util.Map[MyClass,MyClass] = {
linksMap
}
I have the following problem though:
If I leave the MapKey annotation, when loading from the session, the Key of the Map is the integer id of MyClass instead of being an instance of MyClass and this result into a ClassCastException at runtime
If I take it off, since MyClass is an abstract entity I get:
org.hibernate.InstantiationException: Cannot instantiate abstract class or interface
at the moment of persisting.
Can one map a Map of two abstract entities in Hibernate, and if yes, how?
Related
I'm using Hibernate with Spring Boot and JPA, and have a business requirement to retrieve and combine in to a single paged response data that is stored in four different tables in the DB.
Let's call the first two tables "tblCredits", containing Credits, and "tblDebits", containing Debits. For our purposes, those two tables are IDENTICAL - same column names, same column types, same ID fields, everything. And my endpoint is supposed to be able to return a combined list of both Credits and Debits, with the ability to search/sort by any/all of the fields being returned, and with paging.
If I controlled that DB, I would simply merge the two tables in to a single table, or create a view or stored proc which did that for me, but this is a legacy DB used by other applications which I can't modify in any way, so that's not an option.
If I didn't have to sort and page, I could just create two completely independent entities, create a separate Spring Data JPA repository for each entity, query the two repositories separately, and then just combine the results in my own code. But paging the combined results especially would get very hairy, I don't want to have to implement the merged paging logic myself unless I absolutely have to. Ideally I should be able to get JPA to handle all of that for me out-of-the-box.
I have been able achieve this first step for these first two tables using an abstract class declared as an Entity with InheritanceType.TABLE_PER_CLASS, like this:
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractCreditDebitEntity {
/* literally all my properties and ID and column mappings here
...
*/
}
And then two concrete classes which extend that abstract entity and simply specify the two different table mappings, have no class-specific properties or column mappings at all:
#Entity
#Table(name = "tblCredits")
public final class Credit extends AbstractCreditDebitEntity {
//Literally nothing inside this class
}
#Entity
#Table(name = "tblDebits")
public final class Debit extends AbstractCreditDebitEntity {
//Literally nothing inside this class
}
So far so good, this works great, I am able to create a Spring JPA Repository on the AbstractCreditDebitEntity entity, under the hood that generates a union query on the two tables, and I am able to get back records from both tables in a single query, with appropriate paging and sorting. (The performance issues around union queries don't concern me at the moment.)
However, where I'm getting tripped up is on the next step, when I incorporate the additional two tables. tblCredits has a one-to-many relationship to tblCreditLineItems, and tblDebits has a one-to-many relationship to tblDebitLineItems. Again, tblCreditLineItems and tblDebitLineItems are IDENTICAL tables, from our perspective - same column names, same column types, same ID fields, everything.
So I can follow the same pattern as before for those sub-entities:
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractCreditDebitLineItemEntity {
/* literally all my properties and ID and column mappings here
...
*/
}
#Entity
#Table(name = "tblCreditLineItems")
public final class CreditLineItem extends AbstractCreditDebitLineItemEntity {
//Literally nothing inside this class
}
#Entity
#Table(name = "tblDebitLineItems")
public final class DebitLineItem extends AbstractCreditDebitLineItemEntity {
//Literally nothing inside this class
}
But now I need to create the mappings between the Credit/Debit entities and CreditLineItem/DebitLineItem entities. And this is where I'm struggling. Because I need to be able to filter which specific Credit/Debit entities I return based on the values of properties inside their associated CreditLineItem/DebitLineItem entities, I need a bidirectional mapping between the two entities, and I've been unable to get that working successfully.
Here's how far I've gotten so far. First the three Credit/Debit entities with the OneToMany mapping to their associated CreditLineItem/DebitLineItem entities:
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractCreditDebitEntity {
/* literally all my properties and ID and column mappings here
...
*/
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(
name = "MyIdColumnName",
referencedColumnName = "MyIdColumnName"
)
public abstract List<AbstractCreditDebitLineItemEntity> getCreditDebitLineItems();
public abstract void setCreditDebitLineItems(List<AbstractCreditDebitLineItemEntity> items);
}
#Entity
#Table(name = "tblCredits")
public final class Credit extends AbstractCreditDebitEntity {
private List<CreditLineItem> creditDebitLineItems;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = CreditLineItem.class)
#JoinColumn(
name = "MyIdColumnName",
referencedColumnName = "MyIdColumnName"
)
#Override
public List<AbstractCreditDebitLineItemEntity> getCreditDebitLineItems() {
return Optional.ofNullable(creditDebitLineItems).stream()
.flatMap(List::stream)
.filter(value -> AbstractCreditDebitLineItemEntity.class.isAssignableFrom(value.getClass()))
.map(AbstractCreditDebitLineItemEntity.class::cast)
.collect(Collectors.toList());
}
#Override
public void setCreditDebitLineItems(List<AbstractCreditDebitLineItemEntity> items) {
creditDebitLineItems = Optional.ofNullable(items).stream()
.flatMap(List::stream)
.filter(value -> CreditLineItem.class.isAssignableFrom(value.getClass()))
.map(CreditLineItem.class::cast)
.collect(Collectors.toList());
}
}
#Entity
#Table(name = "tblDebits")
public final class Debit extends AbstractCreditDebitEntity {
private List<DebitLineItem> creditDebitLineItems;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = DebitLineItem.class)
#JoinColumn(
name = "MyIdColumnName",
referencedColumnName = "MyIdColumnName"
)
#Override
public List<AbstractCreditDebitLineItemEntity> getCreditDebitLineItems() {
return Optional.ofNullable(creditDebitLineItems).stream()
.flatMap(List::stream)
.filter(value -> AbstractCreditDebitLineItemEntity.class.isAssignableFrom(value.getClass()))
.map(AbstractCreditDebitLineItemEntity.class::cast)
.collect(Collectors.toList());
}
#Override
public void setCreditDebitLineItems(List<AbstractCreditDebitLineItemEntity> items) {
creditDebitLineItems = Optional.ofNullable(items).stream()
.flatMap(List::stream)
.filter(value -> DebitLineItem.class.isAssignableFrom(value.getClass()))
.map(DebitLineItem.class::cast)
.collect(Collectors.toList());
}
}
And then the three CreditLineItem/DebitLineItem entities with their ManyToOne mappings back to the Credit/Debit entities:
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractCreditDebitLineItemEntity {
/* literally all my properties and ID and column mappings here
...
*/
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(
name = "MyIdColumnName",
referencedColumnName = "MyIdColumnName",
updatable = false,
insertable = false)
public abstract AbstractCreditDebitEntity getCreditDebit();
public abstract void setCreditDebit(AbstractCreditDebitEntity creditDebitEntity);
}
#Entity
#Table(name = "tblCreditLineItems")
public final class CreditLineItem extends AbstractCreditDebitLineItemEntity {
private Credit creditDebit;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(
name = "MyIdColumnName",
referencedColumnName = "MyIdColumnName",
updatable = false,
insertable = false)
#Override
public Credit getCreditDebit() {
return creditDebit;
}
#Override
public void setCreditDebit(AbstractCreditDebitEntity creditDebitEntity) {
creditDebit =
Optional.ofNullable(creditDebitEntity)
.filter(value -> Credit.class.isAssignableFrom(value.getClass()))
.map(Credit.class::cast)
.orElse(throw new RuntimeException());
}
}
#Entity
#Table(name = "tblDebitLineItems")
public final class DebitLineItem extends AbstractCreditDebitLineItemEntity {
private Debit creditDebit;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(
name = "MyIdColumnName",
referencedColumnName = "MyIdColumnName",
updatable = false,
insertable = false)
#Override
public Debit getCreditDebit() {
return creditDebit;
}
#Override
public void setCreditDebit(AbstractCreditDebitEntity creditDebitEntity) {
creditDebit =
Optional.ofNullable(creditDebitEntity)
.filter(value -> Debit.class.isAssignableFrom(value.getClass()))
.map(Debit.class::cast)
.orElse(throw new RuntimeException());
}
}
This code compiles, however... when in my automated tests I try to persist one of my Credit entities (I use a simple H2 database for my automated tests), I get the following error:
2021-04-02 13:53:52 [main] DEBUG org.hibernate.SQL T: S: - update AbstractCreditDebitLineItemEntity set MyIdColumnName=? where ID=?
2021-04-02 13:53:52 [main] DEBUG o.h.e.jdbc.spi.SqlExceptionHelper T: S: - could not prepare statement [update AbstractCreditDebitLineItemEntity set MyIdColumnName=? where ID=?]
org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "ABSTRACTCREDITDEBITLINEITEMENTITY" does not exist
It appears to be trying to persist based on the #OneToMany mapping from my AbstractCreditDebitEntity class to my AbstractCreditDebitLineItemEntity. Which, since it's an abstract class with InheritanceType.TABLE_PER_CLASS, has no table specified for it, so it assumes the table it needs to persist to has the same name as the class.
What I wanted to happen here is for the #OneToMany mapping on the concrete getter in the Credit subclass, which specifies its targetEntity as the concrete CreditLineItem.class, to essentially override/replace the #OneToMany mapping on its parent abstract class. But it seems the mapping on the concrete class gets completely ignored?
I could remove the #OneToMany mapping from the AbstractCreditDebitEntity class entirely, and only define that mapping in the two concrete Credit/Debit entities that extend it. That makes the persistence error go away, and 90% of my test cases pass... but in that case when I try to filter or sort the results coming back from the combined AbstractCreditDebitEntity Spring Data JPA repository based on one of the fields that only exists in the CreditLineItem/DebitLineItem sub-entity, the query fails due to the AbstractCreditDebitEntity no longer having any mapping to the AbstractCreditDebitLineItemEntity.
Is there any good way of resolving this problem, so that the OneToMany mapping from AbstractCreditDebitEntity to AbstractCreditDebitLineItemEntity still exists, but the knowledge that the Credit entity maps specifically to the CreditLineItem entity and the Debit entity maps specifically to the DebitLineItem entity is also maintained?
After a lot of experimentation, I found something that works for me.
Basically, rather than try to override the OneToMany mapping in the abstract entity class with the OneToMany mappings in the concrete entities, I had to make them completely separate mappings to completely different properties. Which means my concrete entities have two different collections of AbstractCreditDebitLineItemEntity, and some AbstractCreditDebitLineItemEntity objects will appear twice, in both collections. A bit wasteful in terms of memory/computation, but I'm okay with that, it works!
So here's what I ended up with:
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractCreditDebitEntity {
/* literally all my properties and ID and column mappings here
...
*/
private List<AbstractCreditDebitLineItemEntity> creditDebitLineItems;
#OneToMany(fetch = FetchType.LAZY, targetEntity = AbstractCreditDebitLineItemEntity.class)
#JoinColumn(
name = "MyIdColumnName",
referencedColumnName = "MyIdColumnName",
updatable = false,
insertable = false
)
public List<AbstractCreditDebitLineItemEntity> getCreditDebitLineItems() {
return creditDebitLineItems;
}
public void setCreditDebitLineItems(List<AbstractCreditDebitLineItemEntity> items) {
creditDebitLineItems = items;
}
}
#Entity
#Table(name = "tblCredits")
public final class Credit extends AbstractCreditDebitEntity {
private List<CreditLineItem> creditLineItems;
#OneToMany(cascade = CascadeType.ALL, targetEntity = CreditLineItem.class)
#LazyCollection(LazyCollectionOption.FALSE)
#JoinColumn(
name = "MyIdColumnName",
referencedColumnName = "MyIdColumnName"
)
public List<CreditLineItem> getCreditLineItems() {
return creditLineItems;
}
#Override
public void setCreditDebitLineItems(List<CreditLineItem> items) {
creditLineItems = items;
}
}
With the exact same pattern repeated for the Debit entity.
This allows me to both:
persist, using the OneToMany mappings from the concrete Credit and Debit entities to the concrete CreditLineItem and DebitLineItem entities; and
do finds on the Spring Data JPA repository of AbstractCreditDebitEntity, using the the completely separate OneToMany mapping from that abstract entity to the AbstractCreditDebitLineItemEntity.
Not as clean as if I'd been able to override the OneToMany mapping in the abstract parent class with a more specific OneToMany mapping in the concrete child classes... but as I said, it works!
(The answer on this issue helped me know I needed to replace fetchType=FetchType.EAGER on my concrete OneToMany mappings with #LazyCollection(LazyCollectionOption.FALSE):
Hibernate throws MultipleBagFetchException - cannot simultaneously fetch multiple bags)
So I have three entities. A FormCollection contains multiple Form. The Form is created from a template and thus has also a many-to-one relation to FormTemplate.
#Table(name = "form_collection", schema = "public")
public class FormCollectionDO extends BaseAuditableDO {
#OneToMany(mappedBy = "formCollection")
#OrderBy("formTemplate.templateId") //throws error
private List<FormDO> forms = new ArrayList<>();
}
#Table(name = "form", schema = "public")
public class FormDO extends BaseAuditableDO {
#NotNull
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "form_template_id")
private FormTemplateDO formTemplate;
}
#Table(name = "form_template", schema = "public")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class FormTemplateDO extends BaseDO {
#Column(name = "template_id", nullable = false)
#NotNull
private Long templateId;
}
#OrderBy("formTemplate.templateId") throws an error:
o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: missing FROM-clause entry for table "formtemplate"
#OrderBy("formTemplate.id") works fine. The id comes from the abstract class BaseDO. Why does it not work with any of the fields from the FormTemplateDO class?
Although I am not sure about this solution, What I am suspecting is this issue happens because the formTemplate.templateId isnt part of your query indeed.
I see you are using #OneToMany for defining the relationship, but in hibernate, the default FetchMode is SELECT which means your order by parameter isnt part of your query. To make this parameter part of your query, you will have to make a Join query.
Try this out -
#Fetch(value = FetchMode.JOIN)
#OneToMany(mappedBy = "formCollection")
#OrderBy("formTemplate.templateId") //throws error
private List<FormDO> forms = new ArrayList<>();
And propogate this join to further levels. It might solve your problem.
When you want to order by a collection of entities by a nested attribute, you can not use #OrderBy, because the nested attribute is not part of your query. You can only use #OrderBy for of first level attribute OR a nested attribute IF it is a collection of #Embeddable.
So for this case, you have to use #SortNatural or #SortComparator.
Similar issue : Hibernate - How to sort internal query lists (or List in List)?
More about #OrderBy vs #SortNatural: Sort vs OrderBy - performance impact
I have a MessengerData class which contains a list of resources. This my object MessengerData:
"messengerData":{
"fr":[
{
"messengerType":"ImageCategoryTitle",
"imageURL":"https://assets.pernod-ricard.com/uk/media_images/test.jpg"
}
"EN":[
{
"messengerType":"ImageCategoryTitle",
"imageURL":"https://assets.pernod-ricard.com/uk/media_images/test.jpg",
}
]
This is how I define my object MessengerData:
#Entity
public class MessengerData
{
#Basic
#Id
#GeneratedValue(generator = "notification-system-uuid")
#GenericGenerator(name = "notification-system-uuid", strategy = "uuid")
private String messengerDataId;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) /* , mappedBy = "idResource" */
#JoinTable(name = HemisTablesNames.MESSENGER_RESOURCES, joinColumns = #JoinColumn(name = "idResource"),
inverseJoinColumns = #JoinColumn(name = "messengerDataId"))
private Map<String, Set<Resource>> resources;
}
But I am getting this exception: Use of #OneToMany or #ManyToMany targeting an unmapped class: com.ubiant.hemis.type.MessengerData.resources[java.util.Set]
Could someone help me with this ?
Hibernate doesn't seem to support multimaps (that's what resources is) directly but you could provide your own custom type like described here: https://xebia.com/blog/mapping-multimaps-with-hibernate/ .
However, since your data seems to be Json anyway you could go one more step and directly map the resources as json, i.e. into a text column (or a json column if the db supports it): http://fabriziofortino.github.io/articles/hibernate-json-usertype/
We're doing something similar, which on an outline looks like this (this is a generic type, in most cases a more specific POJO will be better):
class JsonData extends HashMap<String, Object> { ... }
//JsonbUserType is a custom implementation based on code like the one linked above
class JsonDataUT extends JsonbUserType<JsonData > { ... }
Then in package-info.java of the package the user type is in we have this:
#TypeDefs ( {
#TypeDef ( name = "JsonDataUT ", typeClass = JsonDataUT.class, defaultForType = JsonData.class ),
...
})
package our.package;
And our entities then just contain this:
#Column( name = "data_column")
private JsonData data;
One advantage of this is that we don't have to bother with more complex mappings, especially if types are dynamic.
One (major) disadvantage, however, is that you can't use that property in query conditions since Hibernate wouldn't know how to filter in a json column (we're using Postgres so it would really be a jsonb typed column, hence the usertype name) and afaik there's not reasonable way to provide custom functions etc. to enable things like where data.someFlag is true in HQL.
So I want to implement a Jpa Repository of my class Reservation.
My RoomType Enum:
public enum RoomType{
BREUGHELZAAL("Breughel zaal"),
CARDIJNZAAL("Cardijn zaal"),
FEESTZAAL("Feest zaal"),
KEUKEN("Keuken"),
RECEPTIEZAAL("Receptie zaal"),
KLEINEKEUKEN("Kleine keuken");
private String roomType;
RoomType(String roomType){
this.roomType= roomType;
}
public String getRoomType(){
return roomType;
}
}
Now I have no clue how to implement this. I need a List of Enum types in my reservation class, i guess it is something like this, but I don't know the annotation for the enum type:
#OneToMany(cascade = CascadeType.ALL)
List<RoomType> chosenRooms
Thanks in advance for the help!!
You don't have sufficient config for Enum persistence, try :
#ElementCollection(fetch = FetchType.EAGER)
#CollectionTable(name = "RoomType", joinColumns = #JoinColumn(name = "id"))
#Enumerated(EnumType.STRING)
List<RoomType> chosenRooms
#ElementCollection - Defines a collection of instances of a basic type or embeddable class.
#CollectionTable - pecifies the table that is used for the mapping of collections of basic or embeddable types (name - name of the collection table, joinColumn - The foreign key columns of the collection table).
Enumerated - Specifies that a persistent property or field should be persisted as a enumerated type.
There is a foreign key in my entity :
#Entity
#Table(name = "role")
public class Role {
#Id
#Column(name = "role_code")
private String code;
#Column(name = "role_lib")
private String lib;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "role_menu" , joinColumns = {#JoinColumn(name = "role_code")} , inverseJoinColumns = {#JoinColumn(name = "menu_id")} )
#JsonManagedReference
private Set<Menu> menus = new HashSet<Menu>();
// getters and setters
}
It is said in Hibernate documentation that relationship attributes should be of type Interface. Now my problem is when dealing with an instance of this class and using the getMenus() method :
#Override
#Transactional
public Set<Menu> getListMenu(String role_code) {
return ((Role)get(role_code)).getMenus();
}
I want to cast it to a HashSet , but I got castException of persistent object at runtime. So how to make it to be HashSet ?
You cannot cast if the implementations of Set is not HashSet. But you can create a object:
new HashSet(obj.getMenus);
But it's always better to use interfaces, not the implementation.
Here is a note from Hibernate doc:
Hibernate will actually replace the HashSet with an instance of
Hibernate's own implementation of Set. Be aware of the following
errors:
......
(HashSet) cat.getKittens(); // Error!
And here is why you don't actually need to cast nor to create a new object:
The persistent collections injected by Hibernate behave like HashMap,
HashSet, TreeMap, TreeSet or ArrayList, depending on the interface
type.