Recent Posts
Archives

Posts Tagged ‘Hibernate’

PostHeaderIcon [DevoxxBE2024] Performance-Oriented Spring Data JPA & Hibernate by Maciej Walkowiak

At Devoxx Belgium 2024, Maciej Walkowiak delivered a compelling session on optimizing Spring Data JPA and Hibernate for performance, a critical topic given Hibernate’s ubiquity and polarizing reputation in Java development. With a focus on practical solutions, Maciej shared insights from his extensive consulting experience, addressing common performance pitfalls such as poor connection management, excessive queries, and the notorious N+1 problem. Through live demos and code puzzles, he demonstrated how to configure Hibernate and Spring Data JPA effectively, ensuring applications remain responsive and scalable. His talk emphasized proactive performance tuning during development to avoid production bottlenecks.

Why Applications Slow Down

Maciej opened by debunking myths about why applications lag, dismissing outdated notions that Java or databases are inherently slow. Instead, he pinpointed the root cause: misuse of technologies like Hibernate. Common issues include poor database connection management, which can halt applications, and issuing excessive or slow queries due to improper JPA mappings or over-fetching data. Maciej stressed the importance of monitoring tools like DataDog APM, which revealed thousands of queries in a single HTTP request in one of his projects, taking over 7 seconds. He urged developers to avoid guessing and use tracing tools or SQL logging to identify issues early, ideally during testing with tools like Digma’s IntelliJ plugin.

Optimizing Database Connection Management

Effective connection management is crucial for performance. Maciej explained that establishing database connections is costly due to network latency and authentication overhead, especially in PostgreSQL, where each connection spawns a new OS process. Connection pools, standardized in Spring Boot, mitigate this by creating a fixed number of connections (default: 10) at startup. However, developers must ensure connections are released promptly to avoid exhaustion. Using FlexyPool and Spring Boot Data Source Decorator, Maciej demonstrated logging connection acquisition and release times. In one demo, a transactional method unnecessarily held a connection for 273 milliseconds due to an external HTTP call within the transaction. Disabling spring.jpa.open-in-view reduced this to 61 milliseconds, freeing the connection after the transaction completed.

Transaction Management for Efficiency

Maciej highlighted the pitfalls of default transaction settings and nested transactions. By default, Spring Boot’s auto-commit mode triggers commits after each database interaction, but disabling it (spring.datasource.auto-commit=false) delays connection acquisition until the first database interaction, reducing connection hold times. For complex workflows, he showcased the TransactionTemplate for programmatic transaction management, allowing developers to define transaction boundaries within a method without creating artificial service layers. This approach avoids issues with @Transactional(propagation = Propagation.REQUIRES_NEW), which can occupy multiple connections unnecessarily, as seen in a demo where nested transactions doubled connection usage, risking pool exhaustion.

Solving the N+1 Problem and Over-Fetching

The N+1 query problem, a common Hibernate performance killer, occurs when lazy-loaded relationships trigger additional queries per entity. In a banking application demo, Maciej showed a use case where fetching bank transfers by sender ID resulted in multiple queries due to eager fetching of related accounts. By switching @ManyToOne mappings to FetchType.LAZY and using explicit JOIN FETCH in custom JPQL queries, he reduced queries to a single, efficient one. Additionally, he addressed over-fetching by using getReferenceById() instead of findById(), avoiding unnecessary queries when only entity references are needed, and introduced the @DynamicUpdate annotation to update only changed fields, optimizing updates for large tables.

Projections and Tools for Long-Term Performance

For read-heavy operations, Maciej advocated using projections to fetch only necessary data, avoiding the overhead of full entity loading. Spring Data JPA supports projections via records or interfaces, automatically generating queries based on method names or custom JPQL. Dynamic projections further simplify repositories by allowing runtime specification of return types. To maintain performance, he recommended tools like Hypersistence Optimizer (a commercial tool by Vlad Mihalcea) and QuickPerf (an open-source library, though unmaintained) to enforce query expectations in tests. These tools help prevent regressions, ensuring optimizations persist despite team changes or project evolution.

