Ceylon – Yet Another JVM Language (YAJL)

It is all too familiar, yet surprising; it is all too common, yet shocking; to see yet another JVM language created to scratch an itch that countless other languages are already trying to solve.

Of course Java is not expressive enough, it doesn’t have higher order functions, it doesn’t have modularity as a language feature, it doesn’t have clean way to do meta-programming, it does NOT have so many more features we love and does have so many more features we hate. These are most of what has frustrated Gavin King (the creator of Hibernate) as well and made him think about creating a new language – Ceylon. A few days ago, in his presentation at the QCon Beijing 2011 he gave a first glimpse of the language features and a few code snippets showing its beauty.

A lot of people have raised concerns and expressed strong opinions questioning a need for yet another language. Scala fans, the Groovy(++) camp, Gosu and Fantom hackers all think that Ceylon does not solve anything that is not solved already or could have been solved by just contributing to one of these modern languages. So, I am not going to be yet another anti Ceylon person but I am not a fan either.

I believe Ceylon is more of a strategic approach from RedHat than a language created out of true necessity. They would like to control a language and its followers like most other giant companies do today. Think about it. Oracle is controlling Java, Microsoft is controlling C# (VB, VC++, etc), Google is controlling Go (and Python?), Apple is controlling Objective C and VMWare is controlling Groovy. RedHat has just joined the party leaving only IBM out of the equation. I am sure they are not far behind. I just sincerely hope that they adopt an existing language (Scala?) instead of creating yet another one.

That said, the language itself looks cool, is very expressive and adds a lot of syntactic sweetness to say the least. I just wanted to highlight a few of them here…

String Interpolation:
In Java we use a “+” sign for string concatenation. There is no concept of string interpolation in either Java or Scala. In Groovy ${} construct is used while Ruby uses #{}. Ceylon’s syntax looks better than either of them though. It uses a “space” as the string interpolation operator and the result looks a lot cleaner. Don’t you think?

String name;
writeLine("Hello " name "!");

Getter:
In Java we use getXxx() methods to get a property value. This looks like a method and quacks like a method and does not give the feeling of accessing a property at all. In Ceylon, a very simple innovation has resulted in much more succinct getter methods. They have decided to get rid of paranthesis to both define and call getter methods. Look at the last line of the following snippet. Does it look like a method call? NO. Does it look like accessing a property? Of course it does !!!

class Counter() {
   variable Natural count := 0;
   shared Natural currentCount {
      return count;
   }
}
Counter c = new Counter();
writeLine(c.currentCount);

Constructor:
In Ceylon there is no separate constructor. The class definition itself acts as a constructor as shown below. Since, there is no concept of method or operator overloading in Ceylon there is no necessity to have a separate method and this syntax induces a “Why didn’t I think of this before ?” moment… The necessity for an overloaded method is handled by optional /defaulted parameters concept. So, you don’t have to worry too much about it…

class Customer (String cName, Natural cAge, Date cDob) {
   variable String name :=  cName;
   …
}

Builder:
With the support of named parameters and higher-order functions and quite a bit of thought, a syntactic structure as expressive as given below has been achieved in a general purpose and statically typed language like Ceylon.

