Using the Database.com Java SDK

If you’re a Java developer reading this blog (i.e. you have some interest in the Force.com platform), you’ve probably heard of Java on Heroku – one the biggest announcements at this year’s Dreamforce. You can now “slip the surly bonds” of your local J2EE app server by deploying your Java apps to Heroku and taking advantage of all the benefits that a polygot PAAS platform like Heroku provides. Java on Heroku has deservedly gotten a lot of attention and press and if you’re interested in learning more, check out this great Dreamforce session recording by the very esteemed James Ward. There was however another exciting Java related announcement around the time of Dreamforce that you may have missed – the Beta release of the Database.com Java SDK. I’d like to spend some time talking about the SDK and so lets break it down.

1) So, it’s an SDK for Database.com? – Yes and no. Even though the official name for the SDK is the ‘Database.com Java SDK’, you can use it to connect to both Database.com and Force.com/Salesforce.

2), Got it. So what is it? At the highest level, the SDK provides a JPA 2.0 interface to Database.com/Force.com. If allows any Java application to use Database.com or Force.com as their persistence/data layer and use the standard JPA interface provided by the SDK to query and update data from our platform. And the SDK is completely runtime agnostic in that you can deploy your application to a cloud environment that supports Java (e.g. Heroku), or to a local J2EE container – the SDK works in all cases. In addition to a JPA interface, the SDK also has a couple of other very important components/value adds.

3) But I can already connect my Java app to Database.com/Force.com. Why do I need the SDK? - Its true that Java applications (or any other language/platform for that matter) have always been able to integrate with Force.com using one of our APIs – for e.g. the Web Services (SOAP) API or the REST API. What’s different with the SDK is that you can now use a J2EE standard – JPA – to do the same. No WSDL/XML/JSON  to parse or consume – simply use the standard ORM functionality provided by JPA and simplify and standardize your Java code. Other than the JPA provider, the SDK also has other components that provide additional value-adds to Java developers.

4) How is the SDK related to Java on Heroku? – As mentioned before, the SDK has absolutely no direct dependency on Java on Heroku. You can use the SDK no matter what you runtime environment. The only real intersection of the two is if you wanted to deploy a Java application to Heroku that used Database.com/Force.com as its persistence layer.

5) What are the various components of the SDK?

5.1) JPA Provider: The most important component of the SDK is obviously the JPA 2.0 provider. Here is quick snippet from a Java application that uses a simple ‘Album’ Entity with a Many-to-One relationship to the ‘Artist’ Entity.

@Entity
public class Album {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private String id;

    private String name;

    @DateTimeFormat(iso=ISO.DATE)
    @Column(nullable = false)
    private Date releaseDate;

    @ManyToOne
    @CustomField(type= FieldType.MasterDetail)
    private Artist artist;
    ....
    //Public accessor and mutator methods for the above variables
}

Anyone familiar with JPA will instantly recognize this code. JPA uses a POJO based persistence model and relies heavily on annotations – both of which you can see in the above snippet. The SDK supports most of the standard JPA annotations and adds a couple of custom ones (e.g. the ‘@CustomField(type= FieldType.MasterDetail)’ used above). Here is another small snippet of how you can query and update data from the Album entity using the SDK.

public static EntityManagerFactory emf = 
                  Persistence.createEntityManagerFactory("forceDatabase");

public void saveArtistRecord(Artist artist) {
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    tx.begin();

    if(artist.getId()==null) {
		em.persist(artist);
	} else {
		artist = em.find(Artist.class, artist.getId());
		artist =  em.merge(artist);
	}

	tx.commit();
}

public static List<Album> getAlbumsByName(String albumName) {
	if(albumName==null) {
		throw new IllegalArgumentException("Album name cannot be null");
	}

	EntityManager em = emf.createEntityManager();

	String jpqlQuery = "SELECT a FROM Album a WHERE a.Name LIKE '%s'";
	jpqlQuery =	String.format(jpqlQuery,albumName);

	List<Album> albums = em.createQuery(jpqlQuery).getResultList();
	return albums;
}

