Implementing a foreign key relationship in Hibernate - java

I have a class Problem and then various other classes which extend the base class Solution like BasicSolution, ExpertSolution, many other
solution sub classes. The Problem class will be a 'foreign key' for the various solutions classes, although the Problem class doesn't need the solution list.
So I want foreign key of Problem table in various solution tables (one table per solution sub-class). How I can achieve it through Hibernate?
I know that this is not the right DB design from Hibernate's perspective but it's a legacy system and can't be tweaked. I know one-to-many entity
association but that will need some Solution list to be present in Problem class (which I don't want).
Can you please suggest some answer to this problem?

You need to map the relation in the Solution base class with #ManyToOne association:
#Entity
#Inheritance(strategy=InheritanceType.JOINED)
public abstract class Solution {
...
private Problem _problem;
#ManyToOne
#JoinColumn(name="PROBLEM_ID")
public Problem getProblem() {
return _problem;
}
...
}
All Solution sub classes will have the relation to Problem.
You can also use #OneToOne instead of #ManyToOne, the difference is that #ManyToOne must have the foreign key on this side of the relation.

Related

Hibernate: How to distinguish two uni-directional relationship and one bi-directional relationship?

in this answer, the author said:
Take an example of two entities mapped without declaring a owning
side:
#Entity
#Table(name="PERSONS")
public class Person {
#OneToMany
private List<IdDocument> idDocuments;
}
#Entity
#Table(name="ID_DOCUMENTS")
public class IdDocument {
#ManyToOne
private Person person;
}
From a OO point of view this mapping defines not one bi-directional
relation, but two separate uni-directional relations.
1.My first question is:
Why it is not a bi-directional relation?
Docs Oracle:
In a bidirectional relationship, each entity has a relationship field
or property that refers to the other entity. Through the relationship
field or property, an entity class’s code can access its related
object
in the above code, both class have a relationship field that refers to the other entity. then why it is not a bi-directional relation and these are two uni-directional relations?
2.My second question is: what is the difference between two uni-directional relations and one bi-directional relation? aren't they same thing?
(1) No ideas why the author said it is not a bi-directional relationship.
From the hibernate documentation , it also mentions that a similar mapping is a bidirectional which both involved entities can navigate to each other.
In this example, given a Person , we can get its IdDocument by its idDocuments field. And given an IdDocument , we can get its Person by its person field. So it is a bi-directional.
(2) I am not sure too. To me, whenever both entities in a relationship can navigate to each other , it is a bi-directional relationship. If only one entity can navigate to another but not vice versa , it is a unidirectional relationship.
And you can find the equivalent unidirectional case of the example the I mentioned above in this for comparing their differences.

When to use #Embedded and #Embeddable?

Is it possible to annotate a class as #Embeddable or a property as #Embedded?
Sample code:
#Embeddable
class A{
...
}
class B{
...
}
#Entity
class Foo {
A a;
#Embedded B b;
}
When to prefer #Embedded and #Embeddable?
There are two primary uses for #Embedded/#Embeddable as far as I know:
First, and most important: Splitting up large entity classes. In the database world, a large table (one with many columns) is fine. Breaking up such a table might even make things worse, and be in collision with database design principles. In Java (or object oriented languages in general), on the other hand, a large class is a code smell. Here, we would like to split the classes, including entity classes, into smaller units. #Embedded/#Embeddable allows us to easily do this without having to split the database table.
Second, it allows for reuse of common mappings between entities. Say each table has a simple revision tracking, with two columns containing the username of the person who changed the row, and the time it happened. Then, one can make an #Embeddable entity covering these rows, and then reuse this across all entities by embedding it (rather than repeating the variables corresponding to these columns in each entity.)
If we have Person and Address that are two POJOs, You would not want to create another table for Address but you would want to embed the address within the person table. So Address is adding up value to the Person object but doesn't make any sense individually. In this case we may go with:
#Embeddable
public class Address{
}
#Entity
public class Person
{
#Embedded
private Address address;
}
You would use #Embeddable and #Embedded together. You mark your class as #Embeddable, which indicates that this class will not exist in the DB as a separate table. Now when you use #Embedded on the field itself.
The word embeddable and embedded gives you a big clue actually.
Embeddable = This class can be embedded in a class
Embedded = This class will now be embedded in your class as a field.
I guess if you annotate class as #Embeddable you don't need to annotate field as #Embedded. Also, if you annotate class as #Embeddable and you want to use it as primary key, you can use #Id only, but if it is not annotated as #Embeddable, you have to use #EmbeddedId on field to work as primary key.

datanucleus/JDO a relation to many different classes)

