Tag Archives: hibernate

Never use “reserved keyword” as column name

The title says it all. Never EVER use the reserved keyword of a database system for a column name. You will meet problems that cost lots of time (which isn’t worth at all!)

If someone tells you about this little trick:

    <class name="long.model.User" table="USER">
        <cache usage="read-write"/>
        <id name="id" column="ID">
            <generator class="sequence">
                <param name="sequence">user_seq</param>

        <property name="position" column=""POSITION""/>

Then just kick him in the ass! Why we should use something as dirty as “"”?

If you still not believe, take the example above, then try to UPDATE the position of a random user.

As you may guess:

UPDATE public.user set position = 'MANAGER'; // NOT WORK 
UPDATE public.user set 'position' = 'MANAGER'; // NOT WORK 
UPDATE public.user u set u.'position' = 'MANAGER'; // NOT WORK AGAIN 
UPDATE public.user u set u.POSITION = 'MANAGER'; // NOT WORK! 


Here’s what you MUST do if already get fallen into the trap

UPDATE public.user set "POSITION" = "MANAGER"; // WORK! Windows only 
UPDATE public.user set "POSITION" = 'MANAGER'; // WORK! only Linux 

Hence don’t try to trick the system. Curiosity is good, but you might need to pay for it by several hours playing with how Postgresql deal with case-sensitive name. Nice to find out, but either way, it isn’t a portable database script.

Force refreshing second level cache in Hibernate

/** Vietnamese: cách xóa second level cache bằng code trong Hibernate**/

Hibernate second level cache is helpful, but only if using wisely.

In the ordinary context, if you delete an object in database by Hibernate, Hibernate will know and update its cache. But if the object/ tube got deleted by other programs (or by cascade delete set up in database itself), Hibernate won’t know and won’t update anything. Hence the deleted objects may remain in the cache for quite a time, and your code may throw an exception or two when trying to get items related to that object.

It’s a good practice to do every database-related thing through Hibernate. But in reality, sometimes we must do the other way around:

private void evict2ndLevelCache() {

  try {
    log.info("Evicting all Entity Regions of 2nd Level Cache");
    Map classesMetadata = sessionFactory.getAllClassMetadata();
    for (String entityName : classesMetadata.keySet()) {
      log.info("Entity from 2nd level cache:" + entityName);
  } catch (Exception e) {
  log.error("Error evicting 2nd level hibernate cache entities: ", e);


The solution provided here is an alternate of the solution in this question. Thanks brother Tinh for this information.