How can I create my own BaseEntity using PanacheEntityBase? - jpa

I am using Panache ORM (with Postgresql) and I would like to add a column to every entity I have.
I have this:
#Entity
public class MyTable extends PanacheEntityBase {
// My columns
}
I would like this:
#Entity
public class MyBaseEntity extends PanacheEntityBase {
public String someId;
}
#Entity
public class MyTable extends MyBaseEntity {
// My columns
}
Now this does not work since Panache is now looking for the "base_entity" Table, which does not exist.
Can this be achieved ?

As MyBaseEntity has not table you have to replace #Entity with #MappedSuperclass
#MappedSupperclass
public class MyBaseEntity extends PanacheEntityBase {
public String someId;
}
MappedSuperclass tells JPA to use the attributes of this class in the subclasses.
Please also checkout the docs: https://docs.jboss.org/hibernate/orm/5.5/userguide/html_single/Hibernate_User_Guide.html#entity-inheritance-mapped-superclass

Related

How can I use JPA Query Methods to return an OR condition with NULL?

Am trying to create a Query that either matches all rows that equal tier or are NULL. Using Query Methods as described in Spring JPA Docs. The Default implementation below works if I just pass in the tier:-
#Entity
#Table(name = "tier")
class UuTier {
Long id;
Long tierId;
}
#Entity
#Table(name = "user")
class User {
#OneToOne
#JoinColumn(name="tier_id")
UuTier uuTier;
// Other Relationships
}
public interface UserRepository extends Repository<User, Long> {
List<User> findByTier_Id(#Param("tier")Long tier);
}
What I need is something like this, which is throwing an error " No property null found for type User". Can I achieve this ask using Query Methods?:-
public interface UserRepository extends Repository<User, Long> {
List<User> findByTierOrNull_Id(#Param("tier")String tier);
}
Following up from one of the responders (who for some reason deleted her post) - I got this to work!!
#Query("SELECT entity FROM User entity LEFT JOIN UuTier uuTier ON entity.uuTier.tier = uuTier.tier"
+ " WHERE entity.uuTier.tier = :tier OR entity.uuTier.tier IS NULL")
public List<User> findByTierOrNull_Id(#Param("tier") Long tier);

How to map OneToMany relationship from Superclass

Hello! Recently I was stuck with such problem, and I hope the solution I provide below will help some other JPA newbies like me. If there is better solution please post it here!
The problem is as follows:
I want to create OneToMany relationship from classes Book and CD to class Tag.
In order to unify all the logic regarding class Tag from Book and CD I create #MappedSuperclass class Item, and make Book and CD descendants of class Item. But when I try to map
List <Tag>
tags with #OneToMany” in that superclass I get nothing good..
My solution:
In order to do an ORM mapping one should understand first what he actually wants to see in the database. So when I realized that reasonable solution is to create several transition tables between descendants of Item and Tag, I understood, that this may be accomplished using #ManyToMany. And it works fine!
Listing below.
#MappedSuperclass
public class Item extends Model {
#Id
public Long id;
#ManyToMany(cascade = CascadeType.ALL)
public List<Tag> tags;
public String name;
<…> }
#Entity
public class Book extends Item {
public int pageNum;
<…> }
#Entity
public class CD extends Item{
public int size;
<…> }
#Entity
public class Tag extends Model{
#Id
public Long id;
public String text;
<…> }
PS I'd post also class and er diagrams, but currently I got no r8n to post images.

Mapping abstract classes with includePaths

I have a question regarding mapping of Hibernate Search and using an abstract base class.
I'm getting the following error
Caused by: org.hibernate.search.SearchException: Found invalid #IndexedEmbedded->paths configured on class nl.project.model.social.AbstractGroup, member language: language.id
at org.hibernate.search.engine.spi.AbstractDocumentBuilder.validateAllPathsEncountered(AbstractDocumentBuilder.java:901)
at org.hibernate.search.engine.spi.AbstractDocumentBuilder.checkForIndexedEmbedded(AbstractDocumentBuilder.java:880)
at org.hibernate.search.engine.spi.AbstractDocumentBuilder.initializeMemberLevelAnnotations(AbstractDocumentBuilder.java:489)
at org.hibernate.search.engine.spi.AbstractDocumentBuilder.initializeClass(AbstractDocumentBuilder.java:391)
at org.hibernate.search.engine.spi.AbstractDocumentBuilder.<init>(AbstractDocumentBuilder.java:174)
at org.hibernate.search.engine.spi.DocumentBuilderContainedEntity.<init>(DocumentBuilderContainedEntity.java:60)
at org.hibernate.search.spi.SearchFactoryBuilder.initDocumentBuilders(SearchFactoryBuilder.java:396)
at org.hibernate.search.spi.SearchFactoryBuilder.buildNewSearchFactory(SearchFactoryBuilder.java:222)
at org.hibernate.search.spi.SearchFactoryBuilder.buildSearchFactory(SearchFactoryBuilder.java:146)
at org.hibernate.search.event.impl.FullTextIndexEventListener.initialize(FullTextIndexEventListener.java:130)
at org.hibernate.search.hcore.impl.HibernateSearchIntegrator.integrate(HibernateSearchIntegrator.java:83)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:301)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1750)
Based on the following mapping configuration
#Entity
#Table
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "DTYPE", discriminatorType= DiscriminatorType.STRING, length = 3)
#Indexed
public abstract class AbstractGroup implements Serializable, IEntity, IPhoto{
protected Language language;
#ManyToOne(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
#JoinColumn(name="FK_LanguageId")
#Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE,region=CacheRegion.NEVERCHANGE)
#NotNull
#IndexedEmbedded(includePaths={"id"})
public Language getLanguage() {
return language;
}
}
#Entity
#DiscriminatorValue(value = "GRP")
#Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE,region=CacheRegion.GROUP)
public class Group extends AbstractGroup{
#Entity
#DiscriminatorValue(value = "PGE")
#Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE,region=CacheRegion.GROUP)
public class Page extends AbstractGroup{
I've tried putting #Indexed on the subclass but this gives the same error.
The #Indexed annotation should indeed be on the sub classes. However, I am not sure what this should have to to with te discriminator column. JPA and Search annotations should be orthogonal. Two different things really. Btw, how does your Language entity look like? See also https://forum.hibernate.org/viewtopic.php?f=9&t=993097&hilit=abstract+base+class

JPA Inheritance :mapping derived entities to different tables

I use SINGLE_TABLE inheritance startegy to map my usres (see code example bellow).
Is there a way to map UnActiveRegularUser and UnActiveBusinessUser from "ACTIVE_USERS" table to another table, for example "UNACTIVE_USERS" and keep the inheritance startegy?
Note:
-The point here is to avoid code duplication between ex. RegularUser Vs UnActiveRegularUser (since they use the same properties) but still to map them to 2 different tables: "ACTIVE_USERS" and "UNACTIVE_USERS".
-strategy = InheritanceType.SINGLE_TABLE should not be changed.
-May adding another abstraction layer solve this problem?
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#Table(name = "ACTIVE_USERS")
public class User {
#Id #GeneratedValue
protected Long id;
#Column(nullable = false)
protected String name;
}
#Entity
public class RegularUser extends User{
//more getters and settres
}
#Entity
public class UnActiveRegularUser extends User{
//same getters and setters as in RegularUser
}
#Entity
public class BusinessUser extends User {
//more getters and settres
}
#Entity
public class UnActiveBusinessUser extends User {
//same getters and setters as in BusinessUser
}
Thanks,
Nathan
Persisting fields to another table won't prevent code duplication. I think you should just make UnActiveBusinessUser extend BusinessUser, and UnactiveRegularUser extend RegularUser.
Note that if a user can become unactive (i.e. it is a RegularUser and becomes an UnactiveRegularUser), inheritance is not the right solution: an object can't go from one type to another. Since it seems UnactiveRegularUser doesn't have anything more than RegularUser, I'm not sure this subclass is useful.

How do I represent this using JPA?

I would like a 'RolesPlayed' entity with the following columns
user
role
department/project/group
All the three columns above constitute a composite primary key. I would like to know if defining a column to be one of department/project/group possible ? If yes, how ? Or do I need to break the entity into DepartmentRoles, GroupRoles and ProjectRoles.
Thanks.
You could use polymorphism with an abstract base class to do that.
#Entity
public class RolePlayed {
#ManyToOne
private User user;
#ManyToOne
private Role role;
#ManyToOne
private Body body;
...
}
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
public abstract class Body {
...
}
#Entity
public class Department extends Body {
...
}
#Entity
public class Project extends Body {
...
}
#Entity
public class Group extends Body {
...
}
Check out the Polymorphism section in the Java Enterprise tutorial for a good overview.
Alternatively, you could also make the RolePlayed entity abstract, with DepartmentRole, GroupRole and ProjectRole implementations.