Red Hat

In Relation To

The Hibernate team blog on everything data.

Not so Naked Objects

Posted by    |       |    Tagged as

Currently I have noticed that Naked Objects gets more and more blog-time. And every time I wondered why (many?) people found it so intriguing - and I often thought about making a blog about the good and bad about Naked Objects; but I've never found the time.

I still don't have the time to do a detailed blog about it, but just state some facts and/or criticism about the implementation of Naked Objects that I've can't remember seeing listed before.

A. All objects has to implement NakedObject or extend AbstractNakedObject (actually some code in the framework assumes every object is an AbstractNakedObject...but that I guess they will fix a some point).

B. All fields that you want the framework to know about need to be a NakedValue, thus String has to be a TextString, float a FloatingPointNumber, etc. This is all basically done to let the values be mutable and add all the linguistic needs for their (all to easy to criticize, so I won't) automatic GUI.

C. All collections of associated objects need to be NakedCollection which definitly is not in any way a standard java.util.Collection (because they also do not use anything from jdk 1.2, just to be able to run on .Net!).

Each of point A, B and C makes me not like the Naked Objects framework (at least the implementation)! Why ? Because all my objects won't be POJO's anymore - and especially item C, makes it very hard to e.g. use Hibernate (or many other reflection based ORM's) to persist these not so Naked Objects. It at least require some very specific Naked Object code to make it work.

And when we are talking about persistence, then the whole framework does have a built-in persistence engine which is pluggable - but it's very simple, and transaction demarcation looks very hard to control, if even possible at the moment.

But enough harsh criticism ;), the good stuff is their ideas about behavioral complete objects (BCO). From the book: an object should completely model the behavior of the thing that it represents. ... most people continue to design business systems that separate procedure from data, albeit dressed up in the language and technology of object-orientation.

And I do agree to that point - people do get to procedural at times, myself included, and if Naked Objects help us do that a little less I would appreciate it.

Their automatic (and empowering to the users as they call it) UI, is somewhat interesting - but geez, they seriously got to look more into ui design ;) (and yes, I know they did look into ui design to empower their users, but I simply don't think their UI has value in other areas besides being provocative and different ;)

And as I understand the authors then it is the BCO and the automatic created UI that is their focal point, but I don't understand why they have not utilized existing technologies that is close to almost do the same....like the JavaBeans API ? JavaBeans is more than just a naming standard for properties! It was build for allowing IDE's to inspect objects and build intelligent UI's!

It got an Introspection API which one could use to discover all the details of an object and the API is extensible in a much more non-intrusive way than Naked Object does it.

What about using standard property listeners ? Why limit you to use jdk 1.1 ? Who want's to only use Vector, and why not utilize the Collections API interfaces to make their object structure much more standard compliant ?

In the end I encourage the authors to work on their core concepts: BCO and automatic UI's (even though I don't think it will cover more than a few useful applications). But they should really look into using more JDK API's for this, so the framework becomes more useful in real-life applications.

P.S. And why is their catch all blocks and printStackTrace() multiple places in the source of a system that candidates for being used in more than just prototype systems ?

Wrestling With Pigs

Posted by    |       |    Tagged as

I have to repeat this cliche to myself at least once a week:

/Never wrestle with a pig; you both get dirty and the pig loves it./

One of the problems with online forums is that, naturally, they are dominated by the people with the most time on their hands - and by the people with the most dogmatic views. As in any community, the loudest views are often the least-informed. When criticized in a forum like TSS , it's usually better to just stay out of the mud. As difficult as it is to let uninformed statements go unchallenged, it is almost always the best decision. Let the pig be. Disputing a post brings attention to it. If the poster is of a particular personality type, the disputation will very quickly turn personal. Maintaining your dignity once that happens is virtually impossible.

In fact, what most amazes me about IT communities is the sheer ubiquity of /argumentum ad hominem/. I've always associated computing with the pursuit of understanding via scientifically inclined methodology. Yet most of the debate that occurs in the Java community consists of name-calling. I got so mad about this today that I broke all my own rules and launched some /ad hominem/ of my own, which is really quite self-defeating, I suppose.

