| Recent Entries |
| Seam News | (206) |
| Seam | (130) |
| Hibernate | (113) |
| RichFaces | (92) |
| Contexts and Dependency Injection | (87) |
| > Web Beans < | (61) |
| JBoss Tools | (60) |
| News | (57) |
| Eclipse | (56) |
| JavaServer Faces | (55) |
| Ceylon | (46) |
| Core Release | (44) |
| JBoss Tools Eclipse | (44) |
| Weld | (43) |
| Hibernate Search | (41) |
Hibernate3 is now ready for a public test, go get it! It has all (well almost all) features we'll ever need for object/relational mapping, and if it doesn't have it, it's easy to subclass, extend, and implement.
We still have some things left on our TODO for the beta (no release date yet on the final), but it's getting better every day and we might have a very stable first beta. If you want to help, we are still looking for documentation translators.
Incidentally, the Hibernate project is now 1000 days old, if you believe the SourceForge stats . We actually had the Hibernate3 alpha finished for the anniversary, but then Gavin's laptop didn't agree with its owner anymore. At least it was an excuse to finish some website redesign.
P.S. The first copies of Hibernate in Action arrived! Mine was sent to an old address (thats the problem if you need years to finish something) and I'm going to hunt it down now. I already received a Thank You!
email from the finder...
There's been a certain amount of noise recently surrounding simple JDBC frameworks
like iBATIS. I've liked the idea of iBATIS myself, for use in applications which
don't need an object-oriented domain model, and don't work with deep graphs of
associated entities in a single transaction. A JDBC framework also makes good sense
if you are working with some kind of insane
legacy database; ORM solutions tend
to assume that associations are represented as nice clean foreign keys with proper
referential integrity constraints (Hibernate3 much less so than Hibernate 2.x).
Some people even suggest that JDBC frameworks are a suitable alternative to ORM,
even for those systems to which ORM is best suited: object-oriented applications
with clean relational schemas. They argue that you are /always/ better off with
hand-written SQL than generated SQL. Well, I don't think this is true, not only
because the overwhelming bulk of SQL code needed by most applications is of the
tedious kind, and simply does not require human intervention, but also because a
JDBC framework operates at a different semantic level to ORM. A solution like iBATIS
knows a lot less about the semantics of the SQL it is issuing, and of the resulting
datasets. This means that there is much less opportunity for performance optimizations
such as effficent caching. (By efficient
, I am referring mainly to efficient cache
/invalidation strategies, which are crucial to the usefulness of the cache/.)
Furthermore, whenever we have seen handwritten SQL, we have seen N+1 selects problems.
It is extremely tedious to write a new SQL query for each combination of associations
I might need to fetch together. HQL helps /significantly/ here, since HQL is much
less verbose than SQL. For a JDBC framework to be able to make the kind of
optimizations that an ORM can make, it would have to evolve to a similar level of
sophistication. Essentially, it would need to become an ORM, minus SQL generation.
In fact, we already start to see this evolution taking place in existing JDBC
frameworks. This begins to erode one of the stated benefits: the claimed simplicity.
It also raises the following interesting thought: if, by gradually adding stuff, a JDBC framework will eventually end up as ORM, minus SQL generation, why not just take an existing ORM solution like, ooh, um ... Hibernate, maybe ... and subtract the SQL generation?
The Hibernate team has long recognized the need to mix and match generated SQL with the occasional handwritten query. In older versions of Hibernate, our solution was simply to expose the JDBC connection Hibernate is using, so you can execute your own prepared statement. This started to change a while ago, and Max Andersen has recently done a lot of work on this. Now, in Hibernate3, it is possible to write an entire application with no generated SQL, while still taking advantage of all of Hibernate's other features.
Do we really expect or intend people to use Hibernate in this way? Well, not really - I doubt there are many people out there who really enjoy writing tedious INSERT, UPDATE, DELETE statements all day. On the other hand, we do think that quite a few people need to customize the occasional query. But to prove a point, I'll show you how you can do it, if you really want to.
Let's take a simple Person-Employment-Organization domain model. (You can find the code in the org.hibernate.test.sql package, so I'm not going to reproduce it here.) The simplest class is Person; here's the mapping:
<class name="Person" lazy="true">
<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="name" not-null="true"/>
<loader query-ref="person"/>
<sql-insert>INSERT INTO PERSON (NAME, ID) VALUES ( UPPER(?), ? )</sql-insert>
<sql-update>UPDATE PERSON SET NAME=UPPER(?) WHERE ID=?</sql-update>
<sql-delete>DELETE FROM PERSON WHERE ID=?</sql-delete>
</class>
The first thing to notice is the handwritten INSERT, UPDATE and DELETE statements. The ? order of the parameters matches to the order in which properties are listed above (we'll have to eventually support named parameters, I suppose). I guess there is nothing especially interesting there.
More interesting is the <loader> tag: it defines a reference to a named query which is to be used anytime we load a person using get(), load(), or lazy association fetching. In particular, the named query might be a native SQL query, which it is, in this case:
<sql-query name="person">
<return alias="p" class="Person" lock-mode="upgrade"/>
SELECT NAME AS {p.name}, ID AS {p.id} FROM PERSON WHERE ID=? FOR UPDATE
</sql-query>
(A native SQL query may return multiple columns
of entities; this is the simplest
case, where just one entity is returned.)
Employment is a bit more complex, in particular, not all properties are included in the INSERT and UPDATE statements:
<class name="Employment" lazy="true">
<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
<many-to-one name="employee" not-null="true" update="false"/>
<many-to-one name="employer" not-null="true" update="false"/>
<property name="startDate" not-null="true" update="false"
insert="false"/>
<property name="endDate" insert="false"/>
<property name="regionCode" update="false"/>
<loader query-ref="employment"/>
<sql-insert>
INSERT INTO EMPLOYMENT
(EMPLOYEE, EMPLOYER, STARTDATE, REGIONCODE, ID)
VALUES (?, ?, CURRENT_DATE, UPPER(?), ?)
</sql-insert>
<sql-update>UPDATE EMPLOYMENT SET ENDDATE=? WHERE ID=?</sql-update>
<sql-delete>DELETE FROM EMPLOYMENT WHERE ID=?</sql-delete>
</class>
<sql-query name="employment">
<return alias="emp" class="Employment"/>
SELECT EMPLOYEE AS {emp.employee}, EMPLOYER AS {emp.employer},
STARTDATE AS {emp.startDate}, ENDDATE AS {emp.endDate},
REGIONCODE as {emp.regionCode}, ID AS {emp.id}
FROM EMPLOYMENT
WHERE ID = ?
</sql-query>
The mapping for Organization has a collection of Employments:
<class name="Organization" lazy="true">
<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="name" not-null="true"/>
<set name="employments"
lazy="true"
inverse="true">
<key column="employer"/> <!-- only needed for DDL generation -->
<one-to-many class="Employment"/>
<loader query-ref="organizationEmployments"/>
</set>
<loader query-ref="organization"/>
<sql-insert>
INSERT INTO ORGANIZATION (NAME, ID) VALUES ( UPPER(?), ? )
</sql-insert>
<sql-update>UPDATE ORGANIZATION SET NAME=UPPER(?) WHERE ID=?</sql-update>
<sql-delete>DELETE FROM ORGANIZATION WHERE ID=?</sql-delete>
</class>
Not only is there a <loader> query for Organization, but also for its collection of Employments:
<sql-query name="organization">
<return alias="org" class="Organization"/>
SELECT NAME AS {org.name}, ID AS {org.id} FROM ORGANIZATION
WHERE ID=?
</sql-query>
<sql-query name="organizationEmployments">
<return alias="empcol" collection="Organization.employments"/>
<return alias="emp" class="Employment"/>
SELECT {empcol.*},
EMPLOYER AS {emp.employer}, EMPLOYEE AS {emp.employee},
STARTDATE AS {emp.startDate}, ENDDATE AS {emp.endDate},
REGIONCODE as {emp.regionCode}, ID AS {emp.id}
FROM EMPLOYMENT empcol
WHERE EMPLOYER = :id AND DELETED_DATETIME IS NULL
</sql-query>
When I was writing this code, I really started to feel the advantages of having Hibernate write the SQL for me. In just this simple example, I would have eliminated more than 35 lines of code that I would have to later maintain.
Finally, for ad hoc querying, we can use a native SQL query (a named query, or one embedded in the Java code). For example:
<sql-query name="allOrganizationsWithEmployees">
<return alias="org" class="Organization"/>
SELECT DISTINCT NAME AS {org.name}, ID AS {org.id}
FROM ORGANIZATION org
INNER JOIN EMPLOYMENT e ON e.EMPLOYER = org.ID
</sql-query>
Personally, I prefer to program in Java than in XML, so all this stuff is much too XML-heavy for my liking. I think I'll stick with SQL generation, wherever I can, which is almost everywhere. It's not that I don't like SQL. In fact, I am a great fan of SQL, and just love watching the queries scroll past when I turn Hibernate's logging on. It's just that Hibernate is much better at writing SQL than I am.
Just had an interesting discussion on ejb3-feedback@sun.com, started by David Cherryhomes, which saw me stupidly insistingthat something can't be done when in fact, now that I think about it, /I realize I've actually done it before/, and that even the Hibernate AdminApp example uses this pattern!
So, just so I don't forget this pattern again, I'm going to write it down, and also write a reuseable class implementing it.
The basic problem is pagination. I want to display next
and previous
buttons to the user, but disable them if there are
no more, or no previous query results. But I don't want to retrieve all the query results in each request, or execute a
separate query to count them. So, here's the correct approach:
public class Page {
private List results;
private int pageSize;
private int page;
public Page(Query query, int page, int pageSize) {
this.page = page;
this.pageSize = pageSize;
results = query.setFirstResult(page * pageSize)
.setMaxResults(pageSize+1)
.list();
}
public boolean isNextPage() {
return results.size() > pageSize;
}
public boolean isPreviousPage() {
return page > 0;
}
public List getList() {
return isNextPage() ?
results.subList(0, pageSize-1) :
results;
}
}
You can return this object to your JSP, and use it in Struts, WebWork or JSTL tags. Getting a page in your persistence logic is as simple as:
public Page getPosts(int page) {
return new Page(
session.createQuery("from Posts p order by p.date desc")
page,
40
);
}
The Page class works in both Hibernate and EJB 3.0.
Another major change in Hibernate3 is the evolution to use an event and listener paradigm as its core processing model. This allows very fine-grained hooks into Hibernate internal processing in response to external, application initiated requests. It even allows customization or complete over-riding of how Hibernate reacts to these requests. It really serves as an expansion of what Hibernate tried to acheive though the earlier Interceptor, Lifecycle, and Validatable interafaces.
Note: The Lifecycle and Validatable interfaces have been moved to the new classic
package in Hibernate3. Their use is not encouraged, as it introduces
dependencies on the Hibernate library into the users domain model and can
be handled by a custom Interceptor or through the new event model external to
the domain classes. This is nothing new, as the same recomendation was made
in Hibernate2 usage.
So what types of events does the new Hibernate event model define? Essentially all of the methods of the org.hibernate.Session interface correlate to an event. So you have a LoadEvent, a FlushEvent, etc (consult the configuration DTD or the org.hibernate.event package for the full list of defined event types). When a request is made of one of these methods, the Hibernate session generates an appropriate event and passes it to the configured event listener for that type. Out-of-the-box, these listeners implement the same processing in which those methods always resulted. However, the user is free to implement a customization of one of the listener interfaces (i.e., the LoadEvent is processed by the registered implemenation of the LoadEventListener interface), in which case their implementation would be responsible for processing any load() requests made of the Session.
These listeners should be considered effectively singletons; meaning, they are shared between requests, and thus should not save any state as instance variables. The event objects themselves, however, do hold a lot of the context needed for processing as they are unique to each request. Custom event listeners may also make use of the event's context for storage of any needed processing variables. The context is a simple map, but the default listeners don't use the context map at all, so don't worry about over-writing internally required context variables.
A custom listener should implement the appropriate interface for the event it wants to process and/or extend one of the convenience base classes (or even the default event listeners used by Hibernate out-of-the-box as these are declared non-final for this purpose). Custom listeners can either be registered programatically through the Configuration object, or specified in the Hibernate configuration XML (declarative configuration through the properties file is not supported). Here's an example of a custom load event listener:
public class MyLoadListener extends DefaultLoadEventListener {
// this is the single method defined by the LoadEventListener interface
public Object onLoad(LoadEvent event, LoadEventListener.LoadType loadType)
throws HibernateException {
if ( !MySecurity.isAuthorized( event.getEntityName(), event.getEntityId() ) ) {
throw MySecurityException("Unauthorized access");
}
return super.onLoad(event, loadType);
}
}
Then we need a configuration entry telling Hibernate to use our listener instead of the default listener:
<hibernate-configuration>
<session-factory>
...
<listener type="load" class="MyLoadListener"/>
</session-factory>
</hibernate-configuration>
Or we could register it programatically:
Configuration cfg = new Configuration(); cfg.getSessionEventListenerConfig().setLoadEventListener( new MyLoadListener() ); ....
Listeners registered declaratively cannot share instances. If the same class name is used in multiple <listener/> elements, each reference will result in a seperate instance of that class. If you need the capability to share listener instances between listener types you must use the programatic registration approach.
Why implement an interface and define the specific type during configuration? Well, a listener implementation could implement multiple event listener interfaces. Having the type additionally defined during registration makes it easier to turn custom listeners on or off during configuration.
Hibernate3 adds the ability to pre-define filter criteria and attach those filters at both a class and a collection level. What's a pre-defined filter criteria
? Well, it's the ability to define a limit clause very similiar to the existing where
attribute available on the class and various collection elements. Except these filter conditions can be parameterized! The application can then make the decision at runtime whether given filters should be enabled and what their parameter values should be.
Configuration
In order to use filters, they must first be defined and then attached to the appropriate mapping elements. To define a filter, use the new <filter-def/> element within a <hibernate-mapping/> element:
<filter-def name="myFilter">
<filter-param name="myFilterParam" type="string"/>
</filter-def>
Then, this filter can be attched to a class:
<class name="myClass" ...>
...
<filter name="myFilter" condition=":myFilterParam = my_filtered_column"/>
</class>
or, to a collection:
<set ...>
<filter name="myFilter" condition=":myFilterParam = my_filtered_column"/>
</set>
or, even to both (or multiples of each) at the same time!
Usage
In support of this, a new interface was added to Hibernate3, org.hibernate.Filter, and some new methods added to org.hibernate.Session. The new methods on Session are: enableFilter(String filterName), getEnabledFilter(String filterName), and disableFilter(String filterName). By default, filters are not enabled for a given session; they must be explcitly enabled through use of the Session.enabledFilter() method, which returns an instance of the new Filter interface. Using the simple filter defined above, this would look something like:
session.enableFilter("myFilter").setParameter("myFilterParam", "some-value");
Note that methods on the org.hibernate.Filter interface do allow the method-chaining common to much of Hibernate.
Big Deal
This is all functionality that was available in Hibernate before version 3, right? Of course. But before version 3, this was all manual processes by application code. To filter a collection you'd need to load the entity containing the collection and then apply the collection to the Session.filter() method. And for entity filtration you'd have to write stuff that manually modified the HQL string by hand or a custom Interceptor.
This new feature provides a clean and consistent way to apply these types of constraints. The Hibernate team envisions the usefulness of this feature in everything from internationalization to temporal data to security considerations (and even combinations of these at the same time) and much more. Of course it's hard to envision the potential power of this feature given the simple example used so far, so let's look at some slightly more in depth usages.
Temporal Data Example
Say you have an entity that follows the effective record
database pattern. This entity has multiple rows each varying based on the date range during which that record was effective (possibly even maintained via a Hibernate Interceptor). An employment record might be a good example of such data, since employees might come and go and come back again. Further, say you are developing a UI which always needs to deal in current records of employment data. To use the new filter feature to acheive these goals, we would first need to define the filter and then attach it to our Employee class:
<filter-def name="effectiveDate">
<filter-param name="asOfDate" type="date"/>
</filter-def>
<class name="Employee" ...>
...
<many-to-one name="department" column="dept_id" class="Department"/>
<property name="effectiveStartDate" type="date" column="eff_start_dt"/>
<property name="effectiveEndDate" type="date" column="eff_end_dt"/>
...
<!--
Note that this assumes non-terminal records have an eff_end_dt set to a max db date
for simplicity-sake
-->
<filter name="effectiveDate" condition=":asOfDate BETWEEN eff_start_dt and eff_end_dt"/>
</class>
<class name="Department" ...>
...
<set name="employees" lazy="true">
<key column="dept_id"/>
<one-to-many class="Employee"/>
<filter name="effectiveDate" condition=":asOfDate BETWEEN eff_start_dt and eff_end_dt"/>
</set>
</class>
Then, in order to ensure that you always get back currently effective records, simply enable the filter on the session prior to retrieving employee data:
Session session = ...;
session.enabledFilter("effectiveDate").setParameter("asOfDate", new Date());
List results = session.createQuery("from Employee as e where e.salary > :targetSalary")
.setLong("targetSalary", new Long(1000000))
.list();
In the HQL above, even though we only explicitly mentioned a salary constraint on the results, because of the enabled filter the query will return only currently active employees who have a salary greater than a million dollars (lucky stiffs).
Even further, if a given department is loaded from a session with the effectiveDate
filter enabled, its employee collection will only contain active employees.
Security Example
Imagine we have an application that assigns each user an access level, and that some sensitive entities in the system are assigned access levels (way simplistic, I understand, but this is just illustration). So a user should be able to see anything where their assigned access level is greater than that assigned to the entity they are trying to see. Again, first we need to define the filter and apply it:
<filter-def name="accessLevel">
<filter-param name="userLevel" type="int"/>
</filter-def>
<class name="Opportunity" ...>
...
<many-to-one name="region" column="region_id" class="Region"/>
<property name="amount" type="Money">
<column name="amt"/>
<cloumn name="currency"/>
</property>
<property name="accessLevel" type="int" column="access_lvl"/>
...
<filter name="accessLevel"><![CDATA[:userLevel >= access_lvl]]></filter>
</class>
<class name="Region" ...>
...
<set name="opportunities" lazy="true">
<key column="region_id"/>
<one-to-many class="Opportunity"/>
<filter name="accessLevel"><![CDATA[:userLevel >= access_lvl]]></filter>
</set>
...
</class>
Next, our application code would need to enable the filter:
User user = ...;
Session session = ...;
session.enableFilter("accessLevel").setParameter("userLevel", user.getAccessLevel());
At this point, loading a Region would filter its opportunities collection based on the current user's access level:
Region region = (Region) session.get(Region.class, "EMEA"); region.getOpportunities().size(); // <- limited to those accessible by the user's level
Conclusion
These were some pretty simple examples. But hopefully, they'll give you a glimpse of how powerful these filters can be and maybe sparked some thoughts as to where you might be able to apply such constraints within your own application. This can become even more powerful in combination with various interception methods, like web filters, etc. Also a note: if you plan on using filters with outer joining (either through HQL or load fetching) be careful of the direction of the condition expression. Its safest to set this up for left outer joining; in general, place the parameter first followed by the column name(s) after the operator.
|
|
|
Showing 1011 to 1015 of 1050 blog entries |
|
|