Database independent JPA

Java EE 6 contains the JPA 2.0 specification. This means that applications that are built using this interface can be run using application servers that have their own implementation of the JPA 2.0.

Using JPA 2.0 in a Maven enabled Java project would require only this single dependency at provided scope:

<dependency>
	<groupId>javax</groupId>
	<artifactId>javaee-api</artifactId>
	<version>6.0</version>
	<scope>provided</scope>
</dependency>

Does this also mean, that your code can run on any database? No, it does not. It depends for instance on the capabilities of your database. A simple example is the use of auto generated numbers for primary keys. Oracle 11g does not support this, while Derby and MySQL databases do understand this.

The following code therefore, is only applicable to databases that understand and support the concept:

@Entity(name="users")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @XmlTransient
    @Column(name="user_id")
    private int id;

Oracle 11g users may need to use values taken from sequences:

@Entity(name="users") 
public class User { 

     @Id 
     @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="USER_SEQ")        
     @SequenceGenerator(name="USER_SEQ", sequenceName="USER_SEQ", allocationSize=10) 
     @XmlTransient 
     @Column(name="user_id") 
     private int id; 

Again, this is not a bad thing. Using the capabilites of a particular database has real benefit. However, it is wise to keep this in mind while developing and testing your solution. Once you start using functionality of a database that goes beyond simple SQL operations, you really should have such a database available in your development and test environment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s