I don't have Entity classes in my project. My requirement is When I am connecting to DataBase Based on schema I have to Get the all Tables names from that schema.
Here I have a Schema as "companydb" with 5 tables. Below is my code to retrieve total number of tables from particular schema.
Here may be Exception occur by "Query". Query is not well here so what type of query I have to use and how Can I get List of tables.
persiatance.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="reports" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/reports" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
</properties>
</persistence-unit>
</persistence>
GetTableList.java
#WebServlet("/GetTableList")
public class GetTableList extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
EntityManager entityManager = EntityManagerUtil.getEmf()
.createEntityManager();
try {
Query query = entityManager.createQuery("SELECT * FROM companydb.tables");
List list = query.getResultList();
System.out.println(list);
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
iterator.next();
}
out.print(list);
System.out.println("Data retrived successfully");
} catch (Exception e) {
e.printStackTrace();
} finally {
entityManager.close();
}
}
}
Exception is:
java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Syntax error parsing the query [SELECT * FROM companydb], line 1, column 7: unexpected token [*].
Internal Exception: NoViableAltException(93#[330:16: ( DISTINCT )?])
how can I over come.
Use Native query to get List of tables from your schema
Query query = entityManager.createNativeQuery("SHOW TABLES FROM companydb");
Related
i have a frustrating problem with my servlet. This is very basic, i'm supposed to add a blog entry to my database table which has 3 columns (id, tittel(title), main(mainbody)). I can load from my database and display in my jsp file. However i can't persist the data to the database and i cant figure out why.
I use postgres as a database.
This is my "saveBlog"-method:
public void lagreBlogg(Blogg b){
EntityManager em = Persistence.createEntityManagerFactory("kimsBlogg").createEntityManager();
EntityTransaction transaction = em.getTransaction();
try {
transaction.begin();
em.persist(b);
transaction.commit();
} catch (Exception e) {
transaction.rollback();
} finally {
em.close();
}
}
}
This is my entity class:
#Entity
#Table(schema = "blogg", name = "blogg")
public class Blogg {
#Id
#GeneratedValue
private int id;
private String tittel;
private String main;
public Blogg() {
}
public Blogg(String tittel, String main){
this.tittel= tittel;
this.main = main;
}
public String getTittel() {
return tittel;
}
public void setTittel(String tittel) {
this.tittel = tittel;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
}
My persistence.xml
<?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="kimsBlogg">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl
</provider>
<class>no.kim.model.Blogg</class>
<properties>
<property name="javax.persistence.jdbc.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/postgres" />
<property name="javax.persistence.jdbc.user" value="postgres" />
<property name="javax.persistence.jdbc.password" value="krheggen" />
<property name="openjpa.RuntimeUnenhancedClasses" value="supported" />
</properties>
</persistence-unit>
This is the error i get:
HTTP Status 500 - Can only perform operation while a transaction is active.
type Exception report
message Can only perform operation while a transaction is active.
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.openjpa.persistence.InvalidStateException: Can only perform operation while a transaction is active.
org.apache.openjpa.kernel.BrokerImpl.assertTransactionOperation(BrokerImpl.java:4732)
org.apache.openjpa.kernel.BrokerImpl.rollback(BrokerImpl.java:1543)
org.apache.openjpa.kernel.DelegatingBroker.rollback(DelegatingBroker.java:940)
org.apache.openjpa.persistence.EntityManagerImpl.rollback(EntityManagerImpl.java:598)
no.kim.helpers.BloggDAO.lagreBlogg(BloggDAO.java:37)
no.kim.Controller.BloggServlet.doPost(BloggServlet.java:33)
javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
StackTrace
Caused by: org.apache.openjpa.persistence.PersistenceException: ERROR: relation "blogg.openjpa_sequence_table" does not exist
Position: 28 {prepstmnt 166406485 SELECT SEQUENCE_VALUE FROM blogg.OPENJPA_SEQUENCE_TABLE WHERE ID = ? FOR UPDATE} [code=0, state=42P01]
at org.apache.openjpa.jdbc.sql.DBDictionary.narrow(DBDictionary.java:5001)
at org.apache.openjpa.jdbc.sql.DBDictionary.newStoreException(DBDictionary.java:4961)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:133)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:107)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:59)
at org.apache.openjpa.jdbc.kernel.AbstractJDBCSeq.next(AbstractJDBCSeq.java:63)
at org.apache.openjpa.util.ImplHelper.generateValue(ImplHelper.java:159)
at org.apache.openjpa.util.ImplHelper.generateFieldValue(ImplHelper.java:143)
at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.assignField(JDBCStoreManager.java:774)
at org.apache.openjpa.util.ApplicationIds.assign(ApplicationIds.java:492)
at org.apache.openjpa.util.ApplicationIds.assign(ApplicationIds.java:468)
at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.assignObjectId(JDBCStoreManager.java:758)
at org.apache.openjpa.kernel.DelegatingStoreManager.assignObjectId(DelegatingStoreManager.java:135)
at org.apache.openjpa.kernel.StateManagerImpl.assignObjectId(StateManagerImpl.java:595)
at org.apache.openjpa.kernel.StateManagerImpl.preFlush(StateManagerImpl.java:3051)
at org.apache.openjpa.kernel.PNewState.beforeFlush(PNewState.java:44)
at org.apache.openjpa.kernel.StateManagerImpl.beforeFlush(StateManagerImpl.java:1072)
at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:2143)
at org.apache.openjpa.kernel.BrokerImpl.flushSafe(BrokerImpl.java:2103)
at org.apache.openjpa.kernel.BrokerImpl.beforeCompletion(BrokerImpl.java:2021)
at org.apache.openjpa.kernel.LocalManagedRuntime.commit(LocalManagedRuntime.java:81)
at org.apache.openjpa.kernel.BrokerImpl.commit(BrokerImpl.java:1526)
at org.apache.openjpa.kernel.DelegatingBroker.commit(DelegatingBroker.java:932)
at org.apache.openjpa.persistence.EntityManagerImpl.commit(EntityManagerImpl.java:569)
relation "blogg.openjpa_sequence_table" does not exist
This seems to be straightforward, just create a sequence for the table blogg, more information here.
The problem is your " transaction.rollback();" in the catch method. if commit fails with an exception the connection is not longer active.
getting this error in eclipselink JPA example. I am trying to set up a simple JPA class. It complains about the xml document not being well formed, but I don't see any problems. please let me know of any pointers. thanks!
Main class is:
package de.vogella.jpa.simple.main;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import de.vogella.jpa.simple.model.Todo;
public class Main {
private static final String PERSISTENCE_UNIT_NAME = "todos";
private static EntityManagerFactory factory;
public static void main(String[] args) {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
// read the existing entries and write to console
Query q = em.createQuery("select t from Todo t");
List<Todo> todoList = q.getResultList();
for (Todo todo : todoList) {
System.out.println(todo);
}
System.out.println("Size: " + todoList.size());
// create new todo
em.getTransaction().begin();
Todo todo = new Todo();
todo.setSummary("This is a test");
todo.setDescription("This is a test");
em.persist(todo);
em.getTransaction().commit();
em.close();
}
}
here is persistence.xml
<?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>de.vogella.jpa.simple.model.Todo</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:derby:/home/vogella/databases/simpleDb;create=true" />
<property name="javax.persistence.jdbc.user" value="test" />
<property name="javax.persistence.jdbc.password" value="test" />
<!-- EclipseLink should create the database schema automatically -->
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode"
value="database" />
</properties>
</persistence-unit>
</persistence>
The error is the following:
Exception in thread "main" Local Exception Stack:
Exception [EclipseLink-30009] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while trying to load persistence unit at url: file:/C:/paul/oneView/java/de.vogella.jpa.simple/build/eclipse/
Internal Exception: Exception [EclipseLink-30004] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while processing persistence.xml from URL: file:/C:/paul/oneView/java/de.vogella.jpa.simple/build/eclipse/
Internal Exception:
(1. The markup in the document preceding the root element must be well-formed.)
at org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionLoadingFromUrl(PersistenceUnitLoadingException.java:100)
at org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processPersistenceArchive(PersistenceUnitProcessor.java:597)
at org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.getPersistenceUnits(PersistenceUnitProcessor.java:481)
at org.eclipse.persistence.internal.jpa.deployment.JPAInitializer.findPersistenceUnitInfoInArchive(JPAInitializer.java:172)
at org.eclipse.persistence.internal.jpa.deployment.JPAInitializer.findPersistenceUnitInfoInArchives(JPAInitializer.java:154)
at org.eclipse.persistence.internal.jpa.deployment.JPAInitializer.findPersistenceUnitInfo(JPAInitializer.java:135)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:177)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at de.vogella.jpa.simple.main.Main.main(Main.java:17)
I fighing with hibernate. I'm trying to follow hibernate.org/ogm/documentation/getting-started/ . Here are my files
- persistence.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="ogm-jpa-tutorial" transaction-type="JTA">
<!-- Use Hibernate OGM provider: configuration will be transparent -->
<provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
<class>com.mycompany.hibernate.MyEntity</class>
<properties>
<property name="hibernate.ogm.datastore.provider" value="MONGODB"/>
<!-- property optional if you plan and use Infinispan, otherwise adjust to your favorite
NoSQL Datastore provider.
<property name="hibernate.ogm.datastore.provider"
value="org.hibernate.ogm.datastore.infinispan.impl.InfinispanDatastoreProvider"/>
-->
<!-- defines which JTA Transaction we plan to use -->
<property name="hibernate.ogm.datastore.provider" value="org.hibernate.ogm.datastore.mongodb.impl.MongoDBDatastoreProvider"/>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform"/>
</properties>
</persistence-unit>
</persistence>
entity class:
#Entity
#Table(name = "USstates")
public class MyEntity implements Serializable{
#Id
String _id;
String city;
Integer pop;
String state;
public String getId(){return _id;}
public String getCity(){return city;}
public Integer getPop(){return pop;}
public String getState(){return state;}
}
application
private static final String JBOSS_TM_CLASS_NAME = "com.mycompany.hibernate.TransactionManager";
public static void main( String[] args ) throws Exception
{
EntityManagerFactory emf = Persistence.createEntityManagerFactory(
"ogm-jpa-tutorial");
TransactionManager tm = getTransactionManager();
//Persist entities the way you are used to in plain JPA
tm.begin();
EntityManager em = emf.createEntityManager();
MyEntity e = new MyEntity();
e = new MyEntity();
//Retrieve your entities the way you are used to in plain JPA
tm.begin();
em = emf.createEntityManager();
e = em.find(MyEntity.class, "0");
em.flush();
em.close();
tm.commit();
emf.close();
}
public static TransactionManager getTransactionManager() {
try {
Class<?> tmClass = App.class.getClassLoader().loadClass( JBOSS_TM_CLASS_NAME );
return (TransactionManager) tmClass.getMethod( "transactionManager" ).invoke( null );
} catch ( ClassNotFoundException e ) {
e.printStackTrace();
} catch ( InvocationTargetException e ) {
e.printStackTrace();
} catch ( NoSuchMethodException e ) {
e.printStackTrace();
} catch ( IllegalAccessException e ) {
e.printStackTrace();
}
return null;
}
I have database test with collection USstates taken from http://media.mongodb.org/zips.json
Using thic codes I got some wornings about logs and what more important exception while running this application:
Exception in thread "main" javax.persistence.PersistenceException: [PersistenceUnit: ogm-jpa-tutorial] Unable to build Hibernate SessionFactory
any ideas?
UPDATE:
after fighting i got an error of non exising class, I already tried milions of combinations of dependency and still got nothing... error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/hibernate/util/xml/Origin
UPDATE 2.0:
Now I have other problem:
Exception in thread "main" java.lang.NoSuchMethodError: org.hibernate.cfg.Configuration.getIdentifierGeneratorFactory()Lorg/hibernate/id/factory/spi/MutableIdentifierGeneratorFactory;
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:1119)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:291)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:373)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:55)
at org.hibernate.ogm.jpa.HibernateOgmPersistence.createEntityManagerFactory(HibernateOgmPersistence.java:92)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
at com.mycompany.hibernate.App.main(App.java:48)
Ok silly question - did you remove the specific connection properties from your persistence.xml here, or did you not have them - example below?
<property name="hibernate.ogm.datastore.provider" value="mongodb"/>
<property name="hibernate.ogm.datastore.database" value="rntsmpl"/>
<property name="hibernate.ogm.datastore.host" value="127.0.0.1"/>
<property name="hibernate.ogm.datastore.port" value="59541"/>
<property name="hibernate.ogm.datastore.username" value="admin"/>
<property name="hibernate.ogm.datastore.password" value="nnTdE2jPf4FV"/>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform" />
I'm having program that creates JPA entries with the entity manager.
during the process I don't get any errors.
...
factory = Persistence.createEntityManagerFactory("perst");
EntityManager entityManager = factory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(object);
entityManager.getTransaction().commit();
...
entityManager.close();
I have created a program like follows to read the data but it doesn't return any data,
the query returns empty. What could be the reason ?
This is the program to read the data:
static List<String> classList = new ArrayList<String>();
private static EntityManagerFactory factory;
public static void main(String[] args) {
// TODO Auto-generated method stub
factory = Persistence.createEntityManagerFactory("perst");
EntityManager entityManager = factory.createEntityManager();
classList.add("LeaveRequest");
classList.add("person");
for (Object classOjc : classList) {
String className = classOjc.toString();
Query query = entityManager.createQuery("SELECT p FROM " + className + " p");
#SuppressWarnings("rawtypes")
List resultList = query.getResultList();
System.out.println(resultList.size());
for (Object result : resultList) {
System.out.println(result.toString());
}
}
}
the xml persist is:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">
<persistence-unit name="perst" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>LeaveRequest</class>
<class>person</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:derby:/home/vogella/databases/simpleDb;create=true" />
<property name="javax.persistence.jdbc.user" value="Sales" />
<property name="javax.persistence.jdbc.password" value="" />
<!-- EclipseLink should create the database schema automatically -->
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
<property name="eclipselink.ddl-generation.output-mode"
value="database" />
<property name="eclipselink.logging.level" value="SEVERE" />
<property name="eclipselink.logging.exceptions" value="true" />
</properties>
</persistence-unit>
</persistence>
You configured eclipselink to drop and recreate the schema each time the app is started:
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
So obviously, if you run a first application that persists some entries, and then a second application which tries to read what the first one has written, you won't find anything anymore, since eclipselink drops everything and recreates the schema every time.
We are facing an issue while calling the stored procedure from the application.
The database is oracle 10g
This proc has 2 input parameters and 2 output parameters.
Input 1:- DB-List
Input 2:- String
Output 1:-Again a DB-List
Output 2:- Number
When we are trying to use
Query q = session.createSQLQuery("{call proc_name(?,?,?,?)}");
We cannot distinguish between in parameters and out parameters.
So how should we handle it by using this.
Also,
We tried to use callable statement as follows:
Session session = (Session) getEntityManager().getDelegate();
SessionImpl sessionImpl = ((SessionImpl) getEntityManager().getDelegate());
Connection cc = sessionImpl.connection();
CallableStatement callableStatement = null;
callableStatement = cc.prepareCall("{call proc_name(?,?,?,?)}");
ArrayDescriptor descriptor = ArrayDescriptor.createDescriptor("DB_LIST",callableStatement.getConnection());
ARRAY paramArray = new ARRAY(descriptor, callableStatement.getConnection(), array);
callableStatement.setArray(1, paramArray);
callableStatement.setString(2, "N");
callableStatement.registerOutParameter(3, OracleTypes.ARRAY, "DB_RETURN_LIST");
callableStatement.registerOutParameter(4, Types.INTEGER);
// executing the query
callableStatement.execute();
We get the following error:
javax.ejb.EJBException: java.lang.ClassCastException:
$Proxy50 cannot be cast to oracle.jdbc.OracleConnection
Can you please provide some suggestions.
This is the Entity Manager that we are using
public abstract class GenericDAO<T, ID extends Serializable> implements IGenericDAO<T, ID> {
private final Class<T> persistentClass;
#PersistenceContext(unitName = "firstPersistenceUnit")
#Produces
private EntityManager entityManager;
public void setEntityManager(final EntityManager entityManager) throws DataAccessException {
this.entityManager = entityManager;
}
public EntityManager getEntityManager() throws DataAccessException {
return entityManager;
}
}
Here is the entry in the 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="firstPersistenceUnit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/firstDataSource</jta-data-source>
<class>com.domain.Branch</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
<validation-mode>AUTO</validation-mode>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
<persistence-unit name="secondPersistenceUnit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/secondDataSource</jta-data-source>
<class>com.domain.PocJeeCounty</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
<validation-mode>AUTO</validation-mode>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
Dont use second way, instead create and define query and query parameters using #NamedStoredProcedureQuery and #StoredProcedureParameter. Following is the code for your requirement
#NamedStoredProcedureQuery(
name="PROC_NAME",
procedureName="proc_name",
returnsResultSet=true/false,
parameters={
#StoredProcedureParameter(queryParameter="param1",name="p1",direction=Direction.IN,type=Integer.class),
#StoredProcedureParameter(queryParameter="param2",name="p2",direction=Direction.IN,type=Timestamp.class),
#StoredProcedureParameter(queryParameter="param3",name="p3",direction=Direction.OUT,type=String.class),
#StoredProcedureParameter(queryParameter="param4",name="p4",direction=Direction.OUT,type=Integer.class)
}
)
and use em.createNativeQuery() method