Hibernate Mapping - java

I have an issue in performing Hibernate Mapping. The scenario is as follows:
There is a User class which has username, name, dateofbirth, image and other information pertaining to a user with username as the primary key.
Second class is Product class which has product id and other information related to a product with primary key as product key.
The third class is Order class which has OrderId, OrderDate, Username- should be foriegn key-referring to the User class username and finally a Set of type Product- because one order can have many products.
Now I want the primary key of the Order class as a composite key (OrderId, ProductID) and this productID should be reference from Product Class.
The relationships that I want to create are as follows:
1. One order can belong to only one User
2. One order can have many products
Can someone lead me on how to go about it? Any kind of help will be great.

I think most likely you are thinking similar relationship. Difference in your requirement is you need One to Many mapping from Order/PurchaseOrder to Product/Item and you don't want Shipment.
My suggestion would be:
Create bi-directional one-to-many relationship b/w User and Order. Benefit for bidirectional is you can access User Object from Order Object, if not required, you can keep it unidirectional from User to Order.
Create one-to-many relationship b/w Order and Product.
Instead of composite key in order, keep the primary key as just OrderID. You can still fetch list of products from your order object and order object from user object.
The whole point in making this decision is from which object you derive remaining objects. With ORMs you should know from which object you would derive rest and so my suggestion is based on assumption that you will have User object available as attached entity, so you can get list of orders (defined as set) and from a particular order find out list/set of Products.
In case you have Order object available first, then create a bidirectional with User. So that you can find list/set of Products at one end, and Customer associated at other.
For ORM mappings refer Hibernate Mapping Examples.
Hope this clarifies.

Related

Proper way to restrict member value to subset of set

Say I have a person object with a field that is profession, which is simply a list of strings. What is the canonical way, using Spring and hibernate, to restrict this list to only a subset of professions that are defined by either user or the admin? Ie, the list of global, predefined professions at runtime is {Accountant, Developer}, and the user adds 'Plumber' to the list. Now if a new person is created, I'd like to restrict the possible professions that person can have to the 3 that are in the list.
Originally, I implemented an Enum, but this seems like a poor design, as it's generated at compile time, and can't be added to at run time (I think?). Would the proper way be to define a one column table with profession, and at each request to make a person, populate a singleton with one member, which is a list of the professions? Then the domain object person would only source the profession from the singleton (presumably in the service layer?).
You can create a new Entity Profession which is related to Person with a one-to-many relationship. This way a profession is always only what is persisted by Hibernate. The profession entity does not need much. Just an id and name for now. Later you might add more attributes as you need.

one to many association in hibernate

The hibernate documentation gives some rules when we use one-to-many association in Hibernate:
http://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/collections.html#collections-onetomany
A one-to-many association links the tables of two classes via a
foreign key with no intervening collection table. This mapping loses
certain semantics of normal Java collections:
An instance of the contained entity class cannot belong to more than
one instance of the collection.
An instance of the contained entity
class cannot appear at more than one value of the collection index.
Please help me in understanding these statements.
Suppose I have a Product and it has collection of parts, now as per the points what kind of restrictions applied on my Product and its parts?
A Part cannot belong to 2 or more Products
A Part cannot appears more than one time in the Collection of Parts of a Product

Hibernate Master-SubDetails Mapping

I'd like to explore Hibernate and used it in my project instead of JDBC.
My table design is highly normalized.
Suppose, I have this use case: Each insurance applied by a customer has one associated rateplan. Usually, in RDBMS this is implemented using two tables like below.
Table Insurance:
id long;
accountHolder varchar;
ratePlanId int; -->Rate Plan Id is Foreign Key to the RatePlanTable
Table RatePlan:
ratePlanId int;
ratePlanDesc varchar;
discountRate double;
Now, my question is..does this qualify as a onetomany relationship?
Most of the examples that I am seeing on the net regarding onetomany, involves some sort of collections (e.g An Order has a list of products). And when represented in class is translated below, which I think is really a one to many case?
public class Order{
private List products;
}
But how about my case? I don't think that it is a onetomany or I am just mislead by the examples?
How can I do a hbm mapping for my two classes? In my case, I would create two class to represent the two tables, but I am not sure how the hbm.xml would look like for the two class.
Yes, it is a one to many relationship, in that one rate plan is associated with many insurance policies. In entity traversal, when you would go from the Policy, you would get one Plan object, and conversely, from a Plan object, you would get a list of Policy objects.

Unable to persist objects in GAE JDO