Links:

PostHeaderIcon JpaSystemException: A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

Case:

Entity declaration:

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Foo> foos = Lists.newArrayList();

This block

            user.getFoos().clear();
// instantiate `foos`, eg: final List<Foo> foos = myService.createFoos(bla, bla);
            user.setFoos(foos);

generates this error:

org.springframework.orm.jpa.JpaSystemException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: com.github.lalou.jonathan.blabla.User.foos

 Fix:

Do not use setFoos() ; rather, after clearing, use addAll(). In other words, replace:

            user.getFoos().clear();
            user.setFoos(foos);

with

user.getFoos().clear(); user.getFoos().addAll(foos);

 

(copied to https://stackoverflow.com/questions/78858499/jpasystemexception-a-collection-with-cascade-all-delete-orphan-was-no-longer )

PostHeaderIcon [Spring I/O 2023] Do You Really Need Hibernate?

Simon Martinelli’s thought-provoking session at Spring I/O 2023 challenges the default adoption of Hibernate in Java applications. With decades of experience, Simon advocates for jOOQ as a performant, SQL-centric alternative for database-centric projects. Using a track-and-field event management system as a case study, he illustrates how jOOQ simplifies data access, avoids common ORM pitfalls, and complements Hibernate when needed. This presentation is a masterclass in rethinking persistence strategies for modern Java development.

Questioning the ORM Paradigm

Simon begins by questioning the reflexive use of Hibernate and JPA in Java projects. While powerful for complex domain models, ORMs introduce overhead—such as dirty checking or persistence by reachability—that may not suit all applications. For CRUD-heavy systems, like his 25-year-old event management application, a simpler approach is often sufficient. By focusing on database tables rather than object graphs, developers can streamline data operations, avoiding the complexity of managing entity state transitions.

jOOQ: A Database-First Approach

jOOQ’s database-first philosophy is central to Simon’s argument. By generating type-safe Java code from database schemas, jOOQ enables developers to write SQL-like queries using a fluent DSL. This approach, as Simon demonstrates, ensures compile-time safety and eliminates runtime errors from mismatched SQL strings. The tool supports a wide range of databases, including legacy systems with stored procedures, making it versatile for both modern and enterprise environments. Integration with Flyway and Testcontainers further simplifies schema migrations and code generation.

Efficient Data Retrieval with Nested Structures

A highlight of Simon’s talk is jOOQ’s ability to handle nested data structures efficiently. Using the event management system’s ranking list—a tree of competitions, categories, athletes, and results—he showcases jOOQ’s MULTISET feature. This leverages JSON functionality in modern databases to fetch hierarchical data in a single SQL statement, avoiding the redundancy of JPA’s join fetches. This capability is particularly valuable for REST APIs and reporting, where nested data is common, eliminating the need for DTO mapping.

Combining jOOQ and Hibernate for Flexibility

Rather than advocating for jOOQ as a complete replacement, Simon proposes a hybrid approach. jOOQ excels in querying, bulk operations, and legacy database integration, while Hibernate shines in entity state management and cascading operations. By combining both in a single application, developers can leverage their respective strengths. Simon warns against using JPA for raw SQL, as it lacks jOOQ’s type safety, reinforcing the value of choosing the right tool for each task.

Practical Insights and Tooling

Simon’s demo, backed by a GitHub repository, illustrates jOOQ’s integration with Maven, Testcontainers, and a new Testcontainers Flyway plugin. He highlights practical considerations, such as whether to version generated code and jOOQ’s licensing model for commercial databases. The talk also addresses limitations, like MULTISET’s incompatibility with MariaDB, offering candid advice for database selection. These insights ground the presentation in real-world applicability, making it accessible to developers of varying experience levels.

A Call to Rethink Persistence

Simon’s presentation is a compelling call to reassess persistence strategies. By showcasing jOOQ’s performance and flexibility, he encourages developers to align their tools with application needs. His track-and-field application, evolved over decades, serves as a testament to the enduring value of SQL-driven development. For Java developers seeking to optimize data access, this talk offers a clear, actionable path forward, blending modern tooling with pragmatic wisdom.

Hashtags: #SpringIO2023 #jOOQ #Hibernate #Java #SQL #Database #SimonMartinelli #Testcontainers #Flyway

PostHeaderIcon [DevoxxPL2022] Are Immortal Libraries Ready for Immutable Classes? • Tomasz Skowroński

At Devoxx Poland 2022, Tomasz Skowroński, a seasoned Java developer, delivered a compelling presentation exploring the readiness of Java libraries for immutable classes. With a focus on the evolving landscape of Java programming, Tomasz dissected the challenges and opportunities of adopting immutability in modern software development. His talk provided a nuanced perspective on balancing simplicity, clarity, and robustness in code design, offering practical insights for developers navigating the complexities of mutable and immutable paradigms.

The Allure and Pitfalls of Mutable Classes

Tomasz opened his discourse by highlighting the appeal of mutable classes, likening them to a “shy green boy” for their ease of use and rapid development. Mutable classes, with their familiar getters and setters, simplify coding and accelerate project timelines, making them a go-to choice for many developers. However, Tomasz cautioned that this simplicity comes at a cost. As fields and methods accumulate, mutable classes grow increasingly complex, undermining their initial clarity. The internal state becomes akin to a data structure, vulnerable to unintended modifications, which complicates maintenance and debugging. This fragility, he argued, often leads to issues like null pointer exceptions and challenges in maintaining a consistent state, particularly in large-scale systems.

The Promise of Immutability

Transitioning to immutability, Tomasz emphasized its role in fostering robust and predictable code. Immutable classes, by preventing state changes after creation, offer a safeguard against unintended modifications, making them particularly valuable in concurrent environments. He clarified that immutability extends beyond merely marking fields as final or using tools like Lombok. Instead, it requires a disciplined approach to design, ensuring objects remain unalterable. Tomasz highlighted Java records and constructor-based classes as practical tools for achieving immutability, noting their ability to streamline code while maintaining clarity. However, he acknowledged that immutability introduces complexity, requiring developers to rethink traditional approaches to state management.

Navigating Java Libraries with Immutability

A core focus of Tomasz’s presentation was the compatibility of Java libraries with immutable classes. He explored tools like Jackson for JSON deserialization, noting that while modern libraries support immutability through annotations like @ConstructorProperties, challenges persist. For instance, deserializing complex objects may require manual configuration or reliance on Lombok to reduce boilerplate. Tomasz also discussed Hibernate, where immutable entities, such as events or finalized invoices, can express domain constraints effectively. By using the @Immutable annotation and configuring Hibernate to throw exceptions on modification attempts, developers can enforce immutability, though direct database operations remain a potential loophole.

Practical Strategies for Immutable Design

Tomasz offered actionable strategies for integrating immutability into everyday development. He advocated for constructor-based dependency injection over field-based approaches, reducing boilerplate with tools like Lombok or Java records. For RESTful APIs, he suggested mapping query parameters to immutable DTOs, enhancing clarity and reusability. In the context of state management, Tomasz proposed modeling state transitions in immutable classes using interfaces and type-safe implementations, as illustrated by a rocket lifecycle example. This approach ensures predictable state changes without the risks associated with mutable methods. Additionally, he addressed performance concerns, arguing that the overhead of object creation in immutable designs is often overstated, particularly in web-based systems where network latency dominates.

Testing and Tooling Considerations

Testing immutable classes presents unique challenges, particularly with tools like Mockito. Tomasz noted that while Mockito supports final classes in newer versions, mocking immutable objects may indicate design flaws. Instead, he recommended creating real objects via constructors for testing, emphasizing their intentional design for construction. For developers working with legacy systems or external libraries, Tomasz advised cautious adoption of immutability, leveraging tools like Terraform for infrastructure consistency and Java’s evolving ecosystem to reduce boilerplate. His pragmatic approach underscored the importance of aligning immutability with project goals, avoiding dogmatic adherence to either mutable or immutable paradigms.

Embracing Immutability in Java’s Evolution

Concluding his talk, Tomasz positioned immutability as a cornerstone of Java’s ongoing evolution, from records to potential future enhancements like immutable collections. He urged developers to reduce mutation in their codebases and consider immutability beyond concurrency, citing benefits in caching, hashing, and overall design clarity. While acknowledging that mutable classes remain suitable for certain use cases, such as JPA entities in dynamic domains, Tomasz advocated for a mindful approach to code design, prioritizing immutability where it enhances robustness and maintainability.

Links:

PostHeaderIcon (long tweet) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘type=InnoDB’ at line 1

Stacktrace

[java]org.hibernate.tool.hbm2ddl.SchemaExport – You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘type=InnoDB’ at line 1[/java]

Quick fix

In JPA configuration, replace:
datasource.dialect = org.hibernate.dialect.MySQLInnoDBDialect
with:
datasource.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
Actually, Java driver for MySQL 5.5+ is not backward compatible with the SQL dialect MySQLInnoDBDialect.

PostHeaderIcon [DevoxxBE2012] FastOQL – Fast Object Queries for Hibernate

Srđan Luković, a software developer at SOL Software, alongside Žarko Mijailovic and Dragan Milicev from the University of Belgrade, presented a groundbreaking solution to a persistent challenge in Hibernate development. Žarko, a senior Java EE developer and PhD candidate with deep involvement in model-driven frameworks like SOLoist4, led the discussion on FastOQL, a Java library that transforms complex Object Query Language (OQL) statements into highly optimized SQL, addressing Hibernate’s HQL performance bottlenecks in large-scale databases.

The trio began by dissecting the limitations of HQL queries, which often generate inefficient joins when traversing class hierarchies or association tables, leading to sluggish execution on voluminous datasets. FastOQL emerges as a targeted remedy, compiling OQL into minimal-join SQL tailored for Hibernate environments. Srđan illustrated this with examples involving inheritance hierarchies and many-to-many relationships, where FastOQL drastically reduces query complexity without sacrificing the object-oriented expressiveness of OQL.

Žarko delved into the library’s design, emphasizing its derivation from SOL Software’s proprietary persistence layer, ensuring seamless integration as an HQL alternative. Dragan, an associate professor and department chair at the Faculty of Electrical Engineering, provided theoretical grounding, explaining how FastOQL’s strategy leverages specific mappings—like single-table inheritance and association tables—to eliminate unnecessary joins, yielding substantial performance gains in real-world scenarios.

A live demonstration highlighted FastOQL’s prowess: compiling an OQL query spanning multiple entities resulted in SQL with fewer tables and faster retrieval times compared to equivalent HQL. The speakers underscored its focus on prevalent Hibernate mappings, driven by practical observations from blogs, documentation, and industry recommendations. In Q&A, they addressed benchmarking queries, affirming that while initial efforts targeted these mappings for maximal impact, future expansions could encompass others, rooted in FastOQL’s extensible architecture.

FastOQL stands as a beacon for developers grappling with scalable persistence, marrying OQL’s conciseness with SQL’s efficiency to foster maintainable, high-velocity applications in enterprise settings.

Tackling HQL’s Performance Hurdles

Žarko unpacked HQL’s pitfalls, where intricate joins across polymorphic classes inflate query costs. FastOQL counters this by analyzing object structures to prune redundant associations, delivering lean SQL that preserves relational integrity while accelerating data access.

OQL Compilation Mechanics

Srđan demonstrated the compilation pipeline, where OQL expressions map directly to optimized SQL via Hibernate’s session factory. This process ensures type-safe queries remain portable, sidestepping the verbosity of native SQL while inheriting Hibernate’s caching benefits.

Real-World Mapping Strategies

Dragan highlighted FastOQL’s affinity for common patterns, such as table-per-class hierarchies and intermediary tables for collections. By prioritizing these, the library achieves dramatic throughput improvements, particularly in inheritance-heavy domains like content management or e-commerce.

Integration and Future Prospects

The presentation touched on FastOQL’s Hibernate-centric origins, with plans to broaden mapping support. Žarko encouraged exploration via SOL Software’s resources, positioning it as a vital evolution for object-relational mapping in demanding environments.

Links:

PostHeaderIcon (quick tutorial) Migration from MySQL to HSQLDB

Case

I got the project described in MK Yong’s website. This projects is a sample code of JSF + Spring + Hibernate. The laying DB is a MySQL. For many reasons, I’d rather not to detail, I prefered to a HSQLDB instead of the MySQL.

(Notice: the zip you can download at MK Yong’s website contains many errors, not related to the persistance layer but to JSF itself.)

How to migrate any project from MySQL to HSQLDB?

Solution

You have to follow these steps:

Maven

In the pom.xml, replace:
[xml]<!– MySQL database driver –>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
[/xml]
with:
[xml] <!– driver for HSQLdb –>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.2.8</version>
</dependency>
[/xml]
By the way, you can add Jetty plugin to have shorter development cycles:
[xml] <plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<configuration>
<webApp>${basedir}/target/jsf.war</webApp>
<port>8088</port>
</configuration>
</plugin>[/xml]

Persistence

Properties

Replace the content of db.properties file with:[java]jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://localhost:9001
jdbc.username=sa
jdbc.password=[/java]

Hibernate Mapping

In the *.hbm.xml files:

  • in the tag <class>, remove the attribute catalog="..."
  • replace the types with fully qualified object types, eg:
    • long with java.lang.Long,
    • string with java.lang.String,
    • timestamp with java.util.Date,
    • etc.

Hibernate Properties

For the property of key hibernate.dialect, replace the value: org.hibernate.dialect.MySQLDialectorg.hibernate.dialect.HSQLDialect with the value: org.hibernate.dialect.HSQLDialect.
To match my needs, I tuned Hibernate properties a bit more, but it may not be needed in all situations:
[xml] <property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hbm2ddl.auto">create-drop</prop>
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
<prop key="connection.pool_size">1</prop>
<prop key="current_session_context_class">thread</prop>
<prop key="cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
</props>
</property>
[/xml]

Run

Run the HSQLDB server. IMHO, the quickest is to run the following Maven command:

mvn exec:java -Dexec.mainClass="org.hsqldb.Server"

But you may prefer the old school java -cp hsqldb-XXX.jar org.hsqldb.Server ;-).