The big problem from my point of view is that I can't simply ignore the online forums; as an open source project they are an absolutely indispensible way for us to get our ideas heard.

Clay Shirky has written insightfully about how online communities can be designed, so it is interesting to speculate about what kind of adjustments could be made to a community like TSS if we wanted to bring out our good sides, and encourage technical arguments rather than personal ones. But perhaps the very strength of TSS is the freewheeling nature of the debate there. Flame wars get attention; they generate the most traffic.

Well, I'm a big boy. Hibernate has been subject to all kinds of outlandish criticisms right from the start. But we are growing every month. We often joke that criticisms of Hibernate invariably begin with I've never used Hibernate but... and indeed that is still true. If our actual /users/ start bitching, /then/ we will need to start listening harder!

Apologies for the nontechnical post ;)

Hibernate 2.1.2

Posted by    |       |    Tagged as Hibernate ORM

I just released 2.1.2 . This is a maintenence release, meaning no especially exciting new features (the interesting work is all going on in the 2.2 branch). However there are some small changes that might make a big performance difference in certain specific cases, especially if you are using a second-level cache. I'm hoping that this release brings the 2.1 branch to the same level of maturity that we were able to achieve with 2.0.3.

Books for free...

Posted by    |       |    Tagged as Java EE

This is a reply on the Hibernate forum, read the full thread for the context.

As some noticed, I'm a bit impulsive about that kind of thing right now. We get one question a day, sometimes friendly, sometimes not so friendly, if we could just set up the book (Hibernate in Action) for free download or simply send it over.

Don't take it personal if I'm getting annoyed about that. It's sometimes just embarrassing when someone gives you the feeling that you owe them something, just because they use Hibernate. I'd like to explain why its not about the money for the book.

First, and that is really my own personal opinion, a professional Java developer should have enough money for whatever book in any case. Books are important, read at least one each month, better two. I don't buy any of that offshore jobs talk, but knowledge is the only thing that keeps you in business. I don't want to discuss $5 Amazon shipping costs about that.

Now I'd like to start a little rant here, so you better stop reading if you are not in the mood :)

Our software is free, our documentation is of course free, and we will always provide free support on a personal level in this forum, and whenever we think it is needed.

I also think that our software and the whole project shows that we are serious about what we are doing. We worked many nights and weekends last year. Gavin and me quit our jobs to make this possible. Max, David, Steve, Emmanuel spend hours a day after work, writing interesting things and answering questions (now up to 120/day) on the forum.

We really believe in professional open source as a business model in the software sector. Actually I'm now also employed by JBoss Group. We have two people working fulltime on Hibernate.

How do we earn our salary?

With open source, there are no license fees. This is great for developers, as they can sell the software they'd like to use to their project managers and accountants easily. Well, of course only if all the other qualities are right:

  • good software
  • good documentation and free support
  • commercial support (risk management)
  • nice extras

A successful vendor of closed software can provide the second for free, but you have to pay for the other three most of the time. Sometimes its hidden, sometimes not. The situation is quite different with an open source software project. First, there are no hidden costs, because you actually can't hide anything. Second, we as software developers don't like hiding any costs somewhere, we are not good with that kind of thing. It's much easier to tell people what they need and what it costs upfront. I also like the look on peoples faces if you admit that Hibernate solves only 95% of their problems, not 100! Shocking! The truth!

It's hard to break with the traditions and I remember the early Linux days when it was first used used commercially. You actually had to tell people that free software is good because they don't pay money for licenses. They wouldn't believe you, just don't ask for a (real) reason. Usually they expected some hidden costs in the other three items and simply denied that it was any good at all.

Sometimes, I think it was too much propaganda back then, now everyone expects everything for free!

To support a business, some revenue must be made from at least one of the four elements I listed.

I'm not talking about the book, because that really doesn't pay. I think most people know that books don't pay in the end, at least if your name is not Fowler or Bloch. Why do we write it then? It helps us to get more people (and therefore ideas and opinions) into Hibernate, and we can finally write down some thoughts we can't express in any other medium.