Html hello {
   Head head { title = "Squares"; }
   Body body {
      Div {
         cssClass = "greeting";
         "Hello" name "!";
      }
   }

And then there is the rest of the now so common features like array like access to Sequences (equivalent of List in Java), higher-order functions, Closures, Currying, etc

It is not like I loved every single feature of Ceylon. I hated a few, but I am reserving that rant for another post…

Hibernate never stops surprising me

I have a simple form in my web application where a user can fill in his personal details and address details. User specific fields include firstName, middleName and lastName while Address specific fields include street, city and zip. On the server side, I have POJOs for User and Address. Finally I use Hibernate to map these POJOs to the database. Since, the Address will not be used outside the context of the User, I decided to map it as a Component of the User class.

The User class and its corresponding mapping is given below:

@Entity @Table(name = "user")
public class User {

     @Column(name = "first_name")
     private String firstName;
     
     @Column(name = "middle_name")
     private String middleName;
     
     @Column(name = "last_name")
     private String lastName;
    
     @Embedded
     private Address homeAddress;

     ... Getters and Setters
}

The Address class is mapped to User as a component. You can see the specifics of the mapping below.

@Embeddable
public class Address {
     @Column(name = "address_street")
     private String street;
     
     @Column(name = "address_city")
     private String city;
     
     @Column(name = "address_state")
     private String state;

     ... Getters and Setters
}

As you may already know, mapping components using hibernate is a very useful feature. This feature and support for nested components and components referring to other entities are the primary source of support for rich and fine grained domain model in hibernate. But while i was using Component mapping, I recently stepped on an interesting Feature (or it could be an Issue) and I was happily surprised by it.

Want to know the surprise? Keep reading…

In this case you map an Address as a value type using @Embedded annotation in the “homeAddress” field of the User class. The Address class itself is declared to be @Emeddable. This is the standard Hibernate/JPA way to map value types. The Address class has street, city and zip and it gets stored into the same table as the User class’s table. Now, when you insert an instance of User into the database, while specifying all null values for Address‘s fields maybe because the user didn’t give his address, then what would you expect in return at some point in time when you retrieve this User back from the database.

I for one expected user.getAddress() will return an Address instance. Then address.getStreet() will return null. But that is not what happened. user.getAddress() returned null by itself. That was interesting and even helped me in my case because, if the user hasn’t given any details for his home address, then it probably means that his address itself is not there in the system. So, returning null for getAddress() is semantically the right thing to do. I was surprised and when i checked the hibernate documentation it was even mentioned there that if all properties of a component are null, then the component itself is considered null.

In another situation this could have been bad, I don’t know, but for my purpose I was happily surprised with this nice touch from hibernate. These kind of small things is what differentiates a great product from a good product. Ain’t it?

Hibernate: Why should I Force Discriminator?

Hibernate is an ambitious project that aims to be a complete solution to the problem of managing persistent data in java. Even with such an arduous task before them, the hibernate team tries very hard to expose a simple API for developers like us. Still, the complexity behind the API shows its ugly face time and again and I believe it is unavoidable as long as the mismatch between Object and Relational world exists.

That said, although I have worked with hibernate for many years and have been its advocate in all my organizations, I keep facing newer issues and keep finding newer ways to work with it efficiently and effectively. Recently, when I was working for nboomi.com, I faced an issue when mapping a OneToMany relationship to the sub-classes of “Single Table Inheritance” strategy. After a frustrating couple of hours of debugging I finally landed on the correct solution. So, I thought other developers who will travel this path could get benefited and started writing this blog post.

Let me explain the issue I faced with an example. Assume you have a normal User Entity with the typical id, version and loginId properties. Assume this User can have many AboutUs sections and many Service sections. You don’t need to be an architect to model them as OneToMany relationships from User. So, I modelled UserAboutSection and UserServiceSection entities and created a OneToMany relationship between User and these entities. Looking at the commonality between these two, I decided to factor out the common fields into a superclass called UserSection. Now, both UserAboutSection and UserServiceSection extends UserSection. I chose to map this Inheritance hierarchy using “Single Table Inheritance” strategy to keep it simple and since most of the fields were common and only a few were specific.

The User entity is given below. Notice the List<UserAboutSection> and a List<UserServiceSection> mapped using OneToMany relationship.

The getters, setters, adders, imports and static imports are omitted for brevity.

@Entity @Table(name = "user")
public class User extends BaseEntity {

    @Column(name = "login_id")
    private String loginId;

    @Column(name = "password")
    private String password;

    ...

    @OneToMany(cascade = {CascadeType.ALL})
    @JoinColumn(name = "user_id", nullable = false)
    @IndexColumn(name = "user_section_position")
    List<UserAboutSection> aboutUs;

    @OneToMany(cascade = {CascadeType.ALL})
    @JoinColumn(name = "user_id", nullable = false)
    @IndexColumn(name = "user_section_position")
    List<UserServiceSection> services;

    ... Getters, Setters and Adders
}

Here goes the UserSection entity that acts as the base class in this “Single Table Inheritance” strategy. Hibernate uses the @DiscriminatorColumn annotation to distinguish between sub-classes.

@Entity @Table(name = "user_section")
@Inheritance(strategy= InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="user_section_type", discriminatorType = STRING) 
public class UserSection extends BaseEntity {
    
    @Column(name = "title")         
    protected String title;

    @Column(name = "description")   
    protected String description;

    ... Getters and Setters
}

Here goes the UserAboutSection entity that derives from the UserSection entity. Hibernate uses the @DiscriminatorValue annotation to decide if a row in the database belongs to an instance of this class.

@Entity @DiscriminatorValue("ABOUT")
public class UserAboutSection extends UserSection {
    @ManyToOne 
    @JoinColumn(name="user_id",updatable=false,insertable=false,nullable=false)
    protected User user;

    ... Other Properties specific to UserAboutSection
}

Here goes the UserServiceSection entity that derives from the UserSection entity. Hibernate uses the @DiscriminatorValue annotation to decide if a row in the database belongs to an instance of this class.

@Entity @DiscriminatorValue("SERVICE")
public class UserServiceSection extends UserSection {
    @ManyToOne 
    @JoinColumn(name="user_id",updatable=false,insertable=false,nullable=false)
    protected User user;

    ... Other Properties specific to UserServiceSection
}

Pretty straightforward… huh! When you try to retrieve an instance of User along with its aboutUs and services collections eagerly (or lazily – doesn’t matter), what do you expect?

I expected an instance of User with the aboutUs collection filled with only UserAboutSection instances and the services collection filled with only UserServiceSection instances corresponding to only the rows they represent in the database. And I believe this expectation is valid, because that is what the mapping looks like and hibernate also has all the information it needs to make this work.

But I got something different. Both the aboutUs and services collections had all the UserSection rows that belong to this User. I mean, aboutUs collection had all the UserSection instances including UserAboutSection and UserServiceSection instances. This was surprising because hibernate has all the information it needs to populate the right instances.

After quite a bit of debugging, googling and RTFM-ing I landed upon @ForceDiscriminator annotation. This annotation has to be applied to the base class in the Inheritance hierarchy for “Single Table Inheritance” strategy. In my case, I had to apply it to UserSection entity. The UserSection entity after applying this annotation is given below…

@Entity @Table(name = "user_section")
@Inheritance(strategy= InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="user_section_type", discriminatorType = STRING) 
@ForceDiscriminator
public class UserSection extends BaseEntity {
    
    @Column(name = "title")         
    protected String title;

    @Column(name = "description")   
    protected String description;

    ... Getters and Setters
}

Once I ask hibernate to Force Discriminiator, it is happy and populates the aboutUs and services collections with its respective instances.

Ok, Problem Solved! But why did I have to tell hibernate to Force Discriminator. Shouldn’t that be the default behaviour. Is it a bug in hibernate or is it a feature? Am I missing something? If any one of you hibernate fans have walked this path and know the answer, please feel free to drop in a comment. I sincerely hope this post will be a valuable time-saver for other hibernate developers who step on this Bug/Feature.

Hibernate – Difference between session’s get() and load()

Being an avid hibernate fan, I have always defended it in my organization when people throw undue criticism at it in order to protect themselves. In one such debate, a colleague pointed out a pattern in our code-base that introduced needless performance degradation, and condemned hibernate for it. I was glad he brought that up – for 2 reasons. First because, it sure was a problem and called for immediate attention. Second because, once again the problem was not with hibernate, but us. If you look closely at domain driven applications, you will notice that a few core objects are directly referenced by most other objects. Let me clarify what i mean with an example. In an auction application, for example, an Auction is held for an Item, a Bid is placed for an Item, a Buyer buys an Item. The common object referenced here is, well, an Item. This implies that whenever you create a new Auction or Bid you are constrained to supply a reference to Item. The most obvious way to achieve this is by getting a persistent instance of Item from the database using the session.get() method. This works, but it has its limitations.

Session session = << Get session from SessionFactory >>
Long itemId = << Get the item id from request >>

Item item = (Item) session.get(Item.class, itemId);

if(item != null) {
   Bid bid = new Bid();
   bid.setItem(item);
   session.saveOrUpdate(bid);
} else {
   // Handle the error condition appropriately
   log.error("Bid placed for an unavailable item");
}

Think about it… How many times will a bid be placed for an Item? Many… Every time a Bid is placed, is it wise to hit the database and retrieve the corresponding Item just to supply it as a reference? I guess not. That is where session.load() comes in. All the above scenarios remaining the same, if you just used session.load() instead of get(), hibernate will not hit the database. Instead it will return a proxy, or an actual instance if it was present in the current session, and that can be used to serve as a reference. What does this buy you? At least 2 advantages. First, you save a trip to the database. Second, the error handling code just got elegant. Take a look at the code snippet below. Here we don’t handle erroneous conditions using null checks. Instead we use exceptions, which sounds appropriate in this scenario. Don’t they?

Session session = << Get session from SessionFactory >>
Long itemId = << Get the item id from request >>

try{
   Item item = session.load(Item.class, itemId);
   Bid bid = new Bid();
   bid.setItem(item);
   session.saveOrUpdate(bid);
} catch(ObjectNotFoundException e) {
   // Handle the error condition appropriately
   log.error("Bid placed for an unavailable item");
}

From the above piece of code, it is obvious that, an ObjectNotFoundException may be thrown if the actual Item representing the given item id cannot be found. What i am not clear about – and neither is hibernate documentation – is which method is more likely to cause this exception and why? session.load() seems to have a possibility to throw this exception, and so does saveOrUpdate() for the same fact that item for the given id/proxy is not available. I would love to hear from people who have traveled this path and have an answer. Also, it would be wonderful, if you could point out other differences between session.get() and load() that i may have missed.