You are on page 1of 22

Java Interview Questions and Answers on Software Architecture

Good caliber candidates have the ability to look at the big picture and drill down into details. The line between software development and software architecture is a tricky one. Regardless of you are an architect, developer, or both, one needs to have a good understanding of the overall software architecture. The following Java interview questions are very popular with the interviewers and it can significantly influence the decision of Hire/No Hire. So, it really pays to have a good overview of various possible architectures. The questions shown below will also make a good platform for further questions depending on your answers.

Be prepared for a white board session on architectures, especially the bird's eye view of the last application you had worked on. There will be lots of follow on questions like why a particular approach was used?, what are the benefits and drawbacks of a particular approach?, etc.

Q. Can you draw me a 1000 foot view of the architecture of the system you were/are involved in, in your current/last position? Q. Can you describe the architecture of a medium-to-large scale system that you actually designed or implemented? Q. Can you white board the components of the system you recently worked on? Q. How would you go about designing a JEE shopping cart application? Q. Can you discuss some of the high level architectures you are experienced with?
A. There are a number of high level conceptual architectures as discussed below. These individual architectures can be mixed and matched to produce hybrid architectures.

Model-View-Controller Architecture
Most web and stand-alone GUI applications follow this pattern. For example, Struts and Spring MVC frameworks and Swing GUI.

The model represents the core business logic and state. The view renders the content of the model state by adding display logic. The controller translates the interaction with the view into action to be performed by the model. The actions performed by a model include executing the business logic and changing the state of the model. Based on the user interactions, the controller selects an appropriate view to render. The controller decouples the model from the view.

Service Oriented Architecture (SOA)

The business logic and application state are exposed as reusable services. An Enterprise Service Bus (ESB) is used as an orchestration and mediation layer to decouple the applications from the services.

The above architecture has 5 tiers. The application tier could be using a typical MVC architecture. The service orchestration tier could be using ESB products like Oracle Service Bus, TIBCO, etc and BPM products like Lombardi BPM, Pega BPM, etc. In the above diagram, the ESB integrates with the BPM via messaging queues. The service tier consists of individual services that can be accessed through SOAP or RESTful web services. The SOA implementation requires change agents to drive adoption of new approaches. The BPM, application integration, and real-time information all contribute to dynamically changing how business users do their jobs. So, it needs full support from the business, requiring restructuring and also it can take some time to realize the benefits of SOA. Cloud computing is at the leading edge of its hype and as a concept compliments SOA as an architectural style. Cloud computing is expected to provide a computing capability that can scale up (to massive proportions) or scale down dynamically based on demand. This implies a very large pool of computing resources either be within the enterprise intranet or on the Internet (i.e on the cloud).

User Interface (UI) Component Architecture

This architecture is driven by a user interface that is made up of a number of discrete components. Each component calls a service that encapsulates business logic and hides lower level details. Components can be combined to form new composite components allowing richer functionality.

These components can also be shared across a number of applications. For example, JavaScript widgets, Java Server Faces (JSF) components, etc.

RESTful data composition Architecture

The user interface can be built by calling a number of underlying services that are each responsible for building part of a page. The user interface translates and combine the data in different formats like XML(translate to HTML using XSLT), JSON (Java Script Object Notation), ATOM (feed for mail messages and calendar applications), RSS (for generating RSS feeds), etc.

HTML composition Architecture

In this architecture, multiple applications output fragments of HTML that are combined to generate the final user interface. For example, Java portlets used inside a portal application server to aggregate individual content..

Plug-in Architecture

In this architecture, a core application defines an interface, and the functionality will be implemented as a set of plug-ins that conform to that interface. For example, the the Eclipse RCP framework, Maven build tool, etc use this architecture.

Event Driven Architecture (EDA)

The EDA pattern decouples the interactions between the event publishers and the event consumers. Many to many communications are achieved via a topic, where one specific event can be consumed by many subscribers. The EDA also supports asynchronous operations and acknowledgments through event messaging. This architecture requires effective monitoring in place to track queue depth, exceptions, and other possible problems. The traceability, isolation, and debugging of an event can be difficult in some cases. This architecture is useful in scenarios where the business process is inherently asynchronous, multiple consumers are interested in an event(e.g. order status has changed to partially-filled ), no immediate acknowledgment is required (e.g. an email is sent with the booking details and itinerary), and real-time request/response is not required (e.g. a long running report can be generated asynchronously and made available later via online or via email).

Most conceptual architectures use a hybrid approach using a combination of different architectures based on the benefits of each approach and its pertinence to your situation. Here is a sample hybrid approach depicting an online trading system.

