Assume that I have several realm objects (tables) with many connections between them, and I don't yet have all the objects pre populated.
I want to be able to create relationships by their ids (primary keys).
For example, I have JSON file with an object that has a list of another object's ids (not the actual object, although that another object is already exists in the realm db), I want to be able to populate those into objects directly without having to query them first.
How is that possible?
Realm is designed to be an object database without impedance mistach that could happen from mapping Java objects to an entry in table. Relation in Realm is specifically handled to adhere the principle above.
For example, one can describe relationship between object in following.
public class ObjectA extends RealmObject {
...
#PrimaryKey
private long id;
...
}
public class ObjectB extends RealmObject {
...
private RealmList<ObjectA> entries;
...
}
The relation you want, i.e. relation by primarykey id, seems much close to relational databases and it is not supported.
Related
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.
What's the use of #Embedded and #Embeddable In Hibernate ? Because every example i found on internet is inserting data inside of a single table and to do that using two different class. My point is if I am using a single table then I can map all the columns inside of a single class then why should i use different class. and if We use two different table then there is one-to-one and one-to-many hibernate relationship.
There are two types of objects in Hibernate
1. Value Object
2. Entities
Value Objects are the objects which can not stand alone. Take Address, for example. If you say address, people will ask whose address is this. So it can not stand alone.
Entity Objects are those who can stand alone like College and Student.
So in case of value objects preferred way is to Embed them into an entity object.
To answer why we are creating two different classes: first of all, it's a OOPS concept that you should have loose coupling and high cohesion among classes. That means you should create classes for specialized purpose only. For example, your Student class should only have the info related to Student.
Second point is that by creating different classes you promote re-usability.
When we define the value object for the entity class we use #Embeddable.
When we use value type object in entity class we use #Embedded
suppose we have employee table annotated with #entity and employee has Address so here i dont want to create two tables i.e employee and address, i just want create only one table i.e employee not Address table then we need to declare Address instance in Employee and add #embedable annotation on top of Address class, so finally we get table employee with its record and address records as well in single employee table
One entity can be embedded in another entity. The attributes of an entity can be common attributes of more than one entity. In this case there can be one embeddable entity. And this embeddable entity can be embedded in more than one entity.
Let's consider an example. We have one Animal entity, which has name and location attributes. Now two different entities Lion and Elephant can have Animal attributes just by embedding the Animal entity. We can override the attributes. In Animal entity there is location attribute and in Elephant there is place attribute. So with the help of #AttributeOverrides we can do like below:
#AttributeOverrides({ #AttributeOverride(name = "location", column = #Column(name = "place")) })
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.
Is there a possibility in JPA 2.0 to asure that an embedded object is embedded with only one object, but not several?
In my case I have an Address that I can assign to a Customer. I want every customer to use its own address object and would like to create a constraint that makes sure that no two customers share the actually same object.
My code looks like this:
#Entity
public Customer {
#Id
#GeneratedValue
private Long id;
#Embedded
private Address address;
// ..
}
#Embeddable
public Address {
private String street;
private String city;
// ..
}
Currently, if I create two customers and assign them the same Address object, then persist and read them, they again share the object with the same identity. I want to prohibit saving such customers that share addresses with other customers.
The simpliest approach in this case is to create a copy of Address object in Customer.setAddress().
Also, I'm not sure that different Customers can share Address with the same identity when retrieved from the database. Perhaps you get the same objects from the session cache because you save and read them in the same session.
It is the nature of the #Embedded mechanism that embedded instances of an embeddable class are NEVER shared among different instances of the enclosing class. If you observed this behavior in your code, it must have been because you were accessing cached data during reading from the entity manager.
So, even if you assign the same instance of an embeddable class to multiple instances of the enclosing class, then "persist()", then destroy the entity manager and EntityManagerFactories, or invalidate the caches "entityManager.getEntityManagerFactory().getCache().evictAll()", then create a new EntityManager and "find()" the enclosing objects, each of them should have their own instance of (in your case) "Address" objects, even if their content is the same.
The JPA spec says the following about embedded objects in section 2.5:
[...] Instances of these classes, unlike entity instances, do not have
persistent identity of their own. Instead, they exist only as part of
the state of the entity to which they belong. [...]
If your JPA implementation doesn't adhere to that, it isn't really JPA standards-compliant...
I will start with a small example:
Imagine an application with a couple of entities.
EntityA -1---n-> EntityB -1---n-> EntityC
Let's say we have a service method that returns a list of EnityC instances. In the UI we want to display EntityC but also add some additional information to the entity that is only relevant for the UI (maybe a css class or so). A common way to solve this would be to create a wrapper arround EntityC that can also carry the additional information.
public class EntityCWrapper implements EntityC, AdditionalInfo { ...}
or maybe use a transfer object as simple data structure:
public EntityTO {
public EntityC entity;
public AdditionalInfo info;
}
But what if the service returns a list of EnitityA instances and we need to attach AdditionalInfo to all entities in the instance graph (including the referenced entity instances of EntityB and EntityC)?
Does anyone have an idea or can point me to a design pattern suitable in this situation?
Have a look at the Role Object Pattern.
It descripes how an object can be extended with different stuff (called Roles).
The pattern is more about how to add Bussiness Logic (that is why it is called roles) but may the idea helps you.
Assuming AdditionalInfo is instance specific (i.e. each instance of EntityC has a unique 121 relation to an AdditionalInfo instance) best option would be to enhance EntityC definition to include AdditionalInfo inside it as member/..., which is optional and filled up by you.
If you don't have control over EntityC then between teh two options you have given, I would say TransferObject seems better. You won't have to create new objects (of EntityC) that way.
So your data model is essentially 1 to n using the following object as an example (contrived as it may be)
class Thing
{
Collection<DooDad> dooDads;
}
class DooDad
{
Collection<DooDadDetail> details;
}
class DooDadDetail
{
...
}
So I would treat this as my model, in terms of n-tier architecture and therefore this should map back to my database exactly. What comes up is you want your model to do something, whatever that may be. So you should create an object that is composed of Thing that can interact with business logic or outside services. Creating a transfer object would be correct in this case as it ensures your model remains valid and that the interfaces between both you and the outside service are not dependant on your model. It is sort of a Facade pattern and a Data Transfer Object.