And yes, we also hope that it will help us to grow the Hibernate business. Thats our job. There is no professional quality without that background, or at least not for a long period of time.

Hibernate is naturally a very open project driven by the users. This will not change, no matter what our business model is. We think that listening to users and balancing requests is the heart of the project, it is the reason why people like it and why it works(tm).

If you are having problems...

Posted by    |       |    Tagged as

I just finished a consulting job at a large retailer where we managed to increase the performance of a Hibernate application by perhaps two orders of magnitude with just some fairly simple changes. It really drove home to me how almost all performance problems I've ever seen can be solved by either or both of:

  • appropriate session handling
  • appropriate association fetching strategies

(Note that I have not yet met a serious performance problem in Hibernate 2.x that I could not solve quite quickly.)

Hibernate's Session object is a powerful abstraction that allows some extremely flexible architectural choices. Unfortunately, this flexibility comes at a cost: many people seem to stuff it up! There are three well-understood patterns for managing Hibernate sessions correctly (actually, three-and-a-half, as I've recently discovered) and three common antipatterns. The fact that the antipatterns are more common than they should be suggests a real problem with our existing documentation, and highlights the fact that /we need to get this book out!/

The main reason we've previously been unable to explain the correct ways to handle Hibernate sessions is that we simply havn't had a decent language for describing our ideas. Since we've developed this language in the process of writing the book, explanations are much easier. The key concept is the notion of an /application transaction/. An application transaction is a unit of work from the point of view of the user; it spans multiple requests and multiple database transactions - it does, however, have a well-defined beginning and end. Even if you don't currently use this notion explicitly, you probably /do/ use it implicitly in your application.

Briefly, the three acceptable approaches are: session-per-request, session-per-request-with-detached-objects and session-per-application-transaction. A variation of the third approach is the newly-discovered session-per-application-transaction-with-flush-delayed-to-the-last-request (phew!). The three broken approaches are: session-per-operation (ie. many-sessions-per-request), session-per-user-session and session-per-application. If you are using any of these approaches, please stop.

The three acceptable approaches each have different performance and architectural implications and there is no best solution. It is incredibly important to choose the approach that is most suitable to your particular application (this was the key to the two-orders-of-magnitude improvement described above).

