Wednesday, June 10, 2009

Setting EclipseLink 1.1 and Spring 2.5.6 in Eclipse 3.4

This article provides an example of using Spring framework 2.5.6 JPA and Test framework to create a record in the MySQL database. Here we are using EclipseLink 1.1 for the JPA implementation.

I will try to provide all jars and config files necessary to get EclipseLink 1.1 going and also include a simple test case. You will need to have basic knowledge of JPA and have experience using Eclipse IDE.

First you need the following spring 2.5.6 jars. Using Eclipse you can edit your build path and add these libraries.

spring-framework\dist\modules\spring-orm.jar
spring-framework\dist\modules\spring-test.jar
spring-framework\dist\modules\spring-beans.jar
spring-framework\dist\modules\spring-context.jar
spring-framework\dist\modules\spring-context-support.jar
spring-framework\dist\modules\spring-core.jar
spring-framework\lib\junit\junit-4.4.jar
spring-framework\dist\modules\spring-jdbc.jar
spring-framework\dist\weaving\spring-agent.jar
eclipselink\jlib\eclipselink.jar
eclipselink\jlib\jpa\javax.persistence_1.99.0.jar

In your Java project, you will need to configure the persistence.xml in the META-INF folder.

persistence.xml


Next you will need to create a Spring configuration file as follows.

databaseContext.xml



Create a bean called Product in the my package.

eg

@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;

String name;
....

}
Create a DAO class called ProductDao

ProductDao

@Repository
public class ProductDao {

@PersistenceContext
EntityManager em;

public void create(Product product) {
em.persist(product);
}
}


Next create the testcase to test the persistence...

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/databaseContext.xml"})
public class TestDatabaseConnectionCreation {

//Need to test auto creation of tables...
@Autowired
ProductDao dao;

@Test
public void testCreate() {
Product p = new Product();
p.setName("It works");
dao.create(p);
}
}


Note I had to put the runtime weaver in the Run configuration Arguments tab VM arguments as such...

-javaagent:D:\devtools\spring-framework-2.5.6.SEC01\dist\weaving\spring-agent.jar

You will also need to include the MySQL JDBC driver...

You can now right click on the testCreate() and select run as Junit Test. Magic should happen as follows

  • Spring framework should load,
  • Connects to the MySQL database
  • Creates the product table
  • Inserts a product record to the table
  • Rollback the transaction (note the table remains in the database)

No comments:

Post a Comment