Its all standard JPA code, including the use of JPQL (which the SDK supports) to query Database.com/Force.com data. Under the covers, the Album and Artist Entities will be mapped by the SDK to corresponding Custom Objects in the respective Database.com/Force.com Org. The SDK can even keep your data model in sync automatically. If you add a new Entity class (or a new field to an existing Entity class) and restart your application, the SDK will automatically detect these schema changes and create the custom object/field automatically in Database.com/Force.com.

5.2) OAuth and Spring Security: The SDK also has an OAuth component that lets you delegate the authentication and authorization for your Java web app to Salesforce. You only have to configure a couple of OAuth parameters (not a single line of code required) and every time a user tries to access your Java app they will be redirected to Salesforce to login and then redirected back to your Java app. The SDK also includes a Spring Security plugin that “wraps” this OAuth component and lets you delegate security for Spring MVC apps to Salesforce.

5.3) Maven Code generation plugin: Though not technically part of the SDK, I still see this as another component of the SDK. If you have your data model already defined in Database.com/Force.com using some Standard and/or Custom Objects, you can run a simple Maven command and generate the corresponding JPA Entity classes. This cuts down on your development time significantly.

6) This all sounds great! How do I get started? Check out the SDK’s home page for additional details and to get started. You can also watch a recording of the Dreamforce session where I previewed the SDK.

tagged , , , Bookmark the permalink. Trackbacks are closed, but you can post a comment.
  • kamlesh Patel

    Hello, In the spring JPA example, username and password are part of property file. How can we make it to force user based authentication (i.e. redirect to Salesforce.com and back)? Also how to retrieve token so as to call REST API once authenticated. Thanks, Kam

  • Anonymous

    Kamlesh,
    For user based authentication, you’ll need to enable the OAuth plugin (or Spring Security plugin if you’re developing a Spring app) component of the SDK. You can find details on how to do that here – http://forcedotcom.github.com/java-sdk/oauth-auth (for OAuth) and http://forcedotcom.github.com/java-sdk/spring-security (for Spring Security).
    As to your 2nd question, what is your exact use case? The general reason of using the Java SDK is that you can use the standard JPA interface to perform CRUD access to Force.com/DB.com data – you don’t need to drop down to the API level. You could probably look at the SDK code (its open source and on GitHub) to figure out how to extract the access token from the OAuth plugin, but that’s a fair amount of work. Is there a particular reason that you want to use the REST API and not the JPA interface?

  • kamlesh Patel

    Hello,

    Thanks for your prompt reply. I tried implementing http://forcedotcom.github.com/java-sdk/spring-security but documentation is not clear so having hard time to understand.

    I would like to use JPA for Create/Update/Delete transactions which is not easy from from any other language other then Java JPA or Apex classes. Am I right saying that?

    For read only stuff I would like to use REST APIs which outputs JSON which can be consumed by mobile clients directly. So no need to use JPA and Java. What I like about salesforce REST interface is that once you add a field, entity or relationship REST interface automatically exposes all. Whereas with Java it’s all about compilation.

    Please help me if I am not getting it right.

    Thanks a lot.

  • Anonymous

    In order to get Spring Security working, have you looked at the Maven template project (http://forcedotcom.github.com/java-sdk/quick-start) and the configuration for it? That should help you get the config right in your own app.
    As to the other question, there really is not difference between query vs. update/create/delete when it comes to the JPA adapter vs the REST API. You can do either one easily using either the JPA adapter or the REST API. The choice between the 2 really comes down to the use case. If its a mobile Android client, the obviously JPA is not an option and you’ll have to use the REST API for all data query/manipulation actions. If on the other hand you have a Java web app that needs to connect with Force.com/DB.com you can choose to use either the JPA adapter or the REST API (if you prefer JSON), Either one would work. Hope this helps.