Why is spring.jpa.hibernate.naming.implicit-strategy and physical-strategy being ignored and FK columns have underscores? - spring

I have two entity classes:
#Entity
#Data
public class Holiday {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private LocalDate date;
#ManyToOne
private Calendar calendar;
}
#Entity
#Data
public class Calendar {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
When I run an integration test, I'm getting the following error:
org.springframework.dao.InvalidDataAccessResourceUsageException: could
not extract ResultSet; SQL [n/a]; nested exception is
org.hibernate.exception.SQLGrammarException: could not extract
ResultSet at
... 78 more Caused by:
com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name
'calendar_id'. at
The database has calendarId as the FK. I know that underscore is the default but my application.yml file has:
spring:
jpa:
hibernate:
naming:
implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
This should change have hibernate indicate the column as calendarId. Why does this not work? I'm using Spring Boot 2.7.5.

You can explicitly name the column:
#Column(name = "Calendarid")

Related

Spring JPA: try to delete a record in a table with foreign key constraint

In a project with Spring Boot and Spring JPA I an enitity FunctionConfiguration with a list of Integer target_device
#Entity
#Table(name = "function_configuration")
public class FunctionConfigurationEntity {
#Id
#Column(name = "id_function_configuration")
#GeneratedValue(strategy = IDENTITY)
private Integer idFunctionConfiguration;
#ElementCollection
#CollectionTable(name = "target_device")
private List<Integer> targetDevice;
}
If I try to do a delete with an id of a functionConfiguration
#Transactional
#Modifying
#Query(value = "DELETE FROM FunctionConfigurationEntity fce WHERE fce.idFunctionConfiguration = idFunctionConfiguration")
void deleteByFunctionConfigurationId(#Param("idFunctionConfiguration") Integer functionConfigurationId);
I get the following error:
Caused by: org.postgresql.util.PSQLException: ERROR: UPDATE or DELETE statement on table "function_configuration" violates foreign key constraint "fk69tox326tcrs3wed1neufb0pv" on table "target_device"
How can I fix it?

The object of class oracle.sql.TIMESTAMPTZ from mapping could not be converted to class java.util.Date

I am facing an issue in eclipselink with TIMESTAMPTZ. There is a column in table which have timestamp and timezone. When I run my program I am getting exception.
I have tried everything already on stackOverflow with similar issues and even on the below link.
https://www.eclipse.org/forums/index.php/t/443917/
Query q = em.createNativeQuery("SELECT * FROM MY_Schema.MyTable MT WHERE MT.START_DT = (SELECT MAX(START_DT) FROM MY_Schema.MyTable)",MyTable.class);
#Entity
#Table(name = "MyTable", schema = "MY_Schema")
public class MyTable implements Serializable {
#EmbeddedId
private MyTableId id;
#Embeddable
public class MyTableId implements Serializable {
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "END_DT")
private Calendar endTime;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "START_DT")
private Calendar startTime;
Error message:
5943 [Default Executor-thread-32] ERROR com....MyClass -
javax.persistence.PersistenceException: Exception [EclipseLink-3002]
(Eclipse Persistence Services - 2.6.8.WAS-v20181218-0accd7f):
org.eclipse.persistence.exceptions.ConversionException Exception
Description: The object [oracle.sql.TIMESTAMPTZ#d1f0d927], of class
[class oracle.sql.TIMESTAMPTZ], from mapping
[org.eclipse.persistence.mappings.DirectToFieldMapping[startTime--Y_Schema.MyTable.START_DT]]
with descriptor [RelationalDescriptor(com.....MyTableId -->
[DatabaseTable(MY_Schema.MyTable)])], could not be converted to [class
java.util.Date]. at
org.eclipse.persistence.internal.jpa.QueryImpl.getSingleResult(QueryImpl.java:551)

cross join in SpringBoot 2.1.4.RELEASE app

I have a SpringBoot 2.1.4.RELEASE RESTful Web Service app., using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file. I am using an inMemoryDatabase : H2 Database Engine
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
I have these objects:
#Entity
#Table(name="t_menu_alert_notification")
public class MenuAlertNotification implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#JsonProperty("id")
private Long id;
#ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
#JoinColumn(name = "menu_alert_id")
#JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="name")
#JsonIdentityReference(alwaysAsId=true)
protected MenuAlert menuAlert;
...
}
#Entity
#Table(name="t_menu_alert")
public class MenuAlert implements Serializable {
public MenuAlert() {
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "menu_id")
#JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="name")
#JsonIdentityReference(alwaysAsId=true)
Menu menu;
..
}
#Entity
#Table(name = "t_menu")
#JsonPropertyOrder({ "id", "name", "address", "description" })
public class Menu implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#JsonProperty("id")
private Long id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id", nullable = false)
#JsonIgnore
private User user;
..
}
I have this method in the repository class that extends from a CrudRepository
#Transactional
#Modifying
#Query("update MenuAlertNotification n set n.read = :status where n.id in :notificationIdList and n.menuAlert.menu.user.id = :userId")
void changeMenuNotificationListReadStatus( #Param("notificationIdList") List<Long> notificationIdList,
#Param("userId") long userId,
#Param("status") boolean status);
}
But when I run this method I have this error:
org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [update t_menu_alert_notification cross join set is_read=? where (id in (?)) and user_id=?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:279)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:253)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: org.hibernate.exception.SQLGrammarException: could not prepare statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
... 51 more
Caused by: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "UPDATE T_MENU_ALERT_NOTIFICATION CROSS[*] JOIN SET IS_READ=? WHERE (ID IN (?)) AND USER_ID=? "; expected "., AS, SET"; SQL statement:
update t_menu_alert_notification cross join set is_read=? where (id in (?)) and user_id=? [42001-197]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
at org.h2.message.DbException.getSyntaxError(DbException.java:217)
at org.h2.command.Parser.getSyntaxError(Parser.java:555)
at org.h2.command.Parser.read(Parser.java:3518)
at org.h2.command.Parser.parseUpdateSetClause(Parser.java:785)
at org.h2.command.Parser.parseUpdate(Parser.java:780)
at org.h2.command.Parser.parsePrepared(Parser.java:485)
at org.h2.command.Parser.parse(Parser.java:335)
at org.h2.command.Parser.parse(Parser.java:311)
at org.h2.command.Parser.prepareCommand(Parser.java:278)
at org.h2.engine.Session.prepareLocal(Session.java:611)
at org.h2.engine.Session.prepareCommand(Session.java:549)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1247)
at org.h2.jdbc.JdbcPreparedStatement.<init>(JdbcPreparedStatement.java:76)
at org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:304)
at com.zaxxer.hikari.pool.ProxyConnection.prepareStatement(ProxyConnection.java:311)
at com.zaxxer.hikari.pool.HikariProxyConnection.prepareStatement(HikariProxyConnection.java)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$1.doPrepare(StatementPreparerImpl.java:87)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172)
... 73 more
According to the official documentation:
No joins, either implicit or explicit, can be specified in a bulk HQL
query.
So you need to find n.menuAlert first, then pass as parameter to update query or using native query.

