Junit test with entity mananger - java

I am beginner in Unit Testing. I have a Java Web Application build in Netbeans 8.1 and Maven. I have created this class to try to test querys in my PostgreSQl database:
public class DatesUtil {
private Collection<Menusistema> listamenus = new LinkedList<>();
private Menusistema menu= new Menusistema();
private String nombreBuscar = null;
private static final EntityManager entityManager;
static {
entityManager = Persistence.createEntityManagerFactory("com.controlpersonal.pu").
createEntityManager();
}
public static EntityManager getEntityManager() {
return entityManager;
};
public DatesUtil() {
}
#BeforeClass
public static void setUpClass() {
}
#AfterClass
public static void tearDownClass() {
}
#Before
public void setUp() {
}
#After
public void tearDown() {
}
// TODO add test methods here.
// The methods must be annotated with annotation #Test. For example:
//
#Test
public void hello() {
buscarTodo();
}
public void buscarTodo(){
findAll(Menusistema.class);
}
public <T> List<T> findAll(Class<T> clazz) {
return (List<T>) getEntityManager().createQuery("SELECT p FROM " + clazz.getSimpleName() + " p", clazz).getResultList();
}
}
I got the next error when I right click on netbeans and select: Test File:
[EL Info]: 2018-04-30
20:30:57.78--ServerSession(252553541)--EclipseLink, version: Eclipse
Persistence Services - 2.5.2.v20140319-9ad6abd [EL Severe]: ejb:
2018-04-30 20:30:57.836--ServerSession(252553541)--Exception
[EclipseLink-7060] (Eclipse Persistence Services -
2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.ValidationException Exception
Description: Cannot acquire data source [jdbc/controlpersonal].
Internal Exception: javax.naming.NoInitialContextException: Need to
specify class name in environment or system property, or as an applet
parameter, or in an application resource file:
java.naming.factory.initial
My persistence.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="com.controlpersonal.pu" transaction-type="JTA">
<jta-data-source>jdbc/controlpersonal</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
I really would like to test if this is posible. Thanks in advance!

I just created alternative persistente .xml:
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="com.controlpersonal.pu.test" transaction-type="RESOURCE_LOCAL">
<!--<jta-data-source>jdbc/controlpersonal</jta-data-source>-->
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.your.class1</class>
<class>com.your.class2</class>
<properties>
<property name="eclipselink.target-database" value="PostgreSQL" />
<property name="eclipselink.logging.level" value="INFO" />
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/controlpersonal" />
<property name="javax.persistence.jdbc.user" value="postgres" />
<property name="javax.persistence.jdbc.password" value="xxx" />
</properties>
</persistence-unit> </persistence>
Under: src/test/resources/META-INF/persistence.xml

Related

I can´t insert new data into my database with javaDB

i am developing a program to test how to use Derby from Java..
The problem is that i can´t add data from the IDE to my database, because after run my program. The data are not reflected on the DB.
Look my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="DBExamplePU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>exampleDB.sql.Provincia</class>
<class>exampleDB.sql.Persona</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:derby:example;create=true"/>
<property name="javax.persistence.jdbc.user" value="APP"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
<property name="javax.persistence.jdbc.password" value="1234"/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
And this is the code that i am trying to insert new data:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("DBExamplePU"); // Comprobar nombre de la PU
EntityManager em = emf.createEntityManager();
// OPERACIONES DE BD
Provincia provinciaCadiz = new Provincia(0, "Cádiz");
Provincia provinciaSevilla = new Provincia();
provinciaSevilla.setNombre("Sevilla");
em.getTransaction().begin();
em.persist(provinciaCadiz);
em.persist(provinciaSevilla);
em.getTransaction().commit();
em.close();
emf.close();
try {
DriverManager.getConnection("jdbc:derby:DBExamplePU;shutdown=true");
} catch (SQLException ex) {
}
In the platform netbeans IDE the data aren´t reflected on the database, but when i run this:
List<Provincia> listProvincias = queryProvincias.getResultList();
for(int i=0; i<listProvincias.size(); i++) {
Provincia provincia = listProvincias.get(i);
System.out.println(provincia.getNombre());
}
it shows me correctly the data!.
is like the database that i am using in my code is different from the database that i have created previously..
Hope you can help me, thank you!.

Java hibernate JPA error with JUnit Testing

I am using hibernate in my Java EE application in combination with my Wildfly server to persist my Classes in a mysql Database.
So far this works fine but now I am writing unit tests and I am getting crazy about some error which I get.
I would like to test my DAO-Layer in my Unit-Tests but I get these errors:
Caused by: org.hibernate.engine.jndi.JndiException: Error parsing JNDI name [java:/MySqlDS]
Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
my persistence.xml ist this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="primary">
<jta-data-source>java:/MySqlDS</jta-data-source>
<class>org.se.bac.data.Employee</class>
<properties>
<!-- Properties for Hibernate -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/empdb?useSSL=false"/>
<property name="hibernate.connection.username" value="student"/>
<property name="hibernate.connection.password" value="student"/>
<!--
SQL stdout logging
-->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="use_sql_comments" value="true"/>
</properties>
</persistence-unit>
</persistence>
So, Here I am using a jta-data-source> as you can see.
If I remove this line my tests are going fine! But I can not build my project with maven anymore.
Error:
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [com.mysql.jdbc.Driver]
Caused by: java.lang.ClassNotFoundException: Could not load requested class : com.mysql.jdbc.Driver"}}
He can not find the datasource because I removed the line in my persistence.xml
How can I manage to get both run in my application. The tests and of course the maven build?
Here is my test: (Setup is already causing the error):
package org.se.bac.data.dao;
import java.util.List;
import javax.persistence.EntityManager;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.se.bac.data.model.Employee;
public class EmployeeDAOTest
{
private static final JdbcTestHelper JDBC_HELPER = new JdbcTestHelper();
private final static JpaTestHelper JPA_HELPER = new JpaTestHelper();
private EntityManager em = JPA_HELPER.getEntityManager("primary");
private EmpDAO dao;
#BeforeClass
public static void init()
{
JDBC_HELPER.executeSqlScript("sql/test/dropEmployeeTable.sql");
JDBC_HELPER.executeSqlScript("sql/test/createEmployeeTable.sql");
}
#AfterClass
public static void destroy()
{
//JDBC_HELPER.executeSqlScript("sql/test/dropEmployeeTable.sql");
}
#Before
public void setUp()
{
JDBC_HELPER.executeSqlScript("sql/test/dropEmployeeTable.sql");
JDBC_HELPER.executeSqlScript("sql/test/createEmployeeTable.sql");
dao = new EmpDAOImpl();
dao.setEm(em);
JPA_HELPER.txBegin();
Employee emp2 = new Employee();
emp2.setFirstname("Max");
emp2.setLastname("Muster");
emp2.setHiredate("23-12-1991");
dao.insert(emp2);
}
And JPAHELPER Class:
package org.se.bac.data.dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
public class JpaTestHelper
{
/*
* Property: persistenceUnitName
*/
private String persistenceUnitName;
public String getPersistenceUnitName()
{
return persistenceUnitName;
}
public void setPersistenceUnitName(String persistenceUnitName)
{
if(persistenceUnitName == null || persistenceUnitName.length() == 0)
throw new IllegalArgumentException("Illegal parameter persistenceUnitName = " + persistenceUnitName);
this.persistenceUnitName = persistenceUnitName;
}
/*
* Get an instance of the EntityManagerFactory.
*/
protected EntityManagerFactory getEnityManagerFactory()
{
if(persistenceUnitName == null)
throw new IllegalStateException("PersistenceUnitName must be set!");
return Persistence.createEntityManagerFactory(persistenceUnitName);
}
/*
* Manage an EntityManager.
*/
private EntityManager em;
public EntityManager getEntityManager()
{
if(em == null)
{
em = getEnityManagerFactory().createEntityManager();
}
return em;
}
public EntityManager getEntityManager(String persistenceUnitName)
{
setPersistenceUnitName(persistenceUnitName);
return getEntityManager();
}
public void closeEntityManager()
{
if(em != null)
em.close();
}
/*
* Handle Transactions
*/
protected void txBegin()
{
EntityTransaction tx = em.getTransaction();
tx.begin();
}
protected void txCommit()
{
EntityTransaction tx = em.getTransaction();
if(tx.getRollbackOnly())
{
tx.rollback();
}
else
{
tx.commit();
}
}
protected void txRollback()
{
EntityTransaction tx = em.getTransaction();
tx.rollback();
}
}
and my DAO:
package org.se.bac.data.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.se.bac.data.model.Employee;
class EmpDAOImpl // package private
implements EmpDAO
{
#PersistenceContext
private EntityManager em;
/*
* CRUD methods
*/
public Employee findById(int id)
{
System.out.println("empdaoimpl ID " + id);
return em.find(Employee.class, id);
}
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
}
Wildfly Datasource:
<datasources>
<datasource jta="true" jndi-name="java:/MySqlDS" pool-name="MySqlDS" enabled="true" use-ccm="false">
<connection-url>jdbc:mysql://localhost:3306/empdb?useSSL=false</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<driver>mysql-connector-java-5.1.44-bin.jar_com.mysql.jdbc.Driver_5_1</driver>
<security>
<user-name>student</user-name>
<password>student</password>
</security>
<validation>
<valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker"/>
<background-validation>true</background-validation>
<exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLExceptionSorter"/>
</validation>
</datasource>
</datasources>
He can not find the datasource because I removed the line in my persistence.xml
How can I manage to get both run in my application.
The problem is that the data source is managed by Wildfly which is not available on your test environment. So what you could do is define two separate persistence units (one for your production code and the other for the test) as follows:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="primary">
<jta-data-source>java:/MySqlDS</jta-data-source>
<properties>
<!-- Properties for Hibernate -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<!-- SQL stdout logging -->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="use_sql_comments" value="true"/>
</properties>
</persistence-unit>
<persistence-unit name="testPU" transaction-type="RESOURCE_LOCAL">
<class>org.se.bac.data.Employee</class>
<properties>
<!-- Properties for Hibernate -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/empdb?useSSL=false"/>
<property name="hibernate.connection.username" value="student"/>
<property name="hibernate.connection.password" value="student"/>
<!-- SQL stdout logging -->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="use_sql_comments" value="true"/>
</properties>
</persistence-unit>
</persistence>
and then in your EmployeeDAOTest class modify the following line as:
private EntityManager em = JPA_HELPER.getEntityManager("testPU");
Note:
I removed the JDBC connection properties from the primary persistence unit because you don't need them as you already have the data source there on Wildfly.

JPA exception: Object: is not a known entity type

I'm new to JPA and I'm having problems. I read that the problem maybe with the persistence.xml .
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="GreekTravelPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>entities.Room</class>
<class>entities.Country</class>
<class>entities.User</class>
<class>entities.RoomType</class>
<class>entities.Role</class>
<class>entities.Photo</class>
<class>entities.Availability</class>
<class>entities.Message</class>
<class>entities.Location</class>
<class>entities.Booking</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/greektraveldb?zeroDateTimeBehavior=convertToNull"/>
<property name="javax.persistence.jdbc.user" value="psilos"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="psilos"/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
My Exeption:
java.lang.IllegalArgumentException: Object: org.eclipse.persistence.internal.jpa.EntityManagerImpl#665ba601 is not a known entity type.
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.mergeCloneWithReferences(UnitOfWorkImpl.java:3510)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.mergeCloneWithReferences(RepeatableWriteUnitOfWork.java:384)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.mergeCloneWithReferences(UnitOfWorkImpl.java:3481)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.mergeInternal(EntityManagerImpl.java:542)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.merge(EntityManagerImpl.java:519)
The actual code is
#Override public void update(User user) {
EntityManager em = EntityManagerHelper.getEntityManager();
try {
EntityTransaction entityTrasacrion = em.getTransaction();
entityTrasacrion.begin();
em.merge(em);
entityTrasacrion.commit();
} catch (RuntimeException e) {
throw e;
} finally {
EntityManagerHelper.closeEntityManager();
}
}
You're merging the entity manager with the entity manager!!! Ooops!
em.merge(em);
Needs to be
em.merge(user);

#NamedStoredProcedureQuery NamedQuery of name: procuder not found

Greeting for the day..
Please provide me support.
I am new in Jpa and calling procuder with #NamedStoredProcedureQuery but my code is giving Exception as #NamedStoredProcedureQuery NamedQuery of name: procuder not found
my code is :=
#NamedStoredProcedureQuery(name = "TEST1",procedureName = "TEST1",parameters = { #StoredProcedureParameter(name = "P_CODE", mode = ParameterMode.IN, type = String.class), #StoredProcedureParameter(name = "P_DATE", mode = ParameterMode.IN, type = String.class), #StoredProcedureParameter(name = "P_CURSOR", mode = ParameterMode.REF_CURSOR, type = void.class), })
public class AnotherWayOfCallingProcedure implements Serializable
{
private static final String PERSISTENCE_UNIT_NAME = "todos";
private static EntityManagerFactory factory;
public static void main(String arg[]) {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
StoredProcedureQuery addBookNamedStoredProcedure = em.createNamedStoredProcedureQuery("TEST1");
addBookNamedStoredProcedure.setParameter("P_CODE", "5000");
addBookNamedStoredProcedure.setParameter("P_DATE", "5/3/2017");
// Stored procedure call
List createdBookId = addBookNamedStoredProcedure.getResultList();
em.close();
}
}
and persistence.xml is
<?xml version="1.0" encoding="UTF-8" ?>
<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_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="todos" transaction-type="RESOURCE_LOCAL">
<class>com.app.IptAnchorageAreaMaster</class>
<class>com.app.AnotherWayOfCallingProcedure</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:#192.168.6.147:1521:orcl" />
<property name="javax.persistence.jdbc.user" value="aaa_kkk" />
<property name="javax.persistence.jdbc.password" value="aaa" />
<!-- EclipseLink should create the database schema automatically -->
<property name="eclipselink.ddl-generation" value="none" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
</properties>
</persistence-unit>
</persistence>

JPA - Entities not persisted

Here is my persistence.xml :
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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" version="1.0">
<persistence-unit name="miniDS" transaction-type="JTA">
<jta-data-source>java:/miniDS</jta-data-source>
<class>com.company.model.Ordre</class>
<properties>
<!-- Options Hibernate -->
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.default_schema" value="mini" />
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup" />
</properties>
</persistence-unit>
My code :
// Create order
Ordre o = new Ordre();
o.setDate(req.getParameter("date"));
o.setMotif(req.getParameter("motif"));
log.info("Ordre: " + o.getDate() + " " + o.getMotif());
OrdreService os = new OrdreService();
os.persist(o);//This method is NOT even called !
// Process application flow here...
OrdreService.java :
public class OrdreService {
private OrdreDAO dao;
public OrdreService() {
dao = new OrdreDAO();
}
public void persist(Ordre o) {
System.out.println("Service persist");
dao.persist(o);
}
//...
}
OrdreDAO.java :
public class OrdreDAO {
private EntityManagerFactory emf;
private EntityManager em;
public OrdreDAO() {
emf = Persistence.createEntityManagerFactory("miniDS");
em = emf.createEntityManager();
}
public void persist(Ordre o) {
System.out.println("DAO persist");
EntityTransaction et = null;
try {
et = em.getTransaction();
et.begin();
em.persist(o);
System.out.println("commit ?");
if (et != null) {
if (et.isActive()) {
et.commit();
}
}
} catch (Throwable t) {
t.printStackTrace();
if (et != null) {
if (et.isActive()) {
et.rollback();
}
}
}
}
//...
}
OrdreService.persist is never called :\ OrdreDAO.persist too.
What's going on with JBoss ?
JBoss 5.1.0.GA
Postgresql 8.3
JPA 1
When you use '<jta-data-source>' set your transaction type to JTA in persistence.xml file:
<persistence-unit name="your_pu_name" transaction-type="JTA">

Categories

Resources