SequenceGenerator problem with unit testing in Hsqldb/H2 - java

I have tried using both Hsqldb and H2 for unit testing but facing problem with sequence generators. Field declaration looks like this.
#Id #GeneratedValue(strategy=GenerationType.SEQUENCE, generator="keyword_seq")
#SequenceGenerator(name="keyword_seq",sequenceName="KEYWORD_ID_SEQ", allocationSize=1)
#Column(name="IM_KEYWORD_ID")
private Long keywordId;
When I try to test simple insert in this table in Hsqldb with following configuration, it gives error
<prop key="hibernate.connection.driver_class">org.hsqldb.jdbc.JDBCDriver</prop>
<prop key="hibernate.connection.url">jdbc:hsqldb:mem:testdb;sql.syntax_ora=true</prop>
Error :
Caused by: java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: KEYWORD_ID_SEQ.NEXTVAL
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
With H2:
<prop key="hibernate.connection.driver_class">org.h2.Driver</prop>
<prop key="hibernate.connection.url">jdbc:h2:~/test</prop>
Error is :
Hibernate: select KEYWORD_ID_SEQ.nextval from dual
3085 [main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 42001, SQLState: 42001
3088 [main] ERROR org.hibernate.util.JDBCExceptionReporter - Syntax error in SQL statement "SELECT KEYWORD_ID_SEQ.NEXTVAL FROM[*] DUAL "; expected "identifier"; SQL statement:
Any idea, how to solve this?

I think the dialect is set wrongly. Can you check your hibernate configuration.

Related

In Hibernate using update but still going for a create table

Using Hibernate in my project. I am getting create table queries at my logs,
But I am using a HBM2DDL_AUTO="update"
What else could had been missed ?
PS: I get these logs only when the tables are already present at runtime. If tables not present, it obviously runs smooth.
Here are the properties
Properties settings = new Properties();
settings.put(Environment.DRIVER, "org.postgresql.Driver");
settings.put(Environment.URL, "jdbc:postgresql://" + jdbc_host + ":5432/" + jdbc_database + "?prepareThreshold=0");
settings.put(Environment.USER, jdbc_user);
settings.put(Environment.PASS, jdbc_password);
settings.put(Environment.DIALECT, "org.hibernate.dialect.PostgreSQLDialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
settings.put(Environment.HBM2DDL_AUTO, "update");
Error Logs:
[INFO ]: org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
[INFO ]: org.hibernate.type.BasicTypeRegistry - HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#3add81c4
[WARN ]: org.hibernate.boot.internal.InFlightMetadataCollectorImpl - HHH000069: Duplicate generator name wca_seq_generator
[WARN ]: org.hibernate.boot.internal.InFlightMetadataCollectorImpl - HHH000069: Duplicate generator name wca_seq_generator
[WARN ]: org.hibernate.boot.internal.InFlightMetadataCollectorImpl - HHH000069: Duplicate generator name wca_seq_generator
[INFO ]: org.hibernate.orm.connections.access - HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#59696551] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
[WARN ]: org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl - GenerationTarget encountered exception accepting command : Error executing DDL "create table WCA_MESSAGE_AUDIT (id int8 not null, createts times
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table WCA_MESSAGE_AUDIT (id int8 not null, create
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:559)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:504)
I have not worked postgresql in java but I've worked with MySQL. And Whenever' I need to create the table using hibernate then I mention the follow feature in application.properties and it allow to create the table. please once go for it and if it still doesn't work please inform me. Put it in proprerties.
spring.jpa.hibernate.ddl-auto=update

jpa delete error, while print the update sql

When I use JPA delete, I get an error. I check the log and find an update SQL, I don't know why I execute the deleting, but it prints update SQL
java 1.8, spring-data-jpa-2.1.8
the source code:
cardApplyRepository.delete(CardApply.builder().activityId(23443L).build());
the log:
2019-07-15 13:09:20.478 [main] INFO o.s.t.w.s.TestDispatcherServlet [initServletBean:546] - Completed initialization in 19 ms
Hibernate:
insert
into
t_card_apply
(activity_id, activity_name, app_id, card_base_required_id, card_id, mass_msg_id, seller_id)
values
(?, ?, ?, ?, ?, ?, ?)
2019-07-15 13:09:20.573 [main] WARN o.h.e.j.s.SqlExceptionHelper [logExceptions:137] - SQL Error: 1048, SQLState: 23000
2019-07-15 13:09:20.574 [main] ERROR o.h.e.j.s.SqlExceptionHelper [logExceptions:142] - Column 'card_base_required_id' cannot be null
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:296)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:253)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:138)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy206.delete(Unknown Source)
at com.geek.icem.wechat.service.impl.WxCardServiceImplTest.deleteCard(WxCardServiceImplTest.java:34)
When you pass an Entity to the delete method it should be managed at this point.
For example by using the findById method and passing the result to delete.
You are passing a non-managed entity as you build it on the fly.
So either fetch one first or use the deleteById method instead.
We might not inspect your issue in detail unless you provide the code of CardApply and CardApplyRepository if you are using a custom repository implementation.
What I can get is, you want to delete an entity by id, so, I suggest you that just use the deleteById method of Spring data's CrudRepository like below:
cardApplyRepository.deleteById(23443L);
Hope this helps. Good luck!

Spring Mvc Hibernate Encoding/Multi-line import sql

