views:

20

answers:

1
+1  Q: 

ORM question - JPA

I'm reading Pro JPA 2. The book talks begins by talking about ORM in the first few pages.

It talks about mapping a single Java class named Employee with the following instance variables - id,name,startDate, salary.

It then goes on to the issue of how this class can be represented in a relational database and suggests the following scheme.

table A: emp id - primary key startDate

table B: emp_sal id - primary key in this table, which is also a foreign key referencing the 'id' column in table A.

It thus seems to suggest that persisting an Employee instance to the database would require operations on two(multiple) tables.

Should the Employee class have an instance variable 'salary' in the first place?

I think it should possibly belong to a separate class (Class salary maybe?) representing salary and thus the example doesn't seem very intuitive.

What am I missing here?

+1  A: 

First, the author explains that there are multiples ways to represent a class in a database: sometimes the mapping of a class to a table is straightforward, sometimes you don't have a direct correspondence between attributes and columns, sometimes a single class is represented by multiples tables:

In scenario (C), the EMP table has been split so that the salary information is stored in a separate EMP_SAL table. This allows the database administrator to restrict SELECT access on salary information to those users who genuinely require it. With such a mapping, even a single store operation for the Employee class now requires inserts or updates to two different tables.

So even storing the data from a single class in a database can be a challenging exercise.

Then, he describes how relationships are different. At the object level model, you traverse objects via their relations. At the relational model level, you use foreign keys and joins (sometimes via a join table that doesn't even exist at the object model level).

Inheritance is another "problem" and can be "simulated" in various ways at the relational model level: you can map an entire hierarchy into a single table, you can map each concrete class to its own table, you can map each class to its own table.

In other words, there is no direct and unique correspondence between an object model and a relational model. Both rely on different paradigms and the fit is not perfect. The difference between both is known as the impedance mismatch, which is something ORM have to deal with (allowing the mapping between an object model and the many possible representations in a relation model). And this is what the whole section you're reading is about. This is also what you missed :)

Pascal Thivent