Tip! To get a GUI to check the content of the DB instance, you can run:

mvn exec:java -Dexec.mainClass="org.hsqldb.util.DatabaseManager"

Then build and launch Jetty:

mvn clean install jetty:run-exploded

Here you can see the great feature of HSQLDB, that will allow you to create, alter and delete tables on the fly (if hibernate.hbm2ddl.auto is set to create-drop), without any SQL scripts, but only thanks to HBM mapping files.

PostHeaderIcon Unable to instantiate default tuplizer… java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.

Case

On running a web application hosted on Jetty, I get the following stracktrace:
[java]Nested in org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/classes/config/spring/beans/HibernateSessionFactory.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]:
java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V[/java]
Unlike what I immediatly thought at first glance, the problem is not induced by the Tuplizer ; the actual error is hidden at the bottom: java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.

Here are some of the dependencies:
[java]org.hsqldb:hsqldb:jar:2.2.8:compile
org.springframework:spring:jar:2.5.6:compile
org.hibernate:hibernate:jar:3.2.7.ga:compile
javax.transaction:jta:jar:1.0.1B:compile
| +- asm:asm-attrs:jar:1.5.3:compile
| \- asm:asm:jar:1.5.3:compile[/java]

Fix

Main fix

The case is a classic problem of inherited depencencies. To fix it, you have to excluse ASM 1.5.3, and replace it with more recent version. In the pom.xml, you would then have:
[xml]
<properties>
<spring.version>3.1.0.RELEASE</spring.version>
<hibernate.version>3.2.7.ga</hibernate.version>
<asm.version>3.1</asm.version>
</properties>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>${hibernate.version}</version>
<exclusions>
<exclusion>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
</exclusion>
<exclusion>
<groupId>asm</groupId>
<artifactId>asm-attrs</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>${asm.version}</version>
</dependency>
[/xml]

