Notes from my day to day Java and J2EE software development experiences and other related software development technologies.
Sunday, November 2, 2008
GIT Fast Version Control System
I got a chance to play with GIT fast version control system a bit. If anyone is interested in learning more about it, check out my article.
Sunday, October 12, 2008
Introducing Open Source Products to Your Company
A friend was trying to help introduce an open source product into his company, and I compiled some of the notes into an article. Enjoy!
Saturday, September 27, 2008
Run Groovy with Spring 2.5
Recently, I integrated Spring 2.5.6 with Groovy 1.5.6. For anyone trying to do this, let me say it is possible and not too difficult. Just remember Groovy is an extension of Java!
Here's an outline of the steps ..
1.) Create your application context for your Groovy classes. The application context is no different than the application context format as described here for Java applications.
You will need to setup your Spring beans and the overall "plumbing" for your application. The beans you create will connect your Groovy code to those components/services/etc in your application.
Also, include the base-package of your Groovy classes for the component scan. There is nothing different about specifying the local Groovy packages for the component scan vs. what is typically done in Java/Spring.
Here's an example...
2.) In your Groovy class load your application context from #1. Use the org.springframework.context.support.ClassPathXmlApplicationContext class to read your app context file.
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("classpath:your-appContext.xml")
3.) In your Groovy class grab the bean(s) that you need using the following code...
def yourService = appContext.getBean("yourBeanDefinedInAppContext")
4.) Code away! Use your local instance of "yourService" to get your Spring provided information to build out your logic.
That's it! I leave the practice of using annotations or other permutations of Spring up to you.
Please note, the most difficult part of Groovy/Spring may be finding an IDE that plays well with Groovy. I have used Eclipse and NetBeans. So far, NetBeans 6.5+ seems to have the best working environment for Groovy. A friend swears by IntelliJ for Groovy, but I haven't spent enough time with IntelliJ to comment. Eclipse with Groovy is OK, but a bit rough around the edges with the Groovy plugin (GroovyFeature).
Also, if you need information on how to build your Spring/Groovy classes try here.
Good luck!
Here's an outline of the steps ..
1.) Create your application context for your Groovy classes. The application context is no different than the application context format as described here for Java applications.
You will need to setup your Spring beans and the overall "plumbing" for your application. The beans you create will connect your Groovy code to those components/services/etc in your application.
Also, include the base-package of your Groovy classes for the component scan. There is nothing different about specifying the local Groovy packages for the component scan vs. what is typically done in Java/Spring.
Here's an example...
This snippet builds the classpath from
com.pacent.core.invoice.util.consolethrough the component-scan. If you are building your classpath through other means, just reuse your groovy package/classes to build that classpath.
2.) In your Groovy class load your application context from #1. Use the org.springframework.context.support.ClassPathXmlApplicationContext class to read your app context file.
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("classpath:your-appContext.xml")
3.) In your Groovy class grab the bean(s) that you need using the following code...
def yourService = appContext.getBean("yourBeanDefinedInAppContext")
4.) Code away! Use your local instance of "yourService" to get your Spring provided information to build out your logic.
That's it! I leave the practice of using annotations or other permutations of Spring up to you.
Please note, the most difficult part of Groovy/Spring may be finding an IDE that plays well with Groovy. I have used Eclipse and NetBeans. So far, NetBeans 6.5+ seems to have the best working environment for Groovy. A friend swears by IntelliJ for Groovy, but I haven't spent enough time with IntelliJ to comment. Eclipse with Groovy is OK, but a bit rough around the edges with the Groovy plugin (GroovyFeature).
Also, if you need information on how to build your Spring/Groovy classes try here.
Good luck!
Thursday, September 25, 2008
Galileo still Provides a bit of Angst 400 years after his death
The Catholic church recently commissioned a statue of Galileo 400 years after being accused of heresy for stating the Earth revolved around the sun. Yes, I know a diversion, but an interesting diversion for those who don't know the history.
Wednesday, July 16, 2008
Groovy is ... well Groovy!
There are so many great things about Groovy from helper classes for Collections, XML/HTTP/SWING/etc builders, simple parsers, closures, a built in shell to run classes and groovy scripts, and many more. Since this is a blog and not a book, I wanted to highlight one interesting feature of Groovy that helped me understand the true concept of the "meta-language".
Groovy in a way generalizes many of the classes that most Java developers are accustomed to managing in day to day code. In Groovy we deal with POJOs, Plain Old Groovy Objects (POGOs), and interceptors. Groovy has provided a layer to capture each object type. In general this layer is called the Meta-Object Protocol (MOP).
Let's take each object type for a bit of a spin...
class TestMethods extends GroovyTestCase
{
void testPOJO()
{
def val = new String("test method call on POJO")
assertEquals "test method call on POJO" , val.toString()
}
void testInterceptedPOJO()
{
def val = new Integer (999)
Integer.metaClass.toString = {-> 'intercepted at testIntercepted test case' }
assertEquals "intercepted at testIntercepted test case" , val.toString()
}
void testInterceptable()
{
def obj = new InterceptableObject()
assertEquals 'intercepted existingMethod on object', obj.method1()
assertEquals 'intercepted existingMethod on object', obj.method2()
assertEquals 'intercepted existingMethod on object' , obj.existingMethod()
assertEquals 'intercepted existingMethod on object' , obj.nonExistingMethod()
}
}
// Interceptable Object
class InterceptableObject implements GroovyInterceptable
{
def invokeMethod(String name, args) {'intercepted existingMethod on object'}
def method1() {'method1 called'}
def method2() { 'method2 called' }
}
// POGO
class GroovyObject
{
def method1() { 'method1' }
def method2() { 'method2' }
def closureProp = { 'closure called' }
}
Notice that there are several methods for intercepting objects based on the object type (POGO, POJOs, and interceptors) It is also possible to create closures at runtime which essentially injects a new method into an object.
The Interceptable class and testInterceptable method demonstrate a few ideas. The first is that invokeAll will overide all methods in an object. Both method1() and method2() will return "intercepted existingMethod on object" in these examples. Also, Groovy provides the existingMethod() and nonexistingMethod() which define closures for any existing or nonexisting method. This can be useful for catching generic cases that might not fall under a set of predefined methods.
There is a lot more to describe with MOP and dynamic Groovy, and more can be found here. Also, I hope to soon cover DSLs and Groovy which is itself a great topic.
Groovy in a way generalizes many of the classes that most Java developers are accustomed to managing in day to day code. In Groovy we deal with POJOs, Plain Old Groovy Objects (POGOs), and interceptors. Groovy has provided a layer to capture each object type. In general this layer is called the Meta-Object Protocol (MOP).
Let's take each object type for a bit of a spin...
class TestMethods extends GroovyTestCase
{
void testPOJO()
{
def val = new String("test method call on POJO")
assertEquals "test method call on POJO" , val.toString()
}
void testInterceptedPOJO()
{
def val = new Integer (999)
Integer.metaClass.toString = {-> 'intercepted at testIntercepted test case' }
assertEquals "intercepted at testIntercepted test case" , val.toString()
}
void testInterceptable()
{
def obj = new InterceptableObject()
assertEquals 'intercepted existingMethod on object', obj.method1()
assertEquals 'intercepted existingMethod on object', obj.method2()
assertEquals 'intercepted existingMethod on object' , obj.existingMethod()
assertEquals 'intercepted existingMethod on object' , obj.nonExistingMethod()
}
}
// Interceptable Object
class InterceptableObject implements GroovyInterceptable
{
def invokeMethod(String name, args) {'intercepted existingMethod on object'}
def method1() {'method1 called'}
def method2() { 'method2 called' }
}
// POGO
class GroovyObject
{
def method1() { 'method1' }
def method2() { 'method2' }
def closureProp = { 'closure called' }
}
Notice that there are several methods for intercepting objects based on the object type (POGO, POJOs, and interceptors) It is also possible to create closures at runtime which essentially injects a new method into an object.
The Interceptable class and testInterceptable method demonstrate a few ideas. The first is that invokeAll will overide all methods in an object. Both method1() and method2() will return "intercepted existingMethod on object" in these examples. Also, Groovy provides the existingMethod() and nonexistingMethod() which define closures for any existing or nonexisting method. This can be useful for catching generic cases that might not fall under a set of predefined methods.
There is a lot more to describe with MOP and dynamic Groovy, and more can be found here. Also, I hope to soon cover DSLs and Groovy which is itself a great topic.
Friday, July 11, 2008
Run Windows XP on Ubuntu using VMWare
I had a few apps that I still use in Windows :( which motivated me to run Windows XP on my 64bit Ubuntu v2.6.24-19 using VMWare server. Thanks to my amigo Dave Riches for getting me started on this. For all my other colleagues that have asked about this, here are the steps and some details on how to set this up.
First, download the VMWare Image Converter from here. Install this on your Windows box and create a VMWare image using the VMWare image converter wizard. The details within the wizard depend on your situation. I believe most settings can be modified later, so your setup is by no means permanent. If you have the ability to clean out your Windows OS before making an image, I would recommend a good cleanup. I had 56GB of files and starting this image later in VWWare server proved to be extremely slow. An image of a clean OS install would be the best scenario.
Next, move the image to your Ubuntu OS. I had a 500GB external hard drive that I used to move the images over. The image converter allows copying over the network too to your target Ubuntu server. All you need is a Samba mount on Ubuntu to move the files over if you choose to move your image over the network.
Now install the VMWare Server on your Ubuntu OS. There are also instructions out there which describe the VMPlayer setup too. Here's a good article on how to do that, and this also describes how to workaround a header issue that some Ubuntu versions (v2.6.24.16) had with VMWare Player/Server installation.
You will also need a C compiler installed on your Ubuntu machine. The VMWare install will compile all of the libraries during install. The installation will give you specifics if you are missing anything.
Fire up VMWare Server/Player now! You might see something like this..
VMware Player unrecoverable error: (vcpu-0)
Failed to allocate page for guest RAM!
A log file is available in "/path/to/VM/vmware.log". A core file is
available in "/path/to/VM/core". Please request support and include
the contents of the log file and core file.
To collect data to submit to VMware support, run "vm-support".
We will respond on the basis of your support entitlement.
Looking at the VMware log file will show the message "Could not mmap
paging file : No such device".
There is a setting in the Virtual Machine's .vmx config file to fix
this. Edit the config file, add
mainMem.useNamedFile=FALSE
I was finally able to start my VMWare image. The next issue was extremely slow startup time. No biggie, I'll just go grab a cup of coffee.... in the next state! Yah this was slow. I had to tweek some things to get the speed into acceptable condition. These tweeks included...
Good luck!
First, download the VMWare Image Converter from here. Install this on your Windows box and create a VMWare image using the VMWare image converter wizard. The details within the wizard depend on your situation. I believe most settings can be modified later, so your setup is by no means permanent. If you have the ability to clean out your Windows OS before making an image, I would recommend a good cleanup. I had 56GB of files and starting this image later in VWWare server proved to be extremely slow. An image of a clean OS install would be the best scenario.
Next, move the image to your Ubuntu OS. I had a 500GB external hard drive that I used to move the images over. The image converter allows copying over the network too to your target Ubuntu server. All you need is a Samba mount on Ubuntu to move the files over if you choose to move your image over the network.
Now install the VMWare Server on your Ubuntu OS. There are also instructions out there which describe the VMPlayer setup too. Here's a good article on how to do that, and this also describes how to workaround a header issue that some Ubuntu versions (v2.6.24.16) had with VMWare Player/Server installation.
You will also need a C compiler installed on your Ubuntu machine. The VMWare install will compile all of the libraries during install. The installation will give you specifics if you are missing anything.
Fire up VMWare Server/Player now! You might see something like this..
VMware Player unrecoverable error: (vcpu-0)
Failed to allocate page for guest RAM!
A log file is available in "/path/to/VM/vmware.log". A core file is
available in "/path/to/VM/core". Please request support and include
the contents of the log file and core file.
To collect data to submit to VMware support, run "vm-support".
We will respond on the basis of your support entitlement.
Looking at the VMware log file will show the message "Could not mmap
paging file : No such device".
There is a setting in the Virtual Machine's .vmx config file to fix
this. Edit the config file, add
mainMem.useNamedFile=FALSE
I was finally able to start my VMWare image. The next issue was extremely slow startup time. No biggie, I'll just go grab a cup of coffee.... in the next state! Yah this was slow. I had to tweek some things to get the speed into acceptable condition. These tweeks included...
- Set the VMWare image memory settings closer to the recommended memory. VMWare server will tell you the recommended setting. Mine was 256M, but I doubled that to 512M and I immediately saw an improvement.
- Install VMWare tools. VMWare Server has an option to do this.
NOTE: the tools are installed into the VMWare image, not the player/server. I am presuming that once the tools are installed into my image I could go back and run my image in VMWarePlayer with the same tools installed.
Once the VMWare tools were installed, I noticed improvements in both video resolution and less choppy mouse movements. - I removed a lot of crud on my image. This included PICASA which does some background processing at the startup of my VMWare image. There was a floppy drive that I removed from the image that will never be used. This is really the part where you can be creative and is also why I earlier recommended creating an image with the smallest footprint possible.
Good luck!
Monday, June 16, 2008
Windows WAV Compilation
Here's a fascinating compilation of those annoying little Windows wav sounds for emails, errors, startup, etc.
Friday, June 13, 2008
NetBeans 6.1 Install Fun on Ubuntu 8.04
I just worked through a nagging little assertion error during a NetBeans 6.1 install to Ubuntu 8.04. Hopefully this helps someone.
First I made sure that I had Java 6 downloaded and installed on my 64 bit Ubuntu 8.04 OS.
I noticed the install script scans my hardware for jvms as early as 1.5. Here's the section of netbeans-6.1_ml-linux.sh that contains that information...
setJavaCompatibilityProperties_0() {
JAVA_COMP_VERSION_MIN="1.6.0_03"
JAVA_COMP_VERSION_MAX=""
JAVA_COMP_VENDOR=""
JAVA_COMP_OSNAME=""
JAVA_COMP_OSARCH=""
}
Notice I changed JAVA_COMP_VERSION_MIN to 1.6XXX. With the default settings the NetBeans install was picking up 1.5. I was getting Assertion errors and after using the sed option in this thread a blank welcome screen. After changing JAVA_COMP_VERSION_MIN the installer picked up 1.6 and ran fine. W00t! W00t!
First I made sure that I had Java 6 downloaded and installed on my 64 bit Ubuntu 8.04 OS.
I noticed the install script scans my hardware for jvms as early as 1.5. Here's the section of netbeans-6.1_ml-linux.sh that contains that information...
setJavaCompatibilityProperties_0() {
JAVA_COMP_VERSION_MIN="1.6.0_03"
JAVA_COMP_VERSION_MAX=""
JAVA_COMP_VENDOR=""
JAVA_COMP_OSNAME=""
JAVA_COMP_OSARCH=""
}
Notice I changed JAVA_COMP_VERSION_MIN to 1.6XXX. With the default settings the NetBeans install was picking up 1.5. I was getting Assertion errors and after using the sed option in this thread a blank welcome screen. After changing JAVA_COMP_VERSION_MIN the installer picked up 1.6 and ran fine. W00t! W00t!
Sunday, May 25, 2008
The Power of JPA
JPA has provided a useful method to persist entities in a quick and repeatable fashion. Using JPA as an Object Relational Mapping tool (ORM), a developer can rapidly create the persistence layer to the point where the db is another service layer that is managed through annotations within the code.
Here's an example of another entity class...
The entity itself contains the information on primary keys, preset queries, foreign keys, db table relations, class information, and much more. This makes the job of returning and managing an object from the db simple.
For example, all that is needed to find all of the Product classes assigned to a specific Category class would be the following...
Query query2 = em.createNamedQuery("ProductCategory.findByCategory") ;
query2.setParameter("category", category);
productList = query2.getResultList();
Where category is an instance of the Category class and the Named Query "ProductCategory.findByCategory is defined in the ProductCategory Entity class above as follows...
query = "SELECT p FROM ProductCategory p WHERE p.category = :category"
The getResultList method will return a List of Product Objects. All that remains to persist the ProductCategory join table is to add this class to the persistence.xml and to get an instance of the entity manager. The following code will use a factory method to create an instance of the entity manager.
EntityManagerFactory emf;
EntityManager em;
String PERSISTENCE_UNIT_NAME = "ReviewModulePU";
emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em = emf.createEntityManager();
Category category = null ;
try {
Query query = em.createNamedQuery("Category.findByDescription");
query.setParameter("description", getSessionBean1().getSelectedCategory().getDescription());
category = (Category) query.getSingleResult();
Query query2 = em.createNamedQuery("ProductCategory.findByCategory") ;
query2.setParameter("category", category);
productList = query2.getResultList();
setProdByCatTable(new ReviewListTableBean[productList.size()]);
for (int i=0;i<productList.size();i++) {
if (productList.get(i).getProduct() != null) {
Product specificProduct = productList.get(i).getProduct() ;
ReviewListTableBean PICBean = new ReviewListTableBean() ;
PICBean.setDescription(specificProduct.getDescription());
PICBean.setHomePage(specificProduct.getUrl());
PICBean.setImageUrl(specificProduct.getImageUrl()) ;
PICBean.setProductName(specificProduct.getTitle());
getProdByCatTable()[i]=PICBean ;
}
}
} catch (Exception qe) {
System.out.println(this.getClass().toString() + " Exception: " + qe.toString());
} finally {
em.close();
emf.close();
}
Here's an example of another entity class...
package reviewmodule.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
/**
*
* @author Rob
*/
@Entity
@Table(name = "product_category")
@NamedQueries({@NamedQuery(name = "ProductCategory.findByProdId", query = "SELECT p FROM ProductCategory p WHERE p.product = :prod"), @NamedQuery(name = "ProductCategory.findByCategory", query = "SELECT p FROM ProductCategory p WHERE p.category = :category")})
public class ProductCategory implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "PRODCAT_ID")
private long id;
@OneToOne
@JoinColumn(name = "PROD_ID", nullable=false)
private Product product;
@ManyToOne
@JoinColumn(name = "CATEGORY_ID", nullable=false)
private Category category ;
public ProductCategory() {
}
public ProductCategory(Product product, Category category){
this.setProduct(product);
this.setCategory(category);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
/**
*
* @author Rob
*/
@Entity
@Table(name = "product_category")
@NamedQueries({@NamedQuery(name = "ProductCategory.findByProdId", query = "SELECT p FROM ProductCategory p WHERE p.product = :prod"), @NamedQuery(name = "ProductCategory.findByCategory", query = "SELECT p FROM ProductCategory p WHERE p.category = :category")})
public class ProductCategory implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "PRODCAT_ID")
private long id;
@OneToOne
@JoinColumn(name = "PROD_ID", nullable=false)
private Product product;
@ManyToOne
@JoinColumn(name = "CATEGORY_ID", nullable=false)
private Category category ;
public ProductCategory() {
}
public ProductCategory(Product product, Category category){
this.setProduct(product);
this.setCategory(category);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
The entity itself contains the information on primary keys, preset queries, foreign keys, db table relations, class information, and much more. This makes the job of returning and managing an object from the db simple.
For example, all that is needed to find all of the Product classes assigned to a specific Category class would be the following...
Query query2 = em.createNamedQuery("ProductCategory.findByCategory") ;
query2.setParameter("category", category);
productList = query2.getResultList();
Where category is an instance of the Category class and the Named Query "ProductCategory.findByCategory is defined in the ProductCategory Entity class above as follows...
query = "SELECT p FROM ProductCategory p WHERE p.category = :category"
The getResultList method will return a List of Product Objects. All that remains to persist the ProductCategory join table is to add this class to the persistence.xml and to get an instance of the entity manager. The following code will use a factory method to create an instance of the entity manager.
EntityManagerFactory emf;
EntityManager em;
String PERSISTENCE_UNIT_NAME = "ReviewModulePU";
emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em = emf.createEntityManager();
Category category = null ;
try {
Query query = em.createNamedQuery("Category.findByDescription");
query.setParameter("description", getSessionBean1().getSelectedCategory().getDescription());
category = (Category) query.getSingleResult();
Query query2 = em.createNamedQuery("ProductCategory.findByCategory") ;
query2.setParameter("category", category);
productList = query2.getResultList();
setProdByCatTable(new ReviewListTableBean[productList.size()]);
for (int i=0;i<productList.size();i++) {
Product specificProduct = productList.get(i).getProduct() ;
ReviewListTableBean PICBean = new ReviewListTableBean() ;
PICBean.setDescription(specificProduct.getDescription());
PICBean.setHomePage(specificProduct.getUrl());
PICBean.setImageUrl(specificProduct.getImageUrl()) ;
PICBean.setProductName(specificProduct.getTitle());
getProdByCatTable()[i]=PICBean ;
}
}
} catch (Exception qe) {
System.out.println(this.getClass().toString() + " Exception: " + qe.toString());
} finally {
em.close();
emf.close();
}
Sunday, April 13, 2008
Javascript Made Easy: Prototype and Scriptaculous
A reader suggested I read Prototype & Scriptaculous in Action by Dave Crane, Bear Bibeault, and Tom Locke. All I can say is Thanks!! What a great read.. If anyone is interested in throwing in highly professional Javascript effects into their webpages, or using the Protoype library to simplify Javascript for dynamic web pages, I highly recommend skipping the online information and go straight to this book.
I'll try and provide some more details later. I have a busy day today :)
I'll try and provide some more details later. I have a busy day today :)
Glassfish on Ubuntu
Glassfish v2ur1 was surprisingly easy to install on Ubuntu 7.10 server version on an x386 desktop. Here's the breakdown of the steps...
1.) Install JDK 5 or later on Ubuntu.
3.) Set JAVA_HOME to the JDK you have installed on your system. (i.e /usr/lib/jvm/java-1.5.0-sun-1.5.0.13)
4.) Run:
1.) Install JDK 5 or later on Ubuntu.
sudo apt-get install sun-java5-jdk2.) At this point I created an /opt/app directory and copied the glassfish installer to /opt/app to expand and execute.
3.) Set JAVA_HOME to the JDK you have installed on your system. (i.e /usr/lib/jvm/java-1.5.0-sun-1.5.0.13)
4.) Run:
% java -Xmx256m -jar filename.jar
This command will unbundle GlassFish and create a new directory named 'glassfish' rooted under the current directory.- If you want to run glassfish as an app user this is the point to chown -R
: glassfish. Then run steps #3 and #4 as the -
% cd glassfish
-
% chmod -R +x lib/ant/bin
% lib/ant/bin/ant -f setup.xml
Wednesday, January 30, 2008
CAPTCHA hacked
A Russian programmer has claimed his software can read 35% of CAPTCHA. This is an interesting problem to solve with a visual recognition system, but the end result according to this article is more than likely selling out to Spammers. Boo!
Article
Too bad this system wouldn't be used for useful purposes.
Article
Too bad this system wouldn't be used for useful purposes.
Thursday, January 10, 2008
Using JPA to bind Entity Beans to a Database
Here's a quick step thru of how to use JPA to bind an entity bean to a database table. This example uses Glassfish v2. It is amazing at how simple persisting entity beans has become with both EJB 3.0/JPA.
1.) Create Entity Beans.
2.) Configure the persistence unit. I created a persistence.xml file for Glassfish with the following contents...
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="ReviewModulePU" transaction-type="JTA">
<jta-data-source>review</jta-data-source>
<class>reviewmodule.entity.Category</class>
<class>reviewmodule.entity.Company</class>
<class>reviewmodule.entity.Product</class>
<class>reviewmodule.entity.Review</class>
<class>reviewmodule.entity.User</class>
<class>reviewmodule.entity.WatchList</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
</properties>
</persistence-unit>
</persistence>
Each class signifies 1 of several entity beans.
3.) Add the following code to persist the data objects as they are defined...
EntityManagerFactory emf;
EntityManager em;
String PERSISTENCE_UNIT_NAME = "ReviewModulePU";
emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em = emf.createEntityManager();
em.getTransaction().begin();
try{
// org is an entity bean that is being persisted to the db
em.persist(org);
em.getTransaction().commit();
} finally {
em.close();
emf.close();
}
This is an oversimplified example. It does by no means manage retrieving data objects or attempt to abstract the entity beans in any controlled manner. It is just the quick and ugly version for future reference.
1.) Create Entity Beans.
2.) Configure the persistence unit. I created a persistence.xml file for Glassfish with the following contents...
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="ReviewModulePU" transaction-type="JTA">
<jta-data-source>review</jta-data-source>
<class>reviewmodule.entity.Category</class>
<class>reviewmodule.entity.Company</class>
<class>reviewmodule.entity.Product</class>
<class>reviewmodule.entity.Review</class>
<class>reviewmodule.entity.User</class>
<class>reviewmodule.entity.WatchList</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
</properties>
</persistence-unit>
</persistence>
Each class signifies 1 of several entity beans.
3.) Add the following code to persist the data objects as they are defined...
EntityManagerFactory emf;
EntityManager em;
String PERSISTENCE_UNIT_NAME = "ReviewModulePU";
emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em = emf.createEntityManager();
em.getTransaction().begin();
try{
// org is an entity bean that is being persisted to the db
em.persist(org);
em.getTransaction().commit();
} finally {
em.close();
emf.close();
}
This is an oversimplified example. It does by no means manage retrieving data objects or attempt to abstract the entity beans in any controlled manner. It is just the quick and ugly version for future reference.
Subscribe to:
Posts (Atom)