Association fetching is, I think, covered quite well in our documentation, but we still sometimes see people struggling with the dreaded n+1 SELECTs problem. So let me be very clear: Hibernate /completely/ solves the n+1 SELECTs problem! However, it takes some thought and a (very) little work on the part of the user to take full advantage of this fact. We recommend that all associations be configured for lazy fetching by default. Then, for particular use cases, eager outer join fetching may be chosen by specifying a LEFT JOIN FETCH clause in a HQL query, or by calling setFetchMode() for a Criteria query. (If you are too lazy to do this work, you could even try the new batch fetching features of Hibernate 2.1. We don't recommend this less elegant approach, however.)

Less common performance problems may be fixed by using a second-level cache, or occasionally by managing flushing manually (set the session flush mode to FlushMode.NEVER and flush manually when required). However, in almost all cases, acceptable performance can be achieved by concentrating upon the two items listed above.

Don't lock in the middle tier!

Posted by    |       |    Tagged as

One of the reasons we use relational database technology is that existing RDBMS implementations provide extremely mature, scalable and robust concurrency control. This means much more than simple read/write locks. For example, databases that use locking are built to scale efficiently when a particular transaction obtains /many/ locks - this is called /lock escalation/. On the other hand, some databases (for example, Oracle and PostgreSQL) don't use locks at all - instead, they use the multiversion concurrency model. This sophisticated approach to concurrency is designed to achieve higher scalability than is possible using traditional locking models. Databases even let you specify the required level of transaction isolation, allowing you to trade isolation for scalability.

Unfortunately, some Java persistence frameworks (especially CMP engines) assume that they can improve upon the many years of research and development that has gone into these relational systems by implementing their own concurrency control in the Java application. Usually, this takes the form of a comparatively crude locking model, with the locks held in the Java middle tier. There are three main problems with this approach. First, it subverts the concurrency model of the underlying database. If you have spent a lot of money on your Oracle installation, it seems insane to throw away Oracle's sophisticated multiversion concurrency model and replace it with a (less-scalable) locking model. Second, other (non-Java?) applications that share the same database are not aware of the locks. Finally, locks held in the middle tier do not naturally scale to a clustered environment. Some kind of distributed lock will be needed. At best, distributed locking will be implemented using some efficient group communication library like JGroups. At worst (for example, in OJB), the persistence framework will persist the locks to a special database table. Clearly, both of these solutions carry a heavy performance cost. Accordingly, Hibernate was designed to /not require/ any middle-tier locks - even thread synchronization is avoided. This is perhaps the best and least-understood feature of Hibernate and is the key to why Hibernate scales well. So why do other frameworks not just let the database handle concurrency?

Well, the only good justification for holding locks in the middle tier is that we might be using a middle-tier cache. It turns out that the problem of ensuring consistency between the database and the cache is an extremely difficult one and solutions usually do involve some use of middle-tier locking. (Incidently, most applications which use a cache do not solve this problem correctly, even in a non-clustered environment.)

So, for example, when Hibernate integrates with JBoss Cache, the cache implementation must obtain clustered locks internally (again, using JGroups). In Hibernate, we consider it a quality-of-service concern of the cache implementation to provide this kind of functionality. We can do this because Hibernate, unlike many other persistence layers, features a two-level cache architecture. This design separates the transaction-scoped /session cache/ (which does /not/ require middle-tier locking and delegates concurrency concerns to the database) from the process or cluster scoped /second-level cache/ (which /may/ require middle-tier locks). So when the second-level cache is disabled for a particular class, no middle-tier lock is required. Hence, in this case, the scalability of Hibernate is limited only by the scalability of the underlying database. Our design also allows us to consider other, more sophisticated approaches to ensuring consistency between the second-level cache and database - approaches that do not require the use of middle-tier locking. I'll keep this stuff secret for now; it is an active area of investigation!

Jason's observations

Posted by    |       |    Tagged as

Jason has pointed out some interesting things about the current release of Hibernate.

First, he notes that Hibernate's query cache may not currently be used with SwarmCache. This is due to SwarmCache not being a /replicated/ cache - it uses clustered eviction. Hibernate's query cache may be used with any replicated clustered cache, as long as clocks are synchronized in the cluster. Our documentation should make this requirement clearer. (For most applications, the query cache is not an especially useful feature, so this issue affects only a small number of users.)

Second, he has noticed that Hibernate currently writes to the second-level cache too often. I had not previously been aware of this issue. Hibernate was optimized with local, perhaps disk-backed, cache implementations in mind, where lookups are at least as expensive (in the case of a disk-backed cache, /more/ expensive) than puts. Jason has pointed out that in the case of a clustered cache, this is reversed and puts are much more expensive than lookups. We will provide a switch in a future point release of Hibernate 2.1 to adjust this behavior.

Finally, Jason is unhappy that we are not supporting JDK dynamic proxies and require CGLIB for lazy association fetching. (CGLIB causes problems if the JVM is running with a restrictive security policy.) Well, as I explained to Jason, Hibernate already provides a hook to allow the proxy implementation to be customized using a custom persister. (Dynamic proxy support could be implemented with a very small amount of code.) This evening I actually refactored this stuff slightly and introduced a ProxyFactory interface to make the hook more obvious.

I'd like to point out that the Hibernate project has many thousands of users and just a handful of active developers. As a result, we must prioritize feature requests by two considerations: first, how many users beg for the feature; second, how strategic a feature is with respect to the future direction of the project. We simply do not implement every requested feature since we have limited resources and are fighting a continual battle against code bloat (bloat is a /very/ serious issue if you are the person maintaining and enhancing the codebase). Hibernate is open source, so users with special requirements can always use a patched version in their application. In addition, we do not usually process feature requests via IM or javablogs.com! The correct process is to submit an enhancement request to JIRA (and let other users comment and vote) or, even better, to start a discussion in the mailing list. We may be an open source project; this does not mean that we are completely unprofessional and disorganized!

Criteria queries reloaded

Posted by    |       |    Tagged as

There were quite a few comments in response to my post about Criteria queries. I finally get around to responding. A number of people suggest a more tree-oriented approach, where we treat all logical operators as binary. For example, anonymous suggests the following:

session.createCriteria( Project.class,
  or(
      eq("name", "Hibernate"), 
      like("description", "%ORM%")
  )
);

Now, certainly logical operations are binary. But they are also /associative/, and this seems to be denied by the tree approach. We would never, ever write:

( (x=2 and x=1) and y=3 ) and z=4

We always write:

x=2 and x=1 and y=3 and z=4

This is particularly relevant in the case of Criteria queries since the common case is that we compose together many conditions using conjunction. (There were objections to my use of conjunction and disjunction, but I don't know of any other word for a string of expressions composed with and/or.)

Actually, the current API /does/ already allow this alternative. We have Expression.or() and Expression.and(). But to me they seem to be much messier than add().

Carl Rosenberger, the man behind SODA and db4o writes:

In my opinion a clean object querying system is the first and foremost 
basis for any standard on object persistence. 

Enhancers/Reflection/BCEL/code calls to make objects persistent 
all this can be very quickly exchanged, if you want to switch the 
underlying system.

Queries can not be exchanged!

And I couldn't possibly agree more! This is absolutely right. He goes on to say:

Could you maybe bring this thought into JDO 2.0 ? Please ?

Besides, I am positive that a de-facto standard for object querying will 
have a much greater impact on the industry than JDO.
Java is not the only programming language on this planet. 

In fact, I've mentioned the idea of adopting a better query approach to a couple of the guys on the expert group, but didn't get much of a positive response. Besides, I'm not at all convinced that it is even possible to design a nice query language or API in a committee environment. These kind of things need a strong unified vision. Comittees are okay at standardizing mature solutions to well-understood problems, but it is my view that object-oriented querying is a far from well understood problem. Especially, it does not seem to be commonly appreciated that an ORM-oriented query language would look quite different to an object database query language!

James Strachan is pimpin' Groovy , his new JVM-compatible language (I'm not sure if its quite correct to call it a scripting language) that looks quite like Python but features one of the best things about SmallTalk: closures. (Digression: it seems to be widely believed that the JDK Collections API is one of Java's good points. But if you've ever used collections in SmallTalk, you'll know just how impoverished Java actually is when it comes to working with collections. Iterators are far, far uglier than the more functional approach available in languages with closures. If there is /anything/ that I would ask to be fixed in Java, it wouldn't be the lack of generics, the lack of enums, etc, etc - it would be the lack of closures.) Anyway, I'm interested in what James has to say, but I'm skeptical toward the notion that an object-oriented expression language is the right starting point for an ORM query language. Firstly, relational databases implement very different null value semantics to object oriented languages. In fact, SQL's ternary logic is /quite/ different to the binary logic implemented by programming languages. Secondly, equality is a much more slippery concept in the object oriented world than in the database world. For these reasons, and others, we have chosen to base HQL on SQL, not on Java-like syntax. It is my view that this was one of the best decisions we've made.

Razvan describes what (s)he calls an an associative query model (much like the query in JavaSpaces). If I'm not mistaken, this is what we usually call query by example. I'll get round to discussing Hibernate's new Example query API in a future post...

What are scalar types anyway?

Posted by    |       |    Tagged as

About two years ago, a co-worker asked me innocently: What are scalar types anyway?

I realized that I had used that term one too often and he was really asking if I can define it, not just use it.

On my way to the JavaPolis conference I had some time to write up what I understand about /scalar types/. The truth is, I had a lot of time, because my train got the wrong route (twice!), and we even had to go backwards several times.

Just to make this entry even more exciting, I'll also explain what I understand as a /variable/ and a /value/.

A type names a /set of values/. So, a type has a name, we know that. But what is this set of values? According to Chris Date, a value is an /individual constant/. Now, stop thinking in software terms, and think about information and data. A value has, by definition, no location in time and space. For example, we don't know where or when the value Hibernate is located, this question doesn't even make sense. It's a value nevertheless, just as the number 4 and the number 2.

We know that in a strongly typed language such as Java, every value has to have a type. This means that every value in our software carries its type with it. Instead of working with value literals, as I did in the previous paragraph, we assign them to variables. A variable gives a value a location in time and space. In Java, the type of a value is associated with the variable.

String projectName;
projectName = "Hibernate"

In the first line, we declare that String is the type of the variable projectName. The values that can be assigned to projectName are therefore limited to the set of values allowed for the String type, i.e., all character strings. In the next line, we assign the value Hibernate to the variable projectName. The assignment operator (=) checks both operands for compatibility: Is the given value in the set of values allowed for the variables type? Strong typing means that this check is performed for all operations, including all method (operator) calls, not only assignment.

Let's talk about types in Java. We have built-in types such as String, but also custom user-defined types, such as Project. But a Java /class/ is only the mechanism used for type declaration and implementation. Sometimes we are sloppy and say a class is a type, but strictly speaking, it is not. A type is all externally visible elements of a class, that is all operators (methods) and components (attributes) declared public. We just use the mechanism of a class to define this, and of course, to implement the actual (internal) representation. So the following class defines and implements the Project type:

public Project {

   public String projectName;

   public void makeOpenSource() {
      ...
   }

   public Team getProjectTeam() {
      ...
  }

}

The Project type has one component and two operators. But where is this set of values defined?

Consider the type Object in Java: This type implies a set with all possible values. So, in fact, the set is implicit if you create a type. In other words, if you declare a variable of type Object, you can assign whatever value you want. By creating a type (writing a class or interface), you narrow that set. For example, a type Project might imply a set of all possible projects. You can of course further restrict the allowed values by adding constraints to that type (only projects with a name shorter than 10 characters), but thats not the issue here.

Back to the initial question: A scalar type is a type that is /encapsulated/, that is, it doesn't have any user-visible components. The Project type in the example above is non-scalar, it has the user-visible component (attribute) projectName.

On the other hand, the Team returned by the select operator getProjectTeam does not reveal a component, but only gives us a part of the possible representation of a Project. We simply don't now (and shouldn't care) if the Team returned is internally a component (attribute) of the Project or something completely different. The implementation is hidden.

