Java Reference
In-Depth Information
Limitations of Hibernate
First and foremost, Hibernate wants every entity to be identifiable with a primary key. Ideally, it
would like this to be a surrogate key (a single column distinct from the fields of the table). Hiber-
nate will accept a primary key that is not a surrogate key. For example, the username column
might be used to uniquely identify an entry in the user table. Hibernate will also accept a com-
posite key as its primary key, so that the username and hostname might be used to form the
primary key if the username alone does not serve to identify the row.
In the real world, things do not really work like that. Any database that has been around
the block a few times is likely to have at least one table for which the primary key has been
omitted. For instance, the contents of the table may not have needed to be involved in any
relations with other tables. While this is still bad database design, the error is only exposed
when Hibernate tries to map objects to data. It may be that adding a suitable surrogate key
column is an option—when this is the case, we urge you to do so. In practice, however, the
fundamental schema may not be under the developer's control, or other applications may
break if the schema is radically changed.
In most scenarios, a developer will be able to arrange the creation of views or stored pro-
cedures. It may be possible to create the appearance of a suitable primary key using these if no
other options present themselves, but you should consult with your database administrators,
since a table for which no true primary key can be obtained is likely to cause long-term cor-
ruption of your data.
Finally, if you can neither change a broken schema nor add views or stored procedures
to ameliorate its effects, you have the option of obtaining a pure JDBC connection (see
Listing A-12) from the session to the database, and carrying out traditional connected data-
base access. This is the option of last resort, and is only truly of value when you anticipate
being able to correct the faulty schema at some future time.
Listing A-12. Obtaining a JDBC Connection from Hibernate
SessionFactory factory =
new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
Connection connection = session.getConnection();
Hand-Rolled SQL
While Hibernate cannot operate upon entities that lack primary keys, it is also extremely awk-
ward to use Hibernate when there is a poor correspondence between the tables and the
classes of your object model.
Using a Direct Mapping
Figure A-1 presents a fairly typical example of a valid database model that may be painful to
represent in our mapping files.
Search WWH ::




Custom Search