FIX is a Financial Information eXchange protocol. You could also notice a number of synchronous calls using XML/HTTP or SOAP/HTTP and asynchronous calls using JMS. The above diagram also depicts that an enterprise architecture can be complex with a number of moving parts. So, it is imperative that all these moving parts are properly monitored and tested for any potential performance issues. Most of these services will be running as a cluster or a load balanced service with either active/active or active.passive configuration for high availability and scalability.

Java Web Services Interview Questions and Answers: Overview

Q. What are the different application integration styles? A. There are a number of different integration styles like 1. Shared database 2. batch file transfer 3. Invoking remote procedures (RPC) 4. Exchanging asynchronous messages over a message oriented middle-ware (MOM).

Q. What are the different styles of Web Services used for application integration? A. SOAP WS and RESTful Web Service

Q. What are the differences between both SOAP WS and RESTful WS? A.

The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented middle-ware (MOM) integration styles. The Restful Web Service supports only RPC integration style.

The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S), Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.

The SOAP WS permits only XML data format.You define operations, which tunnels through the POST. Thefocus is on accessing the named operations and exposing the application logic as a service. The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations. GET - represent() POST - acceptRepresention() PUT - storeRepresention() DELETE - removeRepresention()

SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better. SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc. The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not.

The SOAP has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. The REST supports transactions, but it is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.

The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.

Q. How would you decide what style of Web Service to use? SOAP WS or REST? A. In general, a REST based Web service is preferred due to its simplicity, performance, scalability, and support for multiple data formats. SOAP is favored where service requires comprehensive support for security and transactional reliability. The answer really depends on the functional and non-functional requirements. Asking the questions listed below will help you choose.

Does the service expose data or business logic? (REST is a better choice for exposing data, SOAP WS might be a better choice for logic).Do the consumers and the service providers require a formal contract? (SOAP has a formal contract via WSDL)

Do we need to support multiple data formats? Do we need to make AJAX calls? (REST can use the XMLHttpRequest) Is the call synchronous or asynchronous? Is the call stateful or stateless? (REST is suited for statless CRUD operations) What level of security is required? (SOAP WS has better support for security)

What level of transaction support is required? (SOAP WS has better support for transaction management) Do we have limited band width? (SOAP is more verbose) Whats best for the developers who will build clients for the service? (REST is easier to implement, test, and maintain)

Q. What tools do you use to test your Web Services? A. SoapUI tool for SOAP WS and the Firefox "poster" plugin for RESTFul services.

Q. What is the difference between SOA and a Web service? A. SOA is a software design principle and an architectural pattern for implementing loosely coupled, reusable and coarse grained services. You can implement SOA using any protocols such as HTTP, HTTPS, JMS, SMTP, RMI, IIOP (i.e. EJB uses IIOP), RPC etc. Messages can be in XML or Data Transfer Objects (DTOs). Web service is an implementation technology and one of the ways to implement SOA. You can build SOA based applications without using Web services for example by using other traditional technologies like Java RMI, EJB, JMS based messaging, etc. But what Web services offer is the standards based and platform-independent service via HTTP, XML, SOAP, WSDL and UDDI, thus allowing interoperability between heterogeneous technologies such as J2EE and .NET.

Q. Web services when you can use traditional style middle-ware such as RPC, CORBA, RMI and DCOM? A. The traditional middle-wares tightly couple connections to the applications and it can break if you make any modification to your application. Tightly coupled applications are hard to maintain and less reusable. Generally do not support heterogeneity. Do not work across Internet. Can be more expensive and hard to use. Web Services support loosely coupled connections. The interface of the Web service provides a layer of abstraction between the client and the server. The loosely coupled applications reduce the cost of maintenance and increases re-usability. Web Services present a new form of middle-ware based on XML and Web. Web services are language and platform independent. You can develop a Web service using any language and deploy it on to any platform, from small device to the largest supercomputer. Web service uses language neutral protocols such as HTTP and communicates between disparate applications by passing XML messages to each other via a Web API. Do work across internet, less expensive and easier to use. Q. What are the different approaches to developing a SOAP based Web service? A. 2 approaches.

The contract-first approach, where you define the contract first with XSD and WSDL and the generate the Java classes from the contract. The contract-last approach where you define the Java classes first and then generate the contract, which is the WSDL file from the Java classes. Note: The WSDL describes all operations that the service provides, locations of the endpoints (i.e.e where the services can be invoked), and simple and complex elements that can be passed in requests and responses.

Q. What are the pros and cons of each approach, and which approach would you prefer? A. Contract-first Web service


Clients are decoupled from the server, hence the implementation logic can be revised on the server without affecting the clients. Developers can work simultaneously on client and server side based on the contract both agreed on.