If we follow the Best Practices for POJOs (or JavaBeans), we automatically create scalar types. Adding a select operator such as getProjectName and removing the public visible component projectName would make the example Project type scalar, that is encapsulated or atomic.

Keep in mind that /scalar/ is not related to /complexity/ in any way. Just because we call Java primitives scalar, doesn't make all scalar types primitive.

Query Objects vs Query Languages

Posted by    |       |    Tagged as

Chris Winters doesn't like object-oriented query APIs. Since Hibernate emphasizes the query /language/ approach, I'm not the best person to disagree with him here. Criteria queries are usually noisier, no doubt about that. And the query languages I've seen tend to be more expressive. Writing arithmetic and even logical expressions is a breeze in a query lanugage, but certainly not in an object-oriented Criteria API.

However, there are a couple of advantages of the Criteria approach. First, some folks like the fact that more can be done to validate the query at compile time. This is no big deal to me because I'm very unit test oriented. Much more importantly, object-oriented query APIs are much better for building queries programmatically. String manipulations suck! Getting your parentheses and whitespace right for all combinations of criteria is a pain. I've seen some truly ugly code that builds HQL strings and it could be rewritten /much/ more neatly using the Criteria API.

Especially, the new query by example stuff could potentially reduce 20 lines of code that builds a query containing the needed properties of Person to:

session.createCriteria(Person.class)
    .add( Example.create(elvis) )
    .list();
    

Well, I suppose query by example is a bit of an extreme case, and you could perhaps implement a similar feature in a query language.

Finally, object oriented query APIs can be more user-extensible. This is what I like best.

P.S. The code example Chris gives is a bit unfair to object APIs. Hibernate's Criteria API is much less verbose than that, partly due to the support for method chaining (which is barely used in Java, so I betray the time I spent with SmallTalk).

back to top