Other improvements

I took the opportunity to upgrade Spring 2.5 to Spring 3.1 (cf the properties above).
Besides, I modified the *.hbm.xml files to use object types, rather than primary types, eg replacing:
[xml]<id name="jonathanId" type="long">[/xml]
with:
[xml]<id name="jonathanId" type="java.lang.Long">[/xml]

PostHeaderIcon Useful DTD

DTDs are useful when your XML editor take them in account: detecting errors, suggestions, complete statements… For instance, I save much time with IntelliJ IDEA automatic completion ; unlike, Eclipse amazingly does not implement this feature.

Here is a list of some widely used DTDs:

File DTD
weblogic-application.xml [xml]<!DOCTYPE weblogic-application PUBLIC "-//BEA Systems, Inc.//DTD WebLogic Application 7.0.0//EN" "http://www.oracle.com/technology/weblogic/weblogic-application/1.1/weblogic-application.xsd">[/xml]
weblogic-application.xml [xml]<!DOCTYPE weblogic-application PUBLIC "-//BEA Systems, Inc.//DTD WebLogic Application 7.0.0//EN" "http://www.oracle.com/technology/weblogic/weblogic-application/1.1/weblogic-application.xsd">[/xml]
web.xml [xml]<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >[/xml]
*.hbm.xml [xml]<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">[/xml]
GWT modules [xml]<!DOCTYPE module SYSTEM "http://google-web-toolkit.googlecode.com/svn/trunk/distro-source/core/src/gwt-module.dtd">[/xml]
GWT UI [xml]<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">[/xml]
Tangosol / Oracle Coherence [xml]<!DOCTYPE coherence SYSTEM "coherence.dtd">[/xml]
Log4J [xml]<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">[/xml]

Tangosol and Log4J DTDs are included within their distribution JARs: you have to extract them or to give their path to IntelliJ IDEA.

PostHeaderIcon org.hibernate.HibernateException: identifier of an instance of … was altered from … to 0

Case

Stracktrace

org.hibernate.HibernateException: identifier of an instance of lalou.jonathan.domain.Foo was altered from 183740934 to 0

Sometimes, the error is slightly different: was altered from XXXX to null

Here is a part of Hibernate mapping:

[xml]<id name="fooId" column="fooId">
<generator class="seqhilo">
<param name="sequence">JL_Foo_SEQ</param>
<param name="max_lo">10</param>
</generator>
</id>[/xml]

Here is the Java code:

[java]Foo sourceFoo = FooDAO.findById(xxxx);
Foo foo = new Foo();
foo = BeanUtils.copyProperties(sourceFoo);
foo.setFooId(null);
FooDAO.createFoo(foo);[/java]

Explanation

Using new Foo() instantiates an object of type Foo, with all its fields initialized at null (or zero for ints, floats, etc.). Writing explicitly foo.setFooId(null) removes the object from Hibernate current session.

Fix

Don’t set explicitly the fooId! Leave Hibernate initialize default values, and set handly other values, without using BeanUtils.