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>
Related
Basically I am doing a Insert inside a PostgreSQL database, but since I have multiple databases I have to change the configurations based on each environment.
The thing is that I used a not really good way to do so, since everytime I do a insert, I replace all variables, which is ultra slow and definetly not a good way to achiev that.
How would I be able to do the same inserts, but having it configured while my Api started?
Here's what i'm currently doing:
package br.jus.tjba.dje.local.service;
import br.jus.tjba.dje.local.entity.Conteudo;
import br.jus.tjba.dje.local.repository.ConteudoRepository;
import br.jus.tjba.tjfw4.core.service.AbstractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.persistence.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
#Service
public class ConteudoService extends AbstractService {
#Autowired
private ConteudoRepository conteudoRepository;
public EntityTransaction insertInDb(String something, String somethingElse) {
Map<String, String> env = System.getenv();
Map<String, Object> configOverrides = new HashMap<>();
// Here I change my persistance.xml configs
for(Map.Entry<String, String> entry: env.entrySet()) {
if (entry.getKey().contains("DATABASE_URL")) {
configOverrides.put("javax.persistence.jdbc.url", env.get(entry.getValue()));
} else if (entry.getKey().contains("DATABASE_USER")) {
configOverrides.put("javax.persistence.jdbc.user", env.get(entry.getValue()));
} else if (entry.getKey().contains("DATABASE_PASSWORD")) {
configOverrides.put("javax.persistence.jdbc.password", env.get(entry.getValue()));
}
}
// Cria um factory dando override nas variáveis.
EntityManagerFactory factory = Persistence.createEntityManagerFactory("default", configOverrides);
EntityManager conteudoManager = factory.createEntityManager();
Query query = conteudoManager.createNativeQuery("INSERT INTO something(" +
"SOMETHING," +
"SOMETHING_ELSE)" +
" VALUES (" +
":something," +
":somethingElse)");
conteudoManager.getTransaction().begin();
query.setParameter("something", something);
query.setParameter("somethingElse", somethingElse);
query.executeUpdate();
return conteudoManager.getTransaction();
}
public Conteudo getContent() {
return conteudoRepository.getContent();
}
}
Also my persistance.xml:
<?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="default" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="javax.persistence.jdbc.url" value="url" />
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.password" value="password" />
<property name="javax.persistence.jdbc.user" value="login" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
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
I'm new with serverless framework. I'm trying to make a test of a simple application with maven, spring, hibernate, jpa, mysql and serverless.
this is my project
As a restApi works ok, but when I invoke the function in serverless terminal the information came null, because is not getting the info from the db.
this is my code
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_2_0.xsd"
version="2.0">
<persistence-unit name="serverless-java" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.serverless.persistence.Wizard</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://mydb.uiyfuas7434.us-east-1.rds.amazonaws.com:3306/mydb" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="1234" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<!-- Important -->
<property name="hibernate.connection.provider_class" value="org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider" />
<property name="hibernate.c3p0.max_size" value="10" />
<property name="hibernate.c3p0.min_size" value="0" />
<property name="hibernate.c3p0.acquire_increment" value="1" />
<property name="hibernate.c3p0.idle_test_period" value="120" />
<property name="hibernate.c3p0.max_statements" value="0" />
<property name="hibernate.c3p0.timeout" value="240" />
<!-- Features -->
<property name="hibernate.connection.autoReconnect" value = "true"/>
<property name="hibernate.show_sql" value = "false" />
<property name="hibernate.connection.autoReconnectForPools" value = "true"/>
<property name="hibernate.connection.is-connection-validation-required" value = "true"/>
</properties>
</persistence-unit>
</persistence>
my Handler class
public class Handler implements RequestHandler<Map<String, Object>, ApiGatewayResponse> {
private static final Logger logger = LoggerFactory.getLogger(TestService.class);
#Autowired
private IBaseService service;
#Override
public ApiGatewayResponse handleRequest(Map<String, Object> input, Context context) {
List<Wizard> prueba = service.getWizards();
Map<String, Wizard> response = new HashMap<>();
Response responseBody = new Response("success", response);
try {
for (Wizard entity : prueba) {
response.put(entity.getName(), entity);
}
responseBody.setInput(response);
} catch (Exception e) {
logger.error(e.getMessage(), e);
responseBody.setMessage("Fail: " + e.getMessage());
}
return ApiGatewayResponse.builder().setStatusCode(200).setObjectBody(responseBody)
.setHeaders(Collections.singletonMap("This is a test", "AWS Lambda & serverless")).build();
}
}
my serverless.yml
service: aws-java-maven # NOTE: update this with your service name
provider:
name: aws
runtime: java8
iamRoleStatements:
- Effect: "Allow"
Action:
- "mysql:*"
Resource: "*"
package:
artifact: target/hello-dev.jar
functions:
get-transactions:
handler: com.serverless.Handler
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);
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">