Using Java to Write to a Database – Part 2

Continuing from Part 1

In part 1 we created the simplest of databases, nothing more than a table with 2 columns.

There are two main ways to write an application in Java, in my opinion of course… the first is for native applications, those applications that run directly on your desktop or mobile device. The second is an application that runs on top of an application server, such as Tomcat. Tomcat would then, normally, provide a way to interface with the application through web pages or APIs.

Of course it is possible to run an application on an application server with no interfaces. This could be for tasks such as generating reports as a scheduled service and sending them via email. Therefore, no interaction and no interface.

So, in this part we will first focus on the most common use, Web Applications.

In this part we will use a JDBC connection so the data can be accessed in our applications.

For Connecting to a database with Tomcat <- use this link as it is the foundation for the rest of this post.

Now, hopefully, you have a database and a simple web application to pull data from that database. The next step is the purpose of this post, writing data back to the database.

In the same way you retrieved data, to write data back just takes a couple more steps.

public void getEntityTableName() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory(“jdbc/myDatabase”);
EntityManager em = emf.createEntityManager();
try {
PetTable petTable = new PetTable();
petTable.setName(“Rex”);
petTable.setKind(“Dog”);
EntityTransaction transaction = em.getTransaction();
transaction.begin();
em.merge(petTable);
transaction.commit();
} catch (Exception e) {
System.out.println(“e = ” + e);
} finally {
em.close();
emf.close();
}
}

The difference is the need to start and end a transaction. When writing data to a transactional database you need to obtain exclusive rights to the table where you are writing data to, just so no one else can write or delete data that you are using. What this also allows is the rolling back of changes if something goes wrong.

EntityTransaction transaction = em.getTransaction();
transaction.begin();

Make some changes to the database

transaction.commit();

That’s it, lastly you need to close the connections to the database, otherwise you could spawn multiple connections and cause a denial of service.

em.close();
emf.close();

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