I am completely fresh to both JDO and GAE, and have been struggling to get my data layer to persist any code at all!
The issues I am facing may be very simple, but I just cant seem to find any a way no matter what solution I try.
Firstly the problem: (Slightly simplified, but still contains all the info necessary)
My data model is as such:
User:
(primary key)
String emailID
String firstName
Car:
(primary key)
User user
(primary key)
String registration
String model
This was the initial datamodel. I implemented a CarPK object to get a composite primary key of the User and the registration. However that ran into a variety of issues. (Which i will save for another time/question)
I then changed the design as such:
User: (Unchanged)
Car:
(primary key)
String fauxPK (here fauxPK = user.getEmailID() + SEP + registration)
User user
String registration
String model
This works fine for the user, and it can insert and retrieve user objects. However when i try to insert a Car Object, i get the following error:
"Cannot have a java.lang.String primary key and be a child object"
Found the following helpful link about it:
http://stackoverflow.com/questions/2063467/persist-list-of-objects
Went to the link suggested there, that explains how to create Keys, however they keep talking about "Entity Groups" and "Entity Group Parents". But I cant seem to find any articles or sites that explain what are "Entity Group"s or an "Entity Group Parents"
I could try fiddling around some more to figure out if i can store an object somehow, But I am running sort on patience and also would rather understand and implement than vice versa.
So i would appreciate any docs (even if its huge) that covers all these points, and preferably has some examples that go beyond the very basic data modeling.
And thanks for reading such a long post :)
I'm afraid you won't like the answer. GAE JDO has to be used a very specific way and is fraught with limitations that you have to observe to use it effectively. Read the docs forwards and backwards. For the issue you are seeing now, you probably need to read this section a couple of times:
http://code.google.com/appengine/docs/java/datastore/relationships.html
GAE JDO has owned and unowned relationships. See the documentation above for examples of owned vs unowned. I believe you want Car and User to have an unowned relationship. Note this revelation in the Google App Engine documentation about unowned relationships:
http://code.google.com/appengine/docs/java/datastore/relationships.html#Unowned_Relationships
In addition to owned relationships, the JDO API also provides a facility for managing unowned relationships. The App Engine implementation of JDO does not yet implement this facility, but don't worry, you can still manage these relationships using Key values in place of instances (or Collections of instances) of your model objects.
This essentially means, to use GAE JDO, you should not use a direct reference for an unowned relationship like between the Car and User classes. Rather, you should use indirect references between them, i.e. Car should have a field for the User's key rather than a direct reference to the User itself. Some of the trouble you are having is because GAE JDO cannot deal with how you are modeling this relationship in code.
Asker goes on to say:
Went to the link suggested there, that explains how to create Keys, however they keep talking about "Entity Groups" and "Entity Group Parents". But I cant seem to find any articles or sites that explain what are "Entity Group"s or an "Entity Group Parents"
Entity Group - a graph of objects that were initially persisted together. For example, because Car refers directly to a User, when you persist a given Car instance for the first time, then you would also persist the User instance to which it refers and this Car instance and this User instance would be part of the same entity group. If this User instance was already been persisted, either independently by itself or as part of another Car instance, then this User instance is already in another entity group. "Owned" relationships are supposed to be in the same entity group. Note that GAE JDO transactions can modify only 1 entity group - any more will raise an exception.
Entity Group Parent - a top-level/root ("parent") persisted class. In the above example, when you persist a given Car instance for the first time, you would also persist the User instance it refers to. The Car instance is the entity group parent. An "owned" "child" class like User embeds its parent's (Car's) key within its own (User) key. If you were to pull a Car instance from the database and then attempt to access the User that this Car refers to, then the GAE JDO will use the Car's key to find the corresponding User (because the target User's key has the parent Car's key embedded as part of its own key).
Asker got this error message:
"Cannot have a java.lang.String primary key and be a child object"
Note this statement in the docs:
The child class must have a key field whose type can contain the parent key information: either a Key, or a Key value encoded as a string. See Creating Data: Keys for information on key field types.
This means that "child" classes must use certain types of keys (i.e. keys that are capable of encapsulating their parent's key within the child's key). Long and String are suitable for entity group parents classes, i.e. non-child classes. However, "child" classes must use either Key or Key encoded as String type for their key. The error message indicates that the Car class refers to the User class as if it were an "owned" "child" class, and therefore the User class must use an key type appropriate for a child, but the User class is not using a key type appropriate for a child (non-encoded String).
The fix for the immediate problem at hand is to model Car and User to be an unowned relationship by changing Car from having the direct reference to User to instead having an indirect reference by storing the related User's key. The overall fix will likely include taking a hard look at how to fit your object model into GAE JDO's framework (once you wade through the docs to try to understand it). This will likely include having to manually manage some of the relationships between the classes.
If its any consolation, I'm dealing with the same sort of issues with GAE JDO myself (I even have a Car class too!).
Read http://code.google.com/appengine/docs/java/datastore/relationships.html

How do I map a Map from an Entity to a Value with hibernate annotations?

I have Shipment and Product entities. Each shipment consists of any amount of any numbers of products. I.e. a shipment has a field named products which is a java.util.Map where they key is the product being shipped and the value is the number of instances of that product being shipped.
How do I map that to a db with hibernate annotations?
This is what you have to do. The field map belongs to the Shipment class, and it maps each Product to the number of products shipped.
This will not work unless you properly define equals and hashCode methods in the class Product that do not depend on hibernate generated ids. (Or read the full story here).
#CollectionOfElements(targetElement=Integer.class)
#MapKeyManyToMany(targetEntity=Product.class)
private Map<Product, Integer> map = new HashMap<Product, Integer>();
This seems like a bit of an odd design to me, but if I understand correctly you'll want a database schema that has:
a shipment table which has an id
a product table which has a foreign key referencing this id
This is all kind of basic, as the relation is a basic one-to-many relationship from the shipment side and many-to-one on the reverse of course. I could give you examples but really the hibernate docs (scroll down to bottom for a map example) seem to have that covered. Some really hard thinking about how that xml maps to the annotations should tide you over. If you're trying to do it in pure JPA you might turn into some trouble, as the linked example seems to use formula.

Categories