Thursday, June 11, 2009

Handy command to see whether a class file exists in your lib/dir

$find ~chiradip/.m2/repository/ -name *.jar -exec jar tvf {} \; egrep 'Spring'
Another command that does the similar thing
$for line in `ls *.jar`; do echo $line; jar tvf $line egrep 'Spring'; done

Running JPA test cases in Maven

First thing first. The directory structure should look like this.
 
  +- pom.xml
  +- src
  |  +- main
  |  |  +- java
  |  |  |  +- mypackage
  |  |  |  |  +- MyEntity.java
  |  |  +- resources
  |  |  |  +- META-INF
  |  |  |  |  +- persistence.xml
  |  +- test
  |  |  +- java
  |  |  |  +- mypackage
  |  |  |  |  +- MyPersistenceTest.java
 
second thing second ;)
 
package mypackage;
 
import org.junit.Assert;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
 
public class MyPersistenceTest {
  @Test
  public void testBasicPersistence() throws Exception {
    EntityManagerFactory factory = Persistence.createEntityManagerFactory("myunitname");
    EntityManager manager = factory.createEntityManager();
 
    String attributeOne = "AttributeOne";
    String attributeTwo = "AttributeTwo";
 
    MyEntity entity = new MyEntity();
 
    entity.setAttributeOne( attributeOne );
    entity.setAttributeTwo( attributeTwo );
 
    manager.getTransaction().begin();
    manager.persist( entity );
    manager.getTransaction().commit();
 
    MyEntity result = ( entity ) manager
      .createQuery("SELECT e FROM MyEntity e WHERE e.attributeOne = :attributeOne")
      .setParameter("attributeOne", attributeOne )
      .getSingleResult();
 
    Assert.assertEquals(firstName, result.getAttributeOne());
    Assert.assertEquals(lastName, result.getAttributeTwo());
 
    manager.close();
    factory.close();
  }
}
Third thing. Make sure all the dependencies are in the pom like JPA, hibernate, or db pool (c3p0 kind of).
 
Thats it.
 
Regards, Chiradip