org.hibernate.hql.ast.QuerySyntaxException table is not mapped - java

I'm getting an error which looks like:
java.lang.IllegalArgumentException: org.hibernate.hql.ast.QuerySyntaxException: DirectAddress is not mapped [select d from DirectAddress d where emailaddress=?]
where query looks like
Query query = session.createQuery("select d from DirectAddress d where emailaddress=?");
and I have set an entity for javax
#Entity
#Table(name = "user")
Then I have tired that query:
Query query = session.createQuery("select d from " + DirectAddress.class.getName() + " d where emailaddress=?");
without any luck.
Also project is not using hibernate.cfg.xml file.
Any thoughts?

To use an entity you've created, make sure it's marked as #Entity using the javax library. You'll also need to map it so hibernate knows it's supposed to link it to your database table. Please verify if your entity is mapped in your applicationContext.xml (for spring applications) or persistence.xml in common hibernate applications.
Mapping your entities
You can map your entities in many ways. The most common methods are:
Mapping it directly in hibernate.cfg.xml:
<mapping class="your.packages.to.the.entity.class" />
Setting it up in your spring applicationContext.xml`s hibernate configurations
For a working example, please refer to:
How configure hibernate.cfg.xml to applicationContext.xml as dataSource?
By Spring Injection
You mentioned not using hibernate.cfg.xml. Are you injecting hibernate`s settings via spring (in a non-web application)? If so, please refer to Can we configure Hibernate Without hibernate.cfg.xml
If none of the solutions apply, please provide more details about your System (web, desktop, setting up hibernate programatically, etc) and i`ll edit with this answer with the most appropriate solution.
Cheers!

DirectAddress is not mapped [select d from DirectAddress d where emailaddress=?]
means hibernate did not find mapping for DirectAddress class.
Check persistence.xml file for entity mapping or you can directly add this class while initializing/loading Configuration.

Related

HSQLDB: case sensitive table names

I have the following jpa/hibernate/hsqldb configuration:
JPA ddl-auto: create-drop
Hibernate entities have no #Table annotation and created with SpringPhysicalNamingStrategy. So, PersonalData entity table name is personal_data. Hibernate creates them due to running the application
hsql DB URL is jdbc:hsqldb:mem:testdb;sql.syntax_pgs=true
My problem is when I try to select due spring repositories with the hsql there is the error about non-existing PERSONAL_DATA table.
I found that this is SQL notation to use CASE_SENSETIVE tables and hqsl follows that. To resolve that developers offer quote table names in sql.
So, I have 2 unlikely ideas
Add #Table annotation to entities.
Override SpringPhysicalNamingStrategy
Is there a way to use a simple property?

SpringBoot JPA Hibernate DB Table name with a "." (period) in it

OK, I'm trying to connect my SpringBoot application via JPA (Hibernate) to a legacy AS/400 DB database. The table names however have a "." (Period) in them.
ex: LE.ONFP is the table name.
Hibernate however is converting the period to an underscore which causes an error because there is not table called "le_onfp".
#Entity
#Table(name = "\"LE.OFNP\"", schema = "QS36F")
Here is my annotations at the beginning of my Entity class.
adding the following line to my application.properties files fixed my issue.
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
and keeping my annotation the same.
#Table(name = "\"LE.OFNP\"", schema = "QS36F")

More than one table found in namespace (, ) - SchemaExtractionException

I have been facing this weird exception while trying to persist some values into a table using Hibernate in a Java application. However this exception occurs only for one particular table/entity for rest of the tables i am able to perform crud operations via Hibernate.
Please find below the Stacktrace and let me know if this is anyway related to java code is or its a database design error.
2016-04-28 11:52:34 ERROR XXXXXDao:44 - Failed to create sessionFactory object.org.hibernate.tool.schema.extract.spi.SchemaExtractionException: More than one table found in namespace (, ) : YYYYYYY
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.XX.dao.XXXXXXXDao.main(XXXXXXXXDao.java:45)
Caused by: org.hibernate.tool.schema.extract.spi.SchemaExtractionException: More than one table found in namespace (, ) : YYYYYYY
at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.processGetTableResults(InformationExtractorJdbcDatabaseMetaDataImpl.java:381)
at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getTable(InformationExtractorJdbcDatabaseMetaDataImpl.java:279)
at org.hibernate.tool.schema.internal.exec.ImprovedDatabaseInformationImpl.getTableInformation(ImprovedDatabaseInformationImpl.java:109)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.performMigration(SchemaMigratorImpl.java:252)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:137)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:110)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:176)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:64)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:458)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at com.xx.dao.zzzzzzzzzzzzDAOFactory.configureSessionFactory(zzzzzzzDAOFactory.java:43)
at com.xx.dao.zzzzzzzzzzzzDAOFactory.buildSessionFactory(zzzzzzzzzDAOFactory.java:27)
at com.xx.dao.XXXXXXXXDao.main(XXXXXXXXDao.java:41)
Thanks in advance for your help
I have had the same problem and was able to dig down to the code to find out the cause, at least in my case. I don't know whether it will be the same issue for you but this may be helpful.
From your stack trace I can see you have the hibernate.hbm2ddl.auto set to upgrade the schema. As part of this, it is trying to look up the metadata for all the tables hibernate knows about and for one of them getting an ambiguous answer because the metadata query is returning more than a single row of table or view metadata.
In my case this was caused by our naming convention for tables. We had a table called (say) "AAA_BBB" for which this was going wrong. Now the use of an underscore in the table name is perfectly acceptable as far as I am aware and is quite common practice. However the underscore is also the SQL wildcard for a single character; looking in the code for the database metadata I can see it is doing a "WHERE table_name LIKE ..." in DatabaseMetaData.getTables(...) method, which is what hibernate is using here.
Now, in my schema I also had a second table called "AAA1BBB" and hence both of these matched the metadata lookup and so it returned a metadata row for each of these tables. The hibernate method is written to just fall down if the result set from the table metadata lookup returns more than one row. I would guess it should examine the available row(s) and find if there is one which is an exact match with the specified table name.
I tested this for both Oracle and MySQL with the same result.
Seems the property hibernate.hbm2ddl.auto set to update is causing the issue here. Try removing it from your hibernate config xml.
This will work:
Check your database schema/s and your database user privileges;
Hibernate update mechanism may fail with this exception if there is a another database schema/user with the same table name, and the db user has the sufficient privileges to view this table.
So in your case, the table 'YYYYYYY' may be found in more than one database user/schema, and your db user has 'DBA' privileges.
To solve this you can either find and delete the ambiguous table or remove the user's redundant privileges.
Another situation may be occurred except whatever dear RichB has been stated.
in ORACLE every user has separate schema ,
Therefore probably there is tow tables with the same name in two different schemes
then you should specify your default schema in persistence.xml with below property
<property name="hibernate.default_schema" value="username"/>
Use catalog value with #Table, i.e.:
#Entity
#Table(**catalog = "MY_DB_USER"**, name = "LOOKUP")
public class Lookup implements Serializable {
}
I don't have this error now.
Hope this work.
We had a Spring Data / JPA application and this error started happening after upgrading to Postgres 10.6 (from 10).
Our solution was as follows, in our JPA configuration class: note the new commented line,
props.put("hibernate.hbm2ddl.auto", "none"); //POSTGRES 10 --> 10.6 migration
Class:
#Configuration
#EnableJpaRepositories(basePackages = "app.dao")
#ComponentScan(basePackages = { "app.service" })
#EnableTransactionManagement
public class JpaConfig {
#Autowired
DataSource dataSource;
#Bean
public Map<String, Object> jpaProperties() {
Map<String, Object> props = new HashMap<String, Object>();
props.put("hibernate.dialect", PostgreSQL95Dialect.class.getName());
props.put("hibernate.hbm2ddl.auto", "none"); //POSTGRES 10 --> 10.6 migration.
return props;
}
So after having the same issue, it turns out that I needed to update my OJDBC driver from ojdbc6 to ojdbc8. Hopefully this helps.
I have same issue with such configuration
#Entity
#Table(name = "NOTIFICATION")
public class Notification {
...
}
issue was resolved for me when I moved table name from #Table to #Entity
#Entity(name = "NOTIFICATION")
#Table
public class Notification {
...
}
Simply, if u are using two schemas then u will get this error. To resolve this error u can use these steps :
1. You need to delete extra schema.
2. Or u can define default schemas or that schema are u using.
spring.jpa.properties.hibernate.default_schema=nameOfSchema
and
jdbc:postgresql://localhost:5432/databaseName?currentSchema=nameOfSchema
I also came across this issue. Here is my solution:
the error:
https://gist.github.com/wencheng1994
I solve that. It mainly because the db account has a higher authority. I set the "hibernate.hbm2ddl.auto=update", So when hbm2ddl works, it tried to find all exists shcema I defied. But there is two schema exist the table with the same name. then the db account can find that. so it found "more than one table in the namespace"
All I need to do is to make the db account lower authority so that it can not find table in other schema. (one shcema relation one db account).

JPA using variable Schema name in annotations

I'm using the Java Persistence API to describe tables from my database that i will manipulate in my code.
However, the schema used is not be the same depending on where my project will be installed. So, when I use the annotations, I would like that the SCHEMA field was a variable, but I can't make it:
#Entity
#Table(name = "TABLE_NAME", schema = schemaVariable, catalog = "")
How can I achieve that?
Is it possible with the persistence.xml file?
No, this is not possible. You can only use compile-time constants (which are all primitives and String) in annotations.
You can use final variables:
public class DatabaseMetadata {
public static final SCHEMA = "MySchema";
}
and then use it in annotation:
#Table(name = "TABLE_NAME", schema = DatabaseMetadata.SCHEMA, catalog = "")
but I think it's not what you wanted.
PS. On the other hand, there can be find examples of using i.e. Spring EL in annotations (see #Value annotation), but this requires custom annotation processor. AFAIK none of JPA providers gives you such ablility.
Putting schema information (like table, column, schema names) in java classes is a bad idea any time IMHO (forcing recompile if you want to deploy elsewhere). You could put that info in orm.xml and just deploy a different orm.xml dependent on your deployment requirement.
As for persistence.xml you would be dependent on your JPA provider having a persistence property that defined the default schema/catalog. I know DataNucleus JPA (what I use) has this, but no idea for Hibernate
If you know that you would be using different schemas, I'd suggest to use 2 mapping files and define
<entity-mappings>
<persistence-unit-metadata>
<persistence-unit-defaults>
<schema>HR</schema>
</persistence-unit-defaults>
</persistence-unit-metadata>
...
</entity-mappings>
In this way you will be able to easily change schemas, without any changes in the application code.

org.hibernate.AnnotationException: #OneToOne or #ManyToOne on <entity> references an unknown entity

I am receiving the following Hibernate Exception:
org.hibernate.AnnotationException: #OneToOne or #ManyToOne on cz.rohan.dusps.model.Switchport.konfiguracniTemplateAccess references an unknown entity: cz.rohan.dusps.model.KonfiguracniTemplate
org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:103)
org.hibernate.cfg.AnnotationConfiguration.processEndOfQueue(AnnotationConfiguration.java:541)
org.hibernate.cfg.AnnotationConfiguration.processFkSecondPassInOrder(AnnotationConfiguration.java:523)
org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:380)
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1377)
org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:954)
cz.rohan.dusps.helper.SessionFactoryHelper.initFactory(SessionFactoryHelper.java:122)
cz.rohan.dusps.helper.SessionFactoryHelper.getSessionFactory(SessionFactoryHelper.java:134)
cz.rohan.dusps.filter.HistorieZmenFilter.doFilter(HistorieZmenFilter.java:102)
cz.rohan.dusps.filter.CharsetFilter.doFilter(CharsetFilter.java:41)
after ~20 hours spent on the problem with various people, having read every possible blog or forum, I am really getting desperate here.
This is a mid-sized project. I should mention the database is Postgres 9.1 and we generate the DB using a modelling tool. Hibernate connects to the database but does not generate it.
I have created a new entity in the database, it's called "KonfiguracniTemplate" (configuration template). I have created the model, controller, form, validators, .jsp's, all basically copied 1:1 from an existing entity of a similar nature. I can now work with KonfiguracniTemplate, CRUD is fully working.
The problem comes when I reference this KonfiguracniTemplate from the entity called Switchport. In the DB there is a relation between the two:
Switchport 1:1 ... 0:N KonfiguracniTemplate (switchport always references a KonfiguracniTemplate; a KonfiguracniTemplate MAY BE referenced zero or more times)
Switchport has FK konfiguracniTemplateAccess_id for this relation.
In .../model/Switchport.java the relation is mapped just like all other relations that are working:
#ManyToOne
#JoinColumn(nullable = false)
private KonfiguracniTemplate konfiguracniTemplateAccess;
I have tried various forms:
#ManyToOne
#JoinColumn(name="konfiguracnitemplateaccess_id", nullable = false)
private KonfiguracniTemplate konfiguracniTemplateAccess;
or
#ManyToOne(targetEntity=KonfiguracniTemplate.class)
#JoinColumn(name="konfiguracnitemplateaccess_id", nullable = false)
private KonfiguracniTemplate konfiguracniTemplateAccess;
I have also checked:
both entities are in the same package
they are both annotated "#Entity" using "import javax.persistence.Entity;"
the build produces no error/warning messages
as long as the reference in Switchport is commented out, everything is fine
No matter what I try I cannot get rid of the "references an unknown entity" exception. Can somebody please share an idea what is happening or maybe how to debug the issue? The stacktrace at the top of the post is all I get in the logs.
All input is greatly appreciated!
Just add the class Team to the "hibernate-cfg.xml" file, because Hibernate doesn't identify without adding into it.
Possible Solutions:
1) Ensure that the entity has been appropriately referenced in hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
...
<mapping class="com.project.entitytwo.model.EntityTwo"/>
...
</session-factory>
2) Ensure that #Entity has been specified at the class-level ( at the top of the class )
#Entity
#Table( name="ENTITY_TWO" )
public class EntityTwo extends AnyClass
{
...
I just had this problem, with entity a referencing entity b. Both entities were located in a common JAR outside of the web project I was working on; a was declared in persistence.xml but b wasn't. I put b in a <class> tag in persistence.xml and it worked!
I ran into this problem when using Spring and not using the hibernate.cfg.xml file. It was solved by adding the fully qualified package name of the Model class to the setPackagesToScan method of LocalSessionFactoryBean class.
Finally got the solution from another developer on the team!
The classes need to be imported before the SessionFactory object is created. Here the import for the new class was missing, so it was unknown to the SessionFactory object.
Anyway, thanks everyone for your hints!
There is one more chance of getting such exception; when you don't mention your mapping class in hibernate.cfg.xml file.
As mentioned above.
I had same exception... I just forget add annotation (#Entity, and #Table) on MASTER class(class with Primary key)
so solution is double check every annotation in your entities , I mean not only #ManyToOne and #OneToMany like i did.
if your two entity in diffrent project,you can scan KonfiguracniTemplate's package in other project.you can do like this in spring boot
#EntityScan({"com.thispackage.entity","com.KonfiguracniTemplatepackage.entity"})
I'll give you a solution that should work for the same error with Spring Boot. This has less to do with the original question, but today, people would probably look for this answer instead because noone uses XML configuration today anymore.
I suffered the same problem and found the solution on this website: https://www.programmersought.com/article/1617314625/
He even describes this very question he would have looked up, but then I'm asking myself: why didn't he answered here after finding the solution? LOL
His own words:
In the Spring Boot project, the default scan package is the package where the main method is located, that is, only the entity classes in the same package as the main method will be discovered. This way you can understand why User is not found: because User is an entity class in another module. Spring Boot does not scan other packages at all;
Configure the #SpringBootApplication annotation on the main method that launches the application, telling Spring Boot that those packages need to be scanned: #SpringBootApplication(scanBasePackages = {“com.xiaomo.*”})
Then, User can be found.
So you basically reconfigure SpringBoot to scan more packages to include the other ones.
My personal addition: you could also move your packages into the package where the starter is located or move the starter a package up (that's what I did).

Categories

Resources