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
+- 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;
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();
@Test
public void testBasicPersistence() throws Exception {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("myunitname");
EntityManager manager = factory.createEntityManager();
String attributeOne = "AttributeOne";
String attributeTwo = "AttributeTwo";
String attributeTwo = "AttributeTwo";
MyEntity entity = new MyEntity();
entity.setAttributeOne( attributeOne );
entity.setAttributeTwo( attributeTwo );
entity.setAttributeTwo( attributeTwo );
manager.getTransaction().begin();
manager.persist( entity );
manager.getTransaction().commit();
manager.persist( entity );
manager.getTransaction().commit();
MyEntity result = ( entity ) manager
.createQuery("SELECT e FROM MyEntity e WHERE e.attributeOne = :attributeOne")
.setParameter("attributeOne", attributeOne )
.getSingleResult();
.createQuery("SELECT e FROM MyEntity e WHERE e.attributeOne = :attributeOne")
.setParameter("attributeOne", attributeOne )
.getSingleResult();
Assert.assertEquals(firstName, result.getAttributeOne());
Assert.assertEquals(lastName, result.getAttributeTwo());
Assert.assertEquals(lastName, result.getAttributeTwo());
manager.close();
factory.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