Hibernate, how to model this relationship - mysql

I have the below tables.
create table logical_id_seq (
logical_id int auto_increment,
primary key(logical_id)
);
create table mytable (
physical_id int auto_increment,
logical_id int not null references parent(logical_id),
data varchar(20),
primary key(physical_id)
);
The second table uses first table auto-generated value as its value. I am not sure how to model this in hibernate.
I read http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-onetoone, but I doesn't seem to understand.

It's actually hard to say, I don't know what you want to represent at the object level: is it a one-to-one foreign key association? a many-to-one association? is the association bi-directional? Using an ORM means thinking objects more than tables and it usually help to provide the object model.
I'll assume this is a one-to-one foreign key association. Here is what Java Persistence with Hibernate recommends:
7.1.2 One-to-one foreign key associations
Instead of sharing a primary key, two
rows can have a foreign key
relationship. One table has a foreign
key column that references the primary
key of the associated table. (The
source and target of this foreign key
constraint can even be the same table:
This is called a self-referencing
relationship.)
Let’s change the mapping from a User
to an Address. Instead of the shared
primary key, you now add a
SHIPPING_ADDRESS_ID column in the
USERS table:
<class name="User" table="USERS">
<many-to-one name="shippingAddress"
class="Address"
column="SHIPPING_ADDRESS_ID"
cascade="save-update"
unique="true"/>
</class>
The mapping element in XML for this
association is <many-to-one> — not
<one-to-one>, as you might have
expected. The reason is simple: You
don’t care what’s on the target side
of the association, so you can treat
it like a to-one association without
the many part. All you want is to
express “This entity has a property
that is a reference to an instance of
another entity” and use a foreign key
field to represent that relationship.
The database schema for this mapping
is shown in figure 7.3.
Figure 7.3 A one-to-one foreign
key association between USERS and
ADDRESS
An additional constraint enforces this
relationship as a real one to one. By
making the SHIPPING_ADDRESS_ID
column unique, you declare that a
particular address can be referenced
by at most one user, as a shipping
address. This isn’t as strong as the
guarantee from a shared primary key
association, which allows a particular
address to be referenced by at most
one user, period. With several foreign
key columns (let’s say you also have
unique HOME_ADDRESS_ID and
BILLING_ADDRESS_ID), you can
reference the same address target row
several times. But in any case, two
users can’t share the same address for
the same purpose.
Let’s make the association from User
to Address bidirectional.
Inverse property reference
The last foreign key association was
mapped from User to Address with
<many-to-one> and a unique
constraint to guarantee the desired
multiplicity. What mapping element can
you add on the Address side to make
this association bidirectional, so
that access from Address to User is
possible in the Java domain model?
In XML, you create a <one-to-one>
mapping with a property reference
attribute:
<one-to-one name="user"
class="User"
property-ref="shippingAddress"/>
You tell Hibernate that the user
property of the Address class is the
inverse of a property on the other
side of the association. You can now
call anAddress.getUser() to access
the user who’s shipping address you’ve
given. There is no additional column
or foreign key constraint; Hibernate
manages this pointer for you.
If what you have is actually a real many-to-one association, it should be pretty easy to adapt the above solution.

Related

polymorphic association alternative

I'm trying to design a part of my database which should cover users login. My users can login with "local", "facebook" or "google" account.
What I have is a table users that contains two columns, login_type login_id.
The values of login_type can be "local", "facebook" or "google" which refers to three tables: local, facebook and google.
login_id is the id of the login_type referenced table.
I don't like this polymorphic association and would redesign this part to keep the database simple and coherent by creating tables that references as usual with foreign key.
Appreciate any suggestion
Regards
What you are doing is a trick known in Object Relational Mapping (ORM) systems as a discriminator column. The problem with it, as you already understand, is that referential integrity goes out the window, because you cannot declare your login_id as being a foreign key that maps to another table, because it may map to one of three possible tables, and the table that it maps to is chosen by the value of the login_type column.
The way to do this correctly might seem a bit strange, but it does guarantee referential integrity.
Table users columns:
id primary key
local_users_id foreign key, references local_users(id)
facebook_users_id foreign key, references facebook_users(id)
google_users_id foreign key, references google_users(id)
So, the login_type column is abandoned, and instead you introduce three nullable foreign keys: local_users_id, facebook_users_id, and google_users_id. Only one of them may be non-null.
You can make sure that only one of them is non-null in code, or even in the database, with a trigger or perhaps even with a constraint.