You have full control over how the request and response messages are constructed -for example, should "status" go as an element or as an attribute? The contract clearly defines it. You can change OXM (i.e. Object to XML Mapping) libraries without having to worry if the "status" would be generated as "attribute" instead of an element. Potentially, even Web service frameworks and tool kits can be changed as well from say Apache Axis to Apache CXF, etc CONS:

More upfront work is involved in setting up the XSDs and WSDLs. There are tools like XML Spy, Oxygen XML, etc to make things easier. The object models need to be written as well.

Developers need to learn XSDs and WSDLs in addition to just knowing Java.

Contract-last Web service PROS:

Developers don't have to learn anything related to XSDs, WSDLs, and SOAP. The services are created quickly by exposing the existing service logic with frameworks/tool sets. For example, via IDE based wizards, etc.

The learning curve and development time can be smaller compared to the Contract-first Web service. CONS:

The development time can be shorter to initially develop it, but what about the on going maintenance and extension time if the contract changes or new elements need to be added? In this approach, since the clients and servers are more tightly coupled, the future changes may break the client contract and affect all clients or require the services to be properly versioned and managed.

In this approach, The XML payloads cannot be controlled. This means changing your OXM libraries could cause something that used to be an element to become an attribute with the change of the OXM.

So, which approach will you choose? The best practice is to use "contract-first", and here is the link that explains this much better with examples --> contract-first versus contract-last web services In a nutshell, the contract-last is more fragile than the "contract-first". You will have to decide what is most appropriate based on your requirements, tool sets you use, etc.


Note: More Java Web Services interview questions and answers including WSDL, SOAP, UDDI, JAXR, SAAJ, etc are covered in Java/J2EE Job Interview Companion with diagrams.

Spring Interview Questions and Answers: Overview

Q. What do you understand by the terms Dependency Inversion Principle (DIP), Dependency Injection (DI) and Inversion of Control (IoC) container ? A.

Dependency Inversion Principle (DIP) is a design principle which is in

some ways related to the Dependency Injection (DI) pattern. The idea of DIP is that higher layers of your application should not directly depend on lower layers. Dependency Inversion Principle does not imply Dependency Injection. This principle doesnt say anything about how higher la yers know what lower layer to use. This could be done as shown below by coding to interface using a factory pattern or through Dependency Injection by using an IoC container like Spring framework, Pico container, Guice, or Apache HiveMind.

The Dependency Inversion Principle (DIP) states that

High level modules should not depend upon low level modules. Both should depend upon abstractions.

Abstractions should not depend upon details. Details should depend upon abstractions. When this principle is applied, the higher level classes will not be working directly with the lower level classes, but with an abstract layer. This gives us the flexibility at the cost of increased effort.Here are some code snippets for DIP. Firstly define the abstraction layer. ?

1 2 3 4 5

package principle_dip2; public interface AnimalHandler { public abstract void handle( ); }

1 2 3 4 5

package principle_dip2; public interface AnimalHelper { public abstract void help( ); }

Now the implementation that depends on the abstraction as opposed to the implementation. ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