I need to create a database with 2 kinds of 'modules'.
domain focused classes
metadata classes
In the first group it is just simple (or complex rather) RDBMS. The second 'block' are metadata classes which collects information about classes from the first block.
What I have done:
Created Entity class which is parent of all fro 1st part:
#PersistenceAware
#Inheritance(strategy = InheritanceStrategy.NEW_TABLE)
public abstract class Entity implements Serializable {
private static final long serialVersionUID = 1L;
}
Created normal schema with all entities inherit somehow Entity class.
Created InternalMapping class as a parent of the whole concept.
#PersistenceCapable
#Inheritance(strategy = InheritanceStrategy.NEW_TABLE)
public abstract class InternalMapping implements Serializable {
private static final long serialVersionUID = 1L;
private Entity entity;
//.. cut off getter and setter
}
Created InternalMapping child which should have that feature.
Finally I found it does not work. Probably because Entity does not have any field. But if so I would expect 2 fields: a primary key and class name. In that way I would map every entity by 2 coordinates: ID and class name.
Any idea how to solve that issue? An finally how JDOQL would looks like.
Ps. I know that RDBMS is not the best solution for that kind of problems but people with whom I work wish to have relational database.
Finally I found solution for my problem. I am able to keep entities of different classes keep in one table. Also I am able to do JDOQL request with filtering instances of particular class.
The example is inside GitHub repository here: https://github.com/jgrzebyta/samples-jdo/tree/metalink and within metalink branch. It is slightly modified Tutorial project from datanucleus example.
So.
The lowest level in the inheritance hierarchy is Core interface with the PK defined inside.
Class MyIndex collects different implementations of the Core interface, i.e. Book and Product. Also I have added new column called type for storing Class names only. I am able to retrieve implementations of Core interface and build query filter against type filed because query type core instanceof Book simple does not work. That is the feature of the identity mapping strategy which I have used in my solution: DataNucleus JDO Objects.
PS. If you run command mvn -Pschema-gen compile than you will receive DDL file.

Hibernate : Difference between # Embedded annotation technique and #OneToOne annotation Technique