What is adding a new relationship to an existing table called?

In database terms, when i add a new foreign key, insert a record for that foreign key and update the existing record, what is the process called? My goal is to be able to find answers more effectively.
//create temporary linking key
alter table example add column example_foreign_key int unsigned null;
//contains more fields
insert into example_referenced_table (example_id, ...)
select id, ...
from example
join ...;
//link with the table
update example join example_referenced_table on example_id = example.id
set example.example_foreign_key = example_referenced_table.id;
//drop linking key
alter table example_referenced_table drop column example_id;
It looks like you're substituting one surrogate identifier for another. Introducing a surrogate key is sometimes (incorrectly) called normalization, so you may get some hits on that term.
In rare cases, normalization requires the introduction of a surrogate key, but in most cases, it simply decomposes a relation (table) into two or more, in such a way that no information is lost.
Surrogate keys are generally used when a natural or candidate key doesn't exist, isn't convenient, or not supported (e.g. composite keys are often a problem for object-relational mappers). For criteria on picking a good primary key, see: What are the design criteria for primary keys
There's little value in substituting one surrogate identifier for another, so the procedure you demonstrate has no proper name as far as I know, at least in the relational model.
If you mean to introduce a surrogate key as an identifier of a new entity set to which the original attribute is transferred, that's close to what Peter Chen called shifting a value set from the lower conceptual domain to the upper conceptual domain. You can find more information in his paper "The entity-relationship model - A basis for the enterprise view of data".
As for your question's title, it's not wrong to say that you're adding a relationship to a table (though that wording mixes conceptual and physical terms), but note that in the entity-relationship model, a relationship is represented by a two or more entity keys in a table (e.g. (id, example_foreign_key) in the example table) and not by a foreign key constraint between tables. The association of relationships with foreign key constraints came from the network data model, which is older than both the relational and entity-relationship models.

Cardinality and foreign key relationship

I am new to database design and am trying to understand the best practice for using foreign keys. I know that when you have a 1:m relationship, we don't have to create a relation for the relationship; instead we could add a foreign key to the m-side of the relationship(which corresponds to the primary key on the 1-side) so as to preserve referential integrity. My question however is: Under what other circumstances could we do the same? Can we do the same when we have a 0..1 to 1 or 1-1 relationship as well? What is the best practice for this type of situation when referential integrity is as important as the computational cost?
There are three possible approaches when we are mapping 1:1 relation to Relational Model:
Foreign Key approach: Choose one of the relations-say S-and include a
foreign key in S the primary key of T. It is better to choose an entity type
with total participation in R in the role of S.
Merged relation option: An alternate mapping of a 1:1 relationship type
is possible by merging the two entity types and the relationship into a
single relation. This may be appropriate when both participations are
total.
Cross-reference or relationship relation option: The third alternative
is to set up a third relation R for the purpose of cross-referencing the
primary keys of the two relations S and T representing the entity types.
For more details you can look into this home.iitj.ac.in/~ramana/ch7-mapping-ER-EER-relations.pdf
Foreign key constraints are restrictions, not references. A relation exists implicitly wherever different columns represent the same domain, and their tables can be joined, with or without foreign keys. The constraint just ensures that the values/entities stored in one column exists in another column. They're appropriate to use wherever a relation is dependent on another, regardless of the cardinality of either. The typical use case here is subtyping of entity sets.
The main benefits of foreign key constraints is the performance gains (reduced calls across the wire as well as development time) enabled by cascading updates/deletes from a single statement instead of having to query for an ID before executing multiple update/delete statements wrapped in a transaction. Not to mention repair time if changes weren't propagated properly.
the M-to-M relationship is equivalent to two 1:M relationships .we can not assign primary key of 1 side as a foreign key of other for this purpose we use a middle entitiy that resolve an M:M and that entity is tipically called "association " or intersection entity. e.g A M:M relationship between project and employee a new midlle entity can be assignment so in this way the relation will convert into 1:M and we can assign a foreign key easilly

innodb non-identifying foreign key requires key to be present?