package principle_dip2; public class CircusService { AnimalHandler handler; public void setHandler(AnimalHandler handler) { this.handler = handler; } public void showStarts( ) { //code omitted for brevity handler.handle( ); } }

1 2 3

package principle_dip2; public class TigerHandler implements AnimalHandler{

4 5 6 7 8 9 10 11 12 13 14 15 16

AnimalHelper helper; public void setHelper(AnimalHelper helper) { this.helper = helper; } public void handle( ){ //... ); //... } }

1 2 3 4 5 6 7 8

package principle_dip2; public class TigerHelper implements AnimalHelper{ public void help( ){ //...... } }

Dependency Injection (DI) is a pattern of injecting a classs dependencies into it at

runtime. This is achieved by defining the dependencies as interfaces, and then injecting in a concrete class implementing that interface to the constructor. This allows you to swap in different implementations without having to modify the main class. The Dependency Injection pattern also promotes high cohesion by promoting the Single Responsibility Principle (SRP), since your dependencies are individual objects which perform discrete specialized tasks like data access (via DAOs) and business services (via Service and Delegate classes) .


Inversion of Control Container (IoC) is a container that supports

Dependency Injection. In this you use a central container like Spring framework, Guice, or HiveMind, which defines what concrete classes should be used for what dependencies throughout your application. This brings in an added flexibility through looser coupling, and it makes it much easier to change what dependencies are used on the fly. The basic concept of the Inversion of Control pattern is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up. Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects. The real power of DI and IoC is realized in its ability to replace the compile time binding of the relationships between classes with binding those relationships at runtime. For example, in Seam framework, you can have a real and mock implementation of an interface, and at runtime decide which one to use based on a property, presence of another file, or some precedence values. This is incredibly useful if you think you may need to modify the way your application

behaves in different scenarios. Another real benefit of DI and IoC is that it makes your code easier to unit test. There are other benefits like promoting looser coupling without any proliferation of factory and singleton design patterns, follows a consistent approach for lesser experienced developers to follow, etc. These benefits can come in at the cost of the added complexity to your application and has to be carefully manged by using them only at the right places where the real benefits are realized, and not just using them because many others are using them. Note: The CDI (Contexts and Dependency Injection) is an attempt at describing a true standard on Dependency Injection. CDI is a part of the Java EE 6 stack, meaning an application running in a Java EE 6 compatible container can leverage CDI out-of-the-box. Weld is the reference implementation of CDI.

--> Q. In your experience, why would you use Spring framework? A.

Spring has a layered architecture with over 20 modules to choose from. This means, use what you need and leave what you don't need now. Spring simplifies JEE through POJO programming. There is no behind the scene magic in Spring as in JEE programming. POJO programming enables continuous integration and testability.

Spring framework's core functionality is dependency injection (DI). Dependency injection promotes easy unit testing and more maintainable and flexible code. DI code is much easier to test. The functionality expressed by the object can be tested in a black box by building 'mock' objects implementing the interfaces expected by your

application logic. DI code is much easier to reuse as the 'depended' functionality is extrapolated into well defined interfaces, allowing separate objects whose configuration is handled by a suitable application platform to be plugged into other objects at will. DI code is more flexible. It is innately loosely coupled code to an extreme. This allows the programmer to pick and choose how objects are connected based exclusively on their required interfaces on one end and their expressed interfaces on the other.

Spring supports Aspect Oriented Programming (AOP), which enables cohesive development by separating application business logic from system services. Supporting functionalities like auditing, gathering performanceand memory metrics, etc can be enabled through AOP.

Spring also provides a lot of templates which act as base classes to make using the JEE standard technologies a breeze to work with. For example, the JdbcTemplate works well with JDBC, the JpaTemplate does good things with JPA, JmsTemplate makes JMS pretty straightforward. The RestTemplate is simply awesome in it's simplicity. Simplicity means more readable and maintainable code.

When writing software these days, it is important to try and decouple as much middleware code from your business logic as possible. The best approach when using remoting is to use Spring Remoting which can then use any messaging or remoting technology under the covers. Apache Camel is a powerful open source integration framework based on known Enterprise Integration Patterns with powerful Bean Integration. Apache Camel is designed to work nicely with the Spring Framework in a number of ways.

It also provides declarative transactions, job scheduling, authentication, a fully-fledged MVC web framework, and integration to other frameworks like Hibernate, iBatis, JasperReports, JSF, Struts,Tapestry, Seam, Quartz job scheduler, etc.

Spring beans can be shared between different JVMs using Terracotta. This allows you to take existing beans and spread them across a cluster, turn Spring application context events into distributed events, export clustered beans via Spring JMX, and make your Spring applications highly available and clustered. Spring also integrate well with other clustering solutions like Oracle's Coherance.

Spring favors unchecked exceptions and eliminates unsightly try, catch, and finally (and some times try/catch within finally itself) blocks. The Spring templates like JpaTemplate takes care of closing or releasing a database connection. This prevents any potential resource leaks and promotes more readable code.

It prevents the proliferation of factory and singleton pattern classes that need to be created to promote loose coupling if not for using a DI framework like Spring or Guice. Q. In your experience, what do you don't like about Spring? Are there any pitfalls? A.

Spring has become very huge and bulky. So, don't over do it by using all its features because of the hype that Spring is good. Look at what parts of Spring really provides some benefits for your project and use those parts. In most cases, it is much better to use proven frameworks like Spring than create your own equivalent solution from a maintenance and applying the best practices perspective. For example, all spring templates (jdbc, rest, jpa etc.) have the following advantages -- perform common setup routines for you, let you skip the boilerplate and concentrate on the logic you want.

Spring MVC is probably not the best Web framework. There are other alternatives like Struts 2, Wicket, and JSF. Having said this, Spring integrates well with the other Web frameworks like Struts, JSF, etc. The XML files can get bloated. This can be minimized by carefully considering other options like annotations, JavaConfig, and having separate XML configuration files. Q. What are the different types of IoC (dependency injection) ? A. There are three types of dependency injection:

Constructor Injection (e.g. Spring): Dependencies are provided as constructor parameters.

Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods). Interface Injection (e.g. Avalon): Injection is done through an interface.

Q. Have you used any other Dependency Injection (DI) frameworks? A. Yes, Guice, Hivemind, and Seam.

Hibernate Interview Questions and Answers: Overview

Q. How will you configure Hibernate? A. The configuration files hibernate.cfg.xml (or and mapping files *.hbm.xml are used by the Configuration class to create (i.e. configure and bootstrap hibernate) the SessionFactory, which in turn creates the Session instances. Session instances are the primary interface for the persistence service. hibernate.cfg.xml (alternatively can use These two files are used to configure the hibernate sevice (connection driver class, connection URL, connection username, connection password, dialect etc). If both files are present in the classpath then hibernate.cfg.xml file overrides the settings found in the file. Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational database. It is the best practice to store each object in an individual mapping file (i.e mapping file per class) because storing large number of persistent classes into one mapping file can be difficult to manage and maintain. The naming convention is to use the same name as the persistent (POJO) class name. For example Account.class will have a mapping file named Account.hbm.xml. Alternatively, hibernate annotations can be used as part of your persistent class code instead of the *.hbm.xml files.

Q. What is a SessionFactory? Is it a thread-safe object? A. SessionFactory is Hibernate's concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an application code. SessionFactory sessionFactory = new Configuration( ).configure( ).buildSessionfactory( );

Q. What is a Session? Can you share a session object between different threads? A. Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get

the current session no matter how many times you make call to the currentSession( ) method. ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14

public class HibernateUtil { public static final ThreadLocal local = new ThreadLocal(); public static Session currentSession() throws HibernateException { Session session = (Session) local.get(); //open a new session if this thread has no session if(session == null) { session = sessionFactory.openSession(); local.set(session); } return session; } }

It is also vital that you close your session after your unit of work completes. Note: Keep your Hibernate Session API handy. Quite often, hibernate is used with Spring framework, using the HibernateTemplate.

--> Q. Explain hibernate object states? Explain hibernate objects life cycle? A. Persistent objects and collections are short lived single threaded objects, which store the persistent state. These objects synchronize their state with the database depending on your flush strategy (i.e. auto-flush where as soon as setXXX() method is called or an item is removed from a Set, List etc or define your own synchronization points with session.flush(), transaction.commit() calls). If you remove an item from a persistent collection like a Set, it will be removed from the database either immediately or when flush() or commit() is called depending on your flush strategy. They are Plain Old Java Objects (POJOs) and are currently associated with a session. As soon as the associated session is closed, persistent objects become detached objects and are free to use directly as data transfer objects in any application layers like business layer, presentation layer etc. Detached objects and collections are instances of persistent objects that were associated with a session but currently not associated with a session. These objects can be freely used as Data Transfer Objects without having any impact on your database. Detached objects can be later on attached to another session by calling methods like session.update(), session.saveOrUpdate() etc. and become persistent objects. Transient objects and collections are instances of persistent objects that were never associated with a session. These objects can be freely used as Data Transfer Objects without having any impact on your database. Transient objects become persistent objects when associated to a session by calling methods like ), session.persist( ) etc.

Q. What are the benefits of detached objects? A. Pros:

When long transactions are required due to user think-time, it is the best practice to break the long transaction up into two or more transactions. You can use detached objects from the first transaction to carry data all the way up to the presentation layer. These detached objects get modified outside a transaction and later on reattached to a new transaction via another session.


In general, working with detached objects is quite cumbersome, and it is better not to clutter up the session with them if possible. It is better to discard them and re-fetch them on subsequent requests. This approach is not only more portable but also more efficient because - the objects hang around in Hibernate's cache anyway.

Also from pure rich domain driven design perspective, it is recommended to use DTOs (DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service and UI tiers. Q. When does an object become detached? A. ?

1 2 3

Session session1 = sessionFactory.openSession(); <span id="IL_AD2" class="IL_AD">Car</span> myCar = session1.get(Car.class, carId); object at this stage. session1.close(); //once the session is closed myCar be

you can now pass the myCar object all the way upto the presentation tier. It can be modified without any effect to your database table. ?


//no effect on the database

When you are ready to persist this change to the database, it can be reattached to another session as shown below: ?

1 2 3 4 5

Session session2 = sessionFactory.openSession(); Transaction tx = session2.beginTransaction(); session2.update(myCar); //detached object myCar gets reattached tx.commit(); //change is synchronized with the database. session2.close()

Q. How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects? A.

Hibernate uses the "version" property, if there is one.

If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys.

Write your own strategy with Interceptor.isUnsaved( ). Note: When you reattach detached objects, you need to make sure that the dependent objects are reattached as well.