Hibernate OGM with MongoDB persistence exception - java

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" />

Related

Hibernate - persist automatically each relation

Maybe it is a simple question, but I can't find out this situation of relations in Hibernate.
I have these Entities:
#Entity
public class User {
...
#OneToMany(mappedBy = "user")
private Set<Conversation> posts = new HashSet<Conversation>();
...
}
#Entity
public class Conversation {
...
#OneToMany(mappedBy = "conversation")
private Set<Message> messages = new HashSet<Message>();
...
}
#Entity
public class Message { ... }
and then I want create User with Conversation and Message at once. Idea should be like this:
User user = new User();
user.getPosts().add(new Conversation(){
{
getMessages().add(new Message());
}
});
session.persist(user);
But just User is saved in database - why isn't it all? Because of default LAZY fetching? Could my idea be implemented somehow?
PS: Of course I know about the solution of persisting each of the entities, but I am used to do like this in other frameworks like nette or Django, so I can't get out of my head.
PPS: I found out that problem is in default CascadeType. Could it be set on globally, e.g. in Hibernate config XML? Is it a good idea (by performance point of view - it is persisted each time on "superpersist" or only in case of changes)?
PPPS: I also found out (opposite to Django) that I have to set FK ex-post for each item added to collection. It is natural (because of selected pure Set type), but new for me. Which approach would you recommend me? Required FK as argument in constructor on item Entity e.g.:
Class Message{
Message(Conversation conversation){
setConversation(conversation);
}
...
}
or make a method for adding where FK sets inside e.g.:
Class Conversation{
...
public void addMessage(Message msg){
msg.setConversation(this);
getMessages().add(msg);
}
...
}
?
Making Session + configure XML.
private final static String CFG = "hibernate-cfg.xml";
private final static String SCRIPT_FILE = "query.sql";
private static SessionFactory sessionFactory;
private static ServiceRegistry buildRegistry() {
return new StandardServiceRegistryBuilder()
.configure(CFG)
.build();
}
private static Metadata getMetaData() {
return new MetadataSources(buildRegistry()).getMetadataBuilder().build();
}
private static SessionFactory buildSessionFactory() {
return getMetaData().getSessionFactoryBuilder().build();
}
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory();
}
return sessionFactory;
}
public static Session getSession(){
try {
return getSessionFactory().openSession();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
and the hibernate-cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/learnme
</property>
<property name="connection.username">root</property>
<property name="connection.password"/>
<property name="connection.pool_size">100</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQL5Dialect
</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>
<!-- Display all generated SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="learnme.hibernate.entities.User"/>
<mapping class="learnme.hibernate.entities.Conversation"/>
<mapping class="learnme.hibernate.entities.Message"/>
</session-factory>
</hibernate-configuration>
According to this and this
you need to have this in your persistence.xml file to set it globally:
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" version="1.0">
<persistence-unit-metadata>
<persistence-unit-defaults>
<cascade-persist/>
</persistence-unit-defaults>
</persistence-unit-metadata>
</entity-mappings>
The mapping file has to be located either in the default location,
META-INF/orm.xml, or in another location that is specified explicitly
in the persistence unit definition (in persistence.xml).

Transaction is not active using OpenJPA

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.

hibernate delete second level jpa2.0

I need in my application to remove all data from a cachable table.
I suposed that to delete all contents, I had to remove the second level cache, then use a truncate.
#Entity
#Table(name = "\"cpf_formacode\"")
#Cacheable
public class CpfRefFormaCode implements Serializable {
.......
}
the Dao method:
public void deleteAll() {
SessionFactory sf = em.unwrap(SessionFactory.class);
sf.getCache().evictEntityRegion(CpfRefFormaCode.class);
em.createNativeQuery("TRUNCATE TABLE cpf_formacode").executeUpdate();
}
persistence file:
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="org.hibernate.FlushMode" value="commit" />
<!-- property name="hibernate.hbm2ddl.auto" value="create-drop" / -->
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.cache.use_second_level_cache" value="true" />
<property name="hibernate.cache.use_query_cache" value="true" />
<property name="hibernate.cache.infinispan.cachemanager" value="java:jboss/infinispan/hibernate" />
<property name="hibernate.cache.region.factory_class" value="org.jboss.as.jpa.hibernate4.infinispan.InfinispanRegionFactory" />
<property name="hibernate.cache.infinispan.statistics" value="true" />
</properties>
the error i have :
17:50:17,161 ERROR [org.jboss.as.ejb3.tx.CMTTxInterceptor] (http--127.0.0.1-8080-2) javax.ejb.EJBTransactionRolledbackException: Hibernate cannot unwrap interface org.hibernate.SessionFactory
17:50:17,163 ERROR [org.jboss.ejb3.invocation] (http--127.0.0.1-8080-2) JBAS014134: EJB Invocation failed on component CpfRefFormaCodeDao for method public void com.agefos.corp.business.dao.CpfRefFormaCodeDao.deleteAll(): javax.ejb.EJBTransactionRolledbackException: Hibernate cannot unwrap interface org.hibernate.SessionFactory
Caused by: javax.persistence.PersistenceException: Hibernate cannot unwrap interface org.hibernate.SessionFactory
I finished by findig the solution,
The problem that i was trying to clean the cach before deleting the data, and it was not the best practice
public void deleteAll() {
try {
TypedQuery<MyEntity> query = em.createQuery("From MyEntity f", MyEntity.class);
query.setHint("org.hibernate.cacheable", true);
List<MyEntity> result = null;
result = query.getResultList();
if (!result.isEmpty()) {
for (MyEntity f : result) {
em.remove(f);
}
}
em.flush();
} catch (Exception e) {
throw new PersistanceException("An error occurred while attempting to delete an instance of an object : " + entityClass, e);
}
}
the problem was resolved by adding the
em.flush();
In other words, flush tells Hibernate to execute the SQL statements needed to synchronize the JDBC connection's state with the state of objects held in the session-level cache. so i was abel to save other entities without ID problems

eclipselink Persistence error and not well formed xml document

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)

How to interact with Tables using EclipseLink without using Entity classes?

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");

Categories