i am creating a database with a EER Diagram and used non-identifying foreign key relationships to create my foreign key.
what i need for my foreign keys:
Default values should be 0 and should be used when no value is given for the FK
the presences of the keys in the related table should not be required
dont allow null values
what i get when synchronizing data models:
Default values are not synced to DB from EER Diagram
Default values are not used when implemented manually
the presences of the keys in the related table are required
FK fields dont allow nulls (yay!)
what am i doing wrong? i tought i had read on the web that non-identifying Foreign keys did what i needed? if everything fails i could create simple columns and only put an index on em but i tought it could be handy in the future to use foreign keys plus it looks better in my EER Diagram.
A non-identifying Foreign key means that your entity can exists without relation to the other entity, and you got it.
But technically in mysql this is achived by using null and not 0, which means instead "linked to an entity with ID=0"

Foreign Keys vs. Partial Keys and their E-R representations

I'm having trouble understanding the difference between partial keys/weak entities and foreign keys. I feel like an idiot for not being able to understand this stuff.
As I understand it:
Weak Entity: An entity that is dependent on another entity.
Partial Key: Specifies a key that that is only partially unique. Used for weak entities.
vs
Foreign Key: A key that is used to establish and enforce a relation between data in different tables.
These don't seem like they're the same thing, but I'm having trouble distinguishing their uses.
Take the [very] simple example:
We have employees specified by an empid. We also have children specified by name. A
child is uniquely specified by name when the parent (employee) is known.
Would the child entity be a weak identity where the partial key is the name (partially unique)? Or should I be using a foreign key because I'm trying to establish and enforce a relation between employee and child? I feel like I can justify both, but I also feel like I'm missing something here. Any insight is appreciated, and I apologize for the stupid questions.
The problem is not you, it is that the ancient textbook or whatever you are using is pure excreta, the "definitions" are not clear, and there have been standard definitions for Relational Databases in use for over 30 years, which are much more clear. The "definitions" you have posted are in fact quite the opposite, non-intuitive, and it is no surprise that people would get confused.
A Foreign Key in a child row, is the value that references its parent Primary Key (in the parent table).
Using IDEF1X terminology. An Identifying Relation is one in which the FK (the parent Pk in the child) is also used to form the child PK. It is unique in the parent, but not unique in the child, you need to add some column to make it unique. Hence the stupid term "Partial Key". Either it is a Key (unique) or it is not a Key; the concept of a "partial Key" is too stupid to contemplate.
In a properly Normalised and standard-compliant database, there will be very few Independent entities. All the rest will be Dependent on some Independent entity. Such entities are not "weak", except in the sense that they cannot exist without the entity that they are Dependent upon.
The use of Identifying Relations (as opposed to Non-identifying) is actually strong; it gives the Dependent ("weak") entities their Identifier. So silly terms like "weak" and "strong" should not be used in a science that demands precision.
Use standard terms.
But to answer your explicit question:
assuming that Employee is "strong" and has a Primary Key (EmployeeId)
then the "weak" EmployeeChild table would need a FK (EmployeeId) to identify the Employee
which would be the perfect first component of the EmployeeChild table, the adorable "partial key"
to which you might add ChildNo, in order to make an ordinary Relational Primary Key
but it is not really "partial" because it is the full Primary Key of the Parent.
Readers who are unfamiliar with the Standard for Modelling Relational Databases may find ▶IDEF1X Notation◀ useful.
A weak entity type is one whose primary key includes some attribute(s) that reference another entity. In other words a foreign key is a subset of the primary key. Therefore the entity cannot exist without its parent.
A partial key means just part of a key - some proper subset of the key attributes.
In your example if the primary key of a Child was (Empid, ChildName) with Empid as a foreign key referencing the Employee then Child is a weak entity. If Empid was not part of the primary key then Child would be a strong entity.
It's worth bearing in mind that the weak/strong distinction is purely an ER modelling concept. In relational database terms it doesn't make much difference. In particular the relational model doesn't make any distinction between primary keys and other candidate keys so for all practical purposes it doesn't make any difference to single out primary key attributes as being a "special" case when they reference other tables.
Suppose there is a relation between two entity Employees and Dependents. Employees is strong entity and Dependents is weak entity. Dependents have attributes Name, Age, Relation and Employees have attributes E_Id (primary key) and E_Name.
Then to satisfy relation we use foreign key E_Id in Dependents table which refers to the E_Id of Employees table.
But by using only foregin key we can't identify the tuples uniquely in Dependents table we require Name(partial key) attribute also to identify the tuples uniquely.
Example : suppose Dependents table has values in Name are Rahul, Akshat, Rahul then it will not unique and when it combine with E_Id then we can identify it uniquely.
E_Id with Name acts as primary key in Dependents table.