I am working on Spring MVC,
On project startup i have set database to import default sql
with hibernate configuration hibernate.hbm2ddl.import_files.
Data inside import.sql is encoded with UTF-8.
Console Output
ERROR: org.hibernate.tool.hbm2ddl.SchemaExport - HHH000388:
Unsuccessful: INSERT INTO menu (id, DATE_CREATED, DATE_DELETED,
DATE_UPDATED, TITLE_ENG, TITLE_GEO, TITLE_RUS, ENABLED, PARENT_ID,
URL, SITE_ID, USER_ID) VALUES
ERROR:
org.hibernate.tool.hbm2ddl.SchemaExport - You have an error in your
SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near '' at line 1
ERROR:
org.hibernate.tool.hbm2ddl.SchemaExport - HHH000388: Unsuccessful: (1,
'2015-09-10 12:00:00', NULL, NULL, 'About Us', N'ჩვენს
შეს�ხებ', 'About Us', b'1', NULL, '/article/view/1', 3,
1).
Make sure you are setting the JDBC driver to use UTF-8:
jdbc:mysql://dbname?useUnicode=true&characterEncoding=utf-8
In persistence.xml, set the hibernate connection charset:
<property name="hibernate.connection.charSet" value="UTF-8"/>
If your resources/import.sql file is multi-line, add:
<property
name="hibernate.hbm2ddl.import_files_sql_extractor"
value="org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor"
/>
or for Spring Boot, in application.properties:
spring.jpa.properties.hibernate.connection.charSet=UTF-8
spring.jpa.properties.hibernate.hbm2ddl.import_files_sql_extractor=org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor

Hibertate Criteria with Projections

´m trying to aply a Criteria.Restriction to a query with Projections.
My code is:
ProjectionList projections = Projections.projectionList().add(Projections.property("mId").as("mId"));
projections.add(Projections.property("mDate").as("mDate"));
Criteria criteria = mSession.createCriteria(MailAgroseguro.class)
.add(Restrictions.between("mDate", dateMin, dateMax))
.setProjection(projections)
.setResultTransformer(new AliasToBeanNestedResultTransformer(ObjectClass.class));
listObjectClass = (List<ObjectClass>)criteria.list();
Edit:
The ObjectClass.java:
public class ObjectClass {
private Integer mId;
private String mDate;
}
And the error is:
Hibernate: select this_.mId as y0_, this_.mDate as y1_ from objectclass this_ where y1_ between ? and ?
[INFO] 2014-11-21 16:59:24,554 - org.hibernate.util.JDBCExceptionReporter -25221 [JavaFX Application Thread] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1054, SQLState: 42S22
[INFO] 2014-11-21 16:59:24,554 - org.hibernate.util.JDBCExceptionReporter -25221 [JavaFX Application Thread] ERROR org.hibernate.util.JDBCExceptionReporter - Unknown column 'y1_' in 'where clause'
If I don´t add the Restriction or the Projections works fine!
Edited2: updated Error
Thanks to everyone!

database connection error associated with the encoding

I have Spring + Hibernate application.
I use PostgreSQL as data store.
application compiles good but when I deployed it to Tomcat and launch it I see following stacktrace:
INFO : org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'
WARN : org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 28P01
ERROR: org.hibernate.util.JDBCExceptionReporter - ?????: ???????????? "my_db" ?? ?????? ???????? ??????????? (?? ??????)
WARN : org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 28P01
ERROR: org.hibernate.util.JDBCExceptionReporter - ?????: ???????????? "my_db" ?? ?????? ???????? ??????????? (?? ??????)
ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection
at org.springframework.orm.hibernate3.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:597)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:372)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:417)
.....
Caused by: org.hibernate.exception.GenericJDBCException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:426)
....
at org.springframework.orm.hibernate3.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:556)
... 57 more
Caused by: org.postgresql.util.PSQLException: ?????: ???????????? "my_db" ?? ?????? ???????? ??????????? (?? ??????)
at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:291)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:108)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:66)
at org.postgresql.jdbc2.AbstractJdbc2Connection.<init>(AbstractJdbc2Connection.java:125)
at org.postgresql.jdbc3.AbstractJdbc3Connection.<init>(AbstractJdbc3Connection.java:30)
at org.postgresql.jdbc3g.AbstractJdbc3gConnection.<init>(AbstractJdbc3gConnection.java:22)
at org.postgresql.jdbc4.AbstractJdbc4Connection.<init>(AbstractJdbc4Connection.java:30)
at org.postgresql.jdbc4.Jdbc4Connection.<init>(Jdbc4Connection.java:24)
at org.postgresql.Driver.makeConnection(Driver.java:393)
...
... 62 more
On another PC this application launch good. Difference: locale. Working PC has English language but another - not.
Please help to find cause of the problem.
update
Looks like database doesn't understand password:
from:PostgreSQL Error Codes
28P01 INVALID PASSWORD invalid_password
update
I didn't know the cause of the problem but problem disappear after database recreation.
This is a known issue with the PostgreSQL version 3 protocol, where the client doesn't know the encoding to decode error messages sent by the server early in the protocol handshake.
It will be fixed when the version 4 protocol is produced, but that's a long way off yet.
In the mean time the only real workaround is to make sure that the client's default encoding is compatible with the server's. The easiest way to do that is to set LC_MESSAGES to something like en_US.UTF-8, perhaps via the lc_messages option in postgresql.conf.

Categories

Resources