Programming
30 May 2012 0 Comments

Using @DataSourceDefinition in Java EE 6 With Postgresql

Introduction

Java EE applications use DataSource objects when they access relational databases through the JDBC API. Typically the Datasource that should be used is referenced by its Java Naming and Directory Interface (JNDI) name in the persistence.xml file:

>java:app/env/myDatasource>

The Datasource details (host, username, password, database type) for this JNDI name need to be declared somewhere. Prior to Java EE 6, you could create a DataSource object using vendor-specific mechanisms. This could be a deployment descriptor for the application server in the WAR, e.g. glassfish-web.xml or XML configuration files in the application server directory.

In Java EE 6 the @DataSourceDefinition annotation was introduced. With this annotation you can declare ‘application server agnostic’ datasources directly in your code. While this is usually a bad idea for production code, it can be very useful for testing, since you don’t have to change the configuration of the application server. You can just deploy the WAR in any application server and it will run.

In this example we run through the steps for…

Tags: datasourcedefinition, entitymanager,
Programming
28 May 2012 1 Comment

Adding JPA Support to a Maven/Eclipse/JSF2 Project

Introduction

the Java Persistence API (JPA) allows for easy managing of relational data in Java applications. It is a replacement of the much criticized EJB 2.0 and EJB 2.1 entity beans. In this post we show how to add JPA support to an existing Maven/Eclipse/JSF2 project with Java EE 6.

With JPA you can do create an entity that is backed by a table in the database. For example you can create a persisted entity (which is just a POJO with some annotations):

Name.java

import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.Column;
 
@Entity
@Table(name="CUSTOMER_INFORMATION")
public class Customer {
    private String name;
 
    @Id
    @Column(name="FULL_NAME")
    public int getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name= name;
    }
}

And a client class that fetches all customer names with and prints them:
Client.java

import javax.persistence.Persistence;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
 
public class Client