Filter Criteria by attribute with #Convert

I have a simple class with a list of Strings and this list is converted to be one column in db with #Convert and now i'm trying to create a criteria based on type attrbute.
#Entity(name = "my_table")
public class MyTable implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column
#Convert(converter = StringListConverter.class)
private List<String> type;
}
and criteria :
c2.add(Restrictions.ilike("type", matchValue, MatchMode.ANYWHERE));
but I got this exception :
org.springframework.orm.jpa.JpaSystemException: Error attempting to apply AttributeConverter; nested exception is javax.persistence.PersistenceException: Error attempting to apply AttributeConverter
*all entries have a value and I use a psql db
It is not possible right now with Hibernate.
Please see the bug ticket: https://hibernate.atlassian.net/browse/HHH-9991

Spring: relation data many-to-one

i have first entity :
#Entity
#Table(name="TABLE_ONE")
public class TableOne implements Serializable {
#Id
#Column(name="ID")
private Integer id;
#ManyToOne
#JoinColumn(name="TABLE_TWO_ID", nullable = false)
private TableTwo tableTwoId;
and the second table entity :
#Entity
#Table(name="TABLE_TWO")
public class TableTwo{
#Id
#Column(name="ID")
private Integer id;
, but then after i compile , the result is :
ERROR: column "table_two_id" does not exist
I want to get ID from TableTwo.
Joincolumn annotation tells hibernate the foreign key join column name, in this case I guess it's ID.

Resources