What is the difference between #Embedded annotation technique and #OneToOne annotation technique because in Embedded the java class contain "Has a" relationship in class and with the help of #Embedded annotation we persist the has a object in database. and in OneToOne relationship we also persist the has a object in database.
#OneToOne is for mapping two DB tables that are related with a one to one relationship. For example a Customer might always have one record in a Name table.
Alternatively if those name fields are on the Customer table (not in a separate table) then you might want an #embedded. On the face of it you could just add the name fields as standard attributes to the Customer entity but it can be useful if those same columns appear on multiple tables (for example you might have the name columns on a Supplier table).
Its the difference between composition and aggregation. #Embedded objects are always managed within the lifecycle of their parents. If the parent is updated or deleted, they are updated or deleted as well. #OneToOne objects may mimic composition via the cascadeType option of their #Join annotation, but by default they are aggregated, aka their lifecycle is separate from that of their parent objects.
#Embedded is used with Value Objects (Objects which have a meaning only when attached to an Object) whereas one to one mapping is between two objects having their own existence and meaning.
For e.g.
Value Object and #Embedded: If we have a User class and this class has an address Object in it, it can be considered as a value object as the address alone does not have any significance until unless associated with a user. Here address object can be annotated with #Embedded.
One to One mapping and #OneToOne: If we have a User class and this class has a 'Father' Object or a 'Mother' object, we would want to annotate the 'Father' or 'Mother' instance as #OneToOne as 'Father' or 'Mother' have their own meaning and existence and are not Value objects to User class.
A closely related difference is between #OneToMany and #ElementCollection. Both are used to save instance variables of Collection type in Java class. The difference being, #ElementCollection is to be used when the elements of Collection being saved are Value Objects whereas #OneToMany is used when the elments and object have well defined meaning and existence.
Use #OneToOne, only if fields can be reused. Otherwise, go for #Embeddable.
A quote from Beginning Hibernte, 3rd Edition:
There is nothing intrinsically wrong with mapping a one-to-one association between two entities where one is not
a component of (i.e., embedded into) the other. The relationship is often somewhat suspect, however. You should
give some thought to using the embedded technique described previously before using the #OneToOne annotation.
#Embeddable:
If the fields in an entity (X) are contained within the same table as another entity (Y), then entity X is called "component" in hibernate terms or "embedded" in JPA terms. In any case, JPA or hibernate do not allow to use 2nd table to store such embedded entities.
Generally, we think of normalizing a table when data is being reused by more than one table. Example: A Customer (id, name, street, city, pin, landmark) can be normalized into Customer(id, name) and CustomerAddress(cust_id, street, city, pin, landmark). In this case, we can reuse CustomerAddress by linking the same using cust_id with other tables. But if this reuse is not required in your application, then we can just keep all columns in one table.
So, a thumb rule is,
If reuse -> #OneToOne,
If no reuse -> #Embeddable
#Embedded is typically to represent a composite primary key as an embeddable class:
#Entity
public class Project {
#EmbeddedId ProjectId id;
:
}
#Embeddable
Class ProjectId {
int departmentId;
long projectId;
}
The primary key fields are defined in an embeddable class. The entity contains a single primary key field that is annotated with #EmbeddedId and contains an instance of that embeddable class. When using this form a separate ID class is not defined because the embeddable class itself can represent complete primary key values.
#OneToOne is for mapping two DB tables that are related with a one to one relationship. #Id will be the primary key.

How do I extend a hibernate annotated class to point a field to a different hibernate entity?

Let's say I have the following class structure:
/** Boring bits snipped */
#Entity
#Table(name = "Foo")
public class Foo {
#JoinColumn(name = "id")
private Bar bar;
/** Other flat data goes here */
}
#Entity
#Table(name = "Bar")
public class Bar {
/** Some data goes here */
}
For reasons I'm not going to go into, I have copies of these tables which I want to also map too, which should appear in Java to also be Foo and Bar objects. Most importantly, the relationships between tables should be between the copied tables when dealing with copied objects.
What is the most correct way of doing this?
I'm guessing I can probably do something like this:
#Entity
#Table(name = "OtherFoo")
public class OtherFoo extends Foo {
#JoinColumn(name = "id")
private OtherBar bar;
}
#Entity
#Table(name = "OtherBar")
public class OtherBar extends Bar {
}
But is that the right way to do it?
You're close, but you can't just inherit from another entity and change the table like that. Entity inheritance has to follow one of the provided inheritance models. It may be for your use case as simple as adding #Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) to the superclass. There are some limitations to this if you have some more complicated mappings with other classes. Since it won't be able to tell which table a superclass based mapping is actually in, it can't join through it. And mappings to the superclass will require checking both tables every time. You also of course need unique ID generation across all the tables in the hierarchy. You may want to consider using an abstract superclass and having both concrete entities be leaf classes. Then at least you can always work with just a single table when you know which one it is.
Alternately you can declare your column mappings in an #MappedSuperclass and each subclass can then be an entity with a table mapping. That might work better if it's legacy data and you don't have unique IDs across the 'regular' and 'copy' tables.

Categories

Resources