Hibernate 6: JPA derived query methods failing when boolean mapping using YesNoConverter - spring-boot

I have the below entity where the deleted column in database is of type character with expected values 'Y' or 'N' . I'm using the YesNoConverter to encode the boolean value as 'Y' or 'N' .
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
.
.
#Column(name = "deleted")
#Convert(converter= YesNoConverter.class)
private boolean deleted;
}
But this code is giving error when I have a derived query method querying on the boolean property like below
public interface UserRepository extends JpaRepository<User,Long> {
List<User> findByDeletedFalse();
}
This repository method throws below exception
2023-02-14T10:30:30.160Z WARN 5796 --- [nio-9000-exec-5] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 42804
2023-02-14T10:30:30.160Z ERROR 5796 --- [nio-9000-exec-5] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: argument of NOT must be type boolean, not type character
Position: 128
2023-02-14T10:30:30.161Z ERROR 5796 --- [nio-9000-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.dao.InvalidDataAccessResourceUsageException: JDBC exception executing SQL [select u1_0.id,u1_0.deleted,u1_0.first_name,u1_0.home_address_id,u1_0.last_name,u1_0.work_address_id from users u1_0 where not(u1_0.deleted)]; SQL [n/a]] with root cause
org.postgresql.util.PSQLException: ERROR: argument of NOT must be type boolean, not type character
Position: 128
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2676) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2366) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:356) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:496) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:413) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:190) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:134) ~[postgresql-42.5.1.jar:42.5.1]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-5.0.1.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-5.0.1.jar:na]
at org.hibernate.sql.results.jdbc.internal.DeferredResultSetAccess.executeQuery(DeferredResultSetAccess.java:217) ~[hibernate-core-6.1.7.Final.jar:6.1.7.Final]
at org.hibernate.sql.results.jdbc.internal.DeferredResultSetAccess.getResultSet(DeferredResultSetAccess.java:146) ~[hibernate-core-6.1.7.Final.jar:6.1.7.Final]
at org.hibernate.sql.results.jdbc.internal.JdbcValuesResultSetImpl.advanceNext(JdbcValuesResultSetImpl.java:205) ~[hibernate-core-6.1.7.Final.jar:6.1.7.Final]
at org.hibernate.sql.results.jdbc.internal.JdbcValuesResultSetImpl.processNext(JdbcValuesResultSetImpl.java:85) ~[hibernate-core-6.1.7.Final.jar:6.1.7.Final]
at org.hibernate.sql.results.jdbc.internal.AbstractJdbcValues.next(AbstractJdbcValues.java:29) ~[hibernate-core-6.1.7.Final.jar:6.1.7.Final]
at org.hibernate.sql.results.internal.RowProcessingStateStandardImpl.next(RowProcessingStateStandardImpl.java:88) ~[hibernate-core-6.1.7.Final.jar:6.1.7.Final]
at org.hibernate.sql.results.spi.ListResultsConsumer.consume(ListResultsConsumer.java:197) ~[hibernate-core-6.1.7.Final.jar:6.1.7.Final]
at org.hibernate.sql.results.spi.ListResultsConsumer.consume(ListResultsConsumer.java:33) ~[hibernate-core-6.1.7.Final.jar:6.1.7.Final]
at org.hibernate.sql.exec.internal.JdbcSelectExecutorStandardImpl.doExecuteQuery(JdbcSelectExecutorStandardImpl.java:443) ~[hibernate-core-6.1.7.Final.jar:6.1.7.Final]
at org.hibernate.sql.exec.internal.JdbcSelectExecutorStandardImpl.executeQuery(JdbcSelectExecutorStandardImpl.java:166) ~[hibernate-core-6.1.7.Final.jar:6.1.7.Final]
at org.hibernate.sql.exec.internal.JdbcSelectExecutorStandardImpl.list(JdbcSelectExecutorStandardImpl.java:91) ~[hibernate-core-6.1.7.Final.jar:6.1.7.Final]
at org.hibernate.sql.exec.spi.JdbcSelectExecutor.list(JdbcSelectExecutor.java:31) ~[hibernate-core-6.1.7.Final.jar:6.1.7.Final]
Hibernate: select u1_0.id,u1_0.deleted,u1_0.first_name,u1_0.home_address_id,u1_0.last_name,u1_0.work_address_id from users u1_0 where not(u1_0.deleted)
Code with this issue: https://github.com/chackomathew/spring-boot3-hibernate6/tree/boolean-converter-issue
Spring Boot v3.0.2
Hibernate v6.1.7.Final
If I provide JPQL query like below it's working fine.
#Query("select u from User u where u.deleted=false")
List<User> findByDeletedFalse();

Related

Problem with saving an object with rest template, Spring web app

So I'm building a flashcard app with Spring, JPA, MySQL and using Thymeleaf.
At first when i started building I only used MVC. All functionality for saving a new user, a new flashcard and a new topic worked.
Now I connected it with a project with a restcontroller and did some modifactions.
The problem is that I can't seem to save a new flashcard (although i can save a topic and a user)
Can someone spot where i've made a mistake?
(note. i have a JPARepository in the backend)
#Controller-class
//This does not work
#PostMapping("/save")
public String set(#ModelAttribute Flashcard flashcard){
restTemplate.postForObject("http://localhost:8081/api/card/save", flashcard, Flashcard.class);
return "redirect:/";
}
//this works
#PostMapping("/savePlayer")
public String savePlayer(#ModelAttribute Player player){
restTemplate.postForObject("http://localhost:8081/api/player/save", player, Player.class);
return "homepage";
}
**#RestController-class**
#PostMapping("/api/card/save")
public Flashcard createFlashcard(#RequestBody Flashcard flashcard) {
log.info("New Card added to FlashcardRepository - {}", flashcard);
return repository.save(flashcard);
}
**Flashcard-class**
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "card_id")
Long id;
String term;
String answer;
#ManyToOne
#JsonBackReference
#JoinColumn(name = "topic_id")
Topic topic;
Error message:
2022-07-15 10:17:41.555 WARN 2016 --- [nio-8081-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1048, SQLState: 23000
2022-07-15 10:17:41.556 ERROR 2016 --- [nio-8081-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : Column 'topic_id' cannot be null
2022-07-15 10:17:41.608 ERROR 2016 --- [nio-8081-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

Spring-Data-JPA Hibernate: how to override/update a detached entity with the same ID?

I have to override/update a set of existing entities mapped by a cascade #OneToMany relationship from another class.
I would like to avoid having to previously load the existing entities and then save them
for making them attached to the session.
#Data
#Entity
#Table(name = "my_asset")
public class MyAsset {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#OneToMany(mappedBy = "myAsset",
fetch = FetchType.EAGER,
cascade = {CascadeType.ALL},
orphanRemoval = true)
private List<AssetComponent> components = new ArrayList<>();
}
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
#EqualsAndHashCode(onlyExplicitlyIncluded = true)
#Entity
#SelectBeforeUpdate
#DynamicUpdate
#Table(name = "asset_component")
public class AssetComponent {
#Id
#EqualsAndHashCode.Include
private UUID id;
#Column(name = "model_id", nullable = false)
private UUID modelID;
#Column(nullable = false)
private String type;
#Column(nullable = false)
private String name;
#ManyToOne(optional = false)
#OnDelete(action = OnDeleteAction.CASCADE)
private MyAsset myAsset;
}
#Repository
public interface MyAssetRepository extends JpaRepository<MyAsset, Long> {}
Now, if I have an existing MyAsset with some existing components already in the DB, I cannot save the MyAsset directly:
MyAsset myAsset = new MyAsset();
myAsset.setComponents(Collections.singletonList(AssetComponent.builder()
.id(UUID.fromString("b76d8a3b-2f0c-442a-bf50-58a19fce0fc9"))
.modelID(UUID.fromString("22db9474-eeeb-4007-91a8-3e8bdfa9b83a"))
.name("Component A")
.type("Type A")
.myAsset(myAsset)
.build()));
myAssetRepository.save(myAsset);
because it gives me a stack of exceptions about the duplicate key exception with the AssetComponent ID:
org.springframework.dao.DataIntegrityViolationException
org.hibernate.exception.ConstraintViolationException
org.postgresql.util.PSQLException
How can I make the MyAsset & AssetComponent #Repository automatically merge the existing entities (if they have the same id) even if they have not been previously loaded from the DB?
Update
I created a GitHub repository to show you the minimum not working example: https://github.com/MaurizioCasciano/Spring-Data-JPA-Testing
I slightly changed the entities' name to make them as much general as possible: Container 1 --> N Item
I also enabled as much debugging as possible (at least i think so. Let me know if I can show more debugging info) using these properties:
spring:
datasource:
url: jdbc:h2:mem:test
driver-class-name: org.h2.Driver
username: test
password: test
h2:
console:
enabled: true
path: /h2-console
jpa:
database-platform: org.hibernate.dialect.H2Dialect
properties:
hibernate:
show_sql: true
format_sql: true
use_sql_comments: true
logging:
level:
org.hibernate.type: trace
This is the simple #Test I'm running:
#SpringBootTest
public class ContainerRepositoryTests {
#Autowired
private ContainerRepository containerRepository;
#Test
public void testSaveContainer(){
final UUID containerID = UUID.randomUUID();
Container container = new Container();
container.setId(containerID);
Collection<Item> items = new HashSet<>();
final UUID itemID = UUID.randomUUID();
Item item = new Item();
item.setId(itemID);
item.setContainer(container);
items.add(item);
container.setItems(items);
this.containerRepository.save(container);
this.containerRepository.save(container);
}
}
and it results in the following console output:
Hibernate:
drop table if exists container CASCADE
Hibernate:
drop table if exists container_items CASCADE
Hibernate:
drop table if exists item CASCADE
Hibernate:
create table container (
id binary(255) not null,
primary key (id)
)
Hibernate:
create table container_items (
container_id binary(255) not null,
items_id binary(255) not null
)
Hibernate:
create table item (
id binary(255) not null,
container_id binary(255) not null,
primary key (id)
)
Hibernate:
alter table container_items
add constraint UK_tjc4gid6ob0h8pqhc9f4s1u9k unique (items_id)
Hibernate:
alter table container_items
add constraint FK3jaf77lxfykpono42ak2pqh7p
foreign key (items_id)
references item
Hibernate:
alter table container_items
add constraint FKt1xy6gjb3c94t8ifnjp36hsol
foreign key (container_id)
references container
Hibernate:
alter table item
add constraint FK9b9sc6vhhyquxqbixmhqtx0g
foreign key (container_id)
references container
Hibernate:
/* load org.testing.spring.data.jpa.domain.Container */ select
container0_.id as id1_0_1_,
items1_.container_id as containe1_1_3_,
item2_.id as items_id2_1_3_,
item2_.id as id1_2_0_,
item2_.container_id as containe2_2_0_
from
container container0_
left outer join
container_items items1_
on container0_.id=items1_.container_id
left outer join
item item2_
on items1_.items_id=item2_.id
where
container0_.id=?
2022-06-10 09:36:41.066 TRACE 12924 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BINARY] - [b8718f19-8a5c-480a-bcb4-a116a74a0fd0]
Hibernate:
/* load org.testing.spring.data.jpa.domain.Item */ select
item0_.id as id1_2_0_,
item0_.container_id as containe2_2_0_
from
item item0_
where
item0_.id=?
2022-06-10 09:36:41.100 TRACE 12924 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BINARY] - [63050373-8b6b-4fca-8ead-49319ee0c1bb]
Hibernate:
/* insert org.testing.spring.data.jpa.domain.Container
*/ insert
into
container
(id)
values
(?)
2022-06-10 09:36:41.121 TRACE 12924 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BINARY] - [b8718f19-8a5c-480a-bcb4-a116a74a0fd0]
Hibernate:
/* insert org.testing.spring.data.jpa.domain.Item
*/ insert
into
item
(container_id, id)
values
(?, ?)
2022-06-10 09:36:41.124 TRACE 12924 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BINARY] - [b8718f19-8a5c-480a-bcb4-a116a74a0fd0]
2022-06-10 09:36:41.125 TRACE 12924 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [BINARY] - [63050373-8b6b-4fca-8ead-49319ee0c1bb]
Hibernate:
/* insert collection
row org.testing.spring.data.jpa.domain.Container.items */ insert
into
container_items
(container_id, items_id)
values
(?, ?)
2022-06-10 09:36:41.128 TRACE 12924 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BINARY] - [b8718f19-8a5c-480a-bcb4-a116a74a0fd0]
2022-06-10 09:36:41.128 TRACE 12924 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [BINARY] - [63050373-8b6b-4fca-8ead-49319ee0c1bb]
Hibernate:
/* load org.testing.spring.data.jpa.domain.Container */ select
container0_.id as id1_0_1_,
items1_.container_id as containe1_1_3_,
item2_.id as items_id2_1_3_,
item2_.id as id1_2_0_,
item2_.container_id as containe2_2_0_
from
container container0_
left outer join
container_items items1_
on container0_.id=items1_.container_id
left outer join
item item2_
on items1_.items_id=item2_.id
where
container0_.id=?
2022-06-10 09:36:41.134 TRACE 12924 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BINARY] - [b8718f19-8a5c-480a-bcb4-a116a74a0fd0]
Hibernate:
/* load org.testing.spring.data.jpa.domain.Item */ select
item0_.id as id1_2_0_,
item0_.container_id as containe2_2_0_
from
item item0_
where
item0_.id=?
2022-06-10 09:36:41.137 TRACE 12924 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BINARY] - [63050373-8b6b-4fca-8ead-49319ee0c1bb]
Hibernate:
/* insert org.testing.spring.data.jpa.domain.Container
*/ insert
into
container
(id)
values
(?)
2022-06-10 09:36:41.138 TRACE 12924 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BINARY] - [b8718f19-8a5c-480a-bcb4-a116a74a0fd0]
2022-06-10 09:36:41.141 WARN 12924 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 23505, SQLState: 23505
2022-06-10 09:36:41.142 ERROR 12924 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Unique index or primary key violation: "PUBLIC.PRIMARY_KEY_8 ON PUBLIC.CONTAINER(ID) VALUES ( /* 1 */ CAST(X'b8718f198a5c480abcb4a116a74a0fd00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' AS BINARY(255)) )"; SQL statement:
/* insert org.testing.spring.data.jpa [23505-212]
2022-06-10 09:36:41.142 INFO 12924 --- [ main] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint ["PUBLIC.PRIMARY_KEY_8 ON PUBLIC.CONTAINER(ID) VALUES ( /* 1 */ CAST(X'b8718f198a5c480abcb4a116a74a0fd00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' AS BINARY(255)) )"; SQL statement:
/* insert org.testing.spring.data.jpa [23505-212]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:276)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:566)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:654)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:407)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
at jdk.proxy2/jdk.proxy2.$Proxy111.save(Unknown Source)
at org.testing.spring.data.jpa.repository.ContainerRepositoryTests.testSaveContainer(ContainerRepositoryTests.java:39)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:577)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:37)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:200)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:46)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3375)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3908)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:107)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478)
at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:721)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:344)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1407)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:489)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3290)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2425)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:449)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:562)
... 82 more
Caused by: org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Unique index or primary key violation: "PUBLIC.PRIMARY_KEY_8 ON PUBLIC.CONTAINER(ID) VALUES ( /* 1 */ CAST(X'b8718f198a5c480abcb4a116a74a0fd00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' AS BINARY(255)) )"; SQL statement:
/* insert org.testing.spring.data.jpa [23505-212]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:508)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:477)
at org.h2.message.DbException.get(DbException.java:223)
at org.h2.message.DbException.get(DbException.java:199)
at org.h2.index.Index.getDuplicateKeyException(Index.java:525)
at org.h2.mvstore.db.MVSecondaryIndex.checkUnique(MVSecondaryIndex.java:223)
at org.h2.mvstore.db.MVSecondaryIndex.add(MVSecondaryIndex.java:184)
at org.h2.mvstore.db.MVTable.addRow(MVTable.java:519)
at org.h2.command.dml.Insert.insertRows(Insert.java:174)
at org.h2.command.dml.Insert.update(Insert.java:135)
at org.h2.command.dml.DataChangeStatement.update(DataChangeStatement.java:74)
at org.h2.command.CommandContainer.update(CommandContainer.java:174)
at org.h2.command.Command.executeUpdate(Command.java:252)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:209)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:169)
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197)
... 103 more
Hibernate already does select by id before saving detached entity. But the problem is that hibernate can't find entity by uuid. I don't know exactly how it works (it is possible that the problem is in the DBMS), but you can fix it by adding #Type annotation:
#Entity
public class Container {
#Id
#Type(type = "uuid-char")
private UUID id;
}
Spring Data JPA should already detect, that the entity is not new and should call merge.
You could make your entity implement Persistable which should fix the problem.
Alternatively, you could create a breakpoint in SimpleJpaRepository.save(..) and debug, why Spring Data JPA doesn't consider your entity new.

why is there error, when i use querydsl in kotlin?

i want to use querydsl in springboot(kotlin), but when i test querydsl by useing findOne(), there is error..
Account data class
#Entity
data class Account(
val username: String,
val firstName: String,
val lastName: String
) {
#Id
#GeneratedValue
val id: Long? = null
}
AccountRepository
interface AccountRepository : JpaRepository<Account, Long>,
QuerydslPredicateExecutor<Account>
test code
#DataJpaTest
class AccountRepositoryTest {
#Autowired
lateinit var accountRepository: AccountRepository
#Test
fun crud() {
accountRepository.save(Account(username = "sooyougkim",
firstName = "sooyoug",
lastName = "kim"))
val predicate: Predicate = QAccount
.account
.firstName
.containsIgnoreCase("sooyoug")
.and(QAccount.account.lastName.startsWith("kim"))
val findOne = accountRepository.findOne(predicate).get()
}
}
error message
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap.put(Collections.java:1459)
at com.querydsl.jpa.JPQLSerializer.visitConstant(JPQLSerializer.java:327)
at com.querydsl.core.support.SerializerBase.visit(SerializerBase.java:221)
at com.querydsl.core.support.SerializerBase.visit(SerializerBase.java:36)
at com.querydsl.core.types.ConstantImpl.accept(ConstantImpl.java:140)
.
.
.
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
at java.lang.Thread.run(Thread.java:821)
AccountRepositoryTest > crud() FAILED
java.lang.UnsupportedOperationException at AccountRepositoryTest.kt:31
2020-07-30 09:58:37.653 INFO 21450 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-07-30 09:58:37.653 INFO 21450 --- [extShutdownHook] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
Hibernate:
i think that there is some mapping error QAccount -> Account...
is there anyone to check?
I solved the problem.
the reason is plugin version problem..
when i changed version to latest, querydsl doing well.
this is my dependency of build.gradle.kts
api("com.querydsl:querydsl-jpa:4.3.1")
kapt("com.querydsl:querydsl-apt:4.3.1:jpa")
and, you can check the version of plugin here.
https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/html/appendix-dependency-versions.html

Problem with a ORACLE LONG datatype field when searching for it with JPA

Solved with a workaround, read in bottom
I have a model called "EmailTransmitido":
#Data
#Entity
#Builder
#Table(schema = "EMAIL", name = "EN_EMAIL_TRANSMITIDO")
public class EmailTransmitido extends EntidadeBase {
...
#ManyToOne
#JoinColumn(name = "NRO_EMAIL")
private EmailMensagem emailMensagem;
...
And another called "EmailMensagem":
#Data
#Entity
#Table(schema = "EMAIL", name = "EN_MENSAGEM_EMAIL")
public class EmailMensagem extends EntidadeBase {
...
#Column(name = "TXT_TITULO")
private String txtTitulo;
#Column(name = "TXT_MENSAGEM")
private String txtMensagem;
...
Then i need to search through this field "
#Repository
public interface EmailTransmitidoRepository extends JpaRepository<EmailTransmitido, Long> {
...
#Query("SELECT et FROM EmailTransmitido et WHERE et.recursoHumano = ?1 "
+ "AND et.emailMensagem.txtMensagem LIKE %?2%")
Page<EmailTransmitido> getMensagensNotArquivadasByEnRh(
#Param("enRh") EnRh enRh, #Param("pesquisa") String pesquisa, Pageable pageable);
...
But i receive a error:
Hibernate:
select
*
from
( select
emailtrans0_.SEQ_EMAIL_TRANSMITIDO as SEQ_EMAIL_TRANSMIT1_5_,
emailtrans0_.TXT_CAMPOS_MSG as TXT_CAMPOS_MSG2_5_,
emailtrans0_.DTA_AGENDA as DTA_AGENDA3_5_,
emailtrans0_.DTA_ULT_ATUALIZ as DTA_ULT_ATUALIZ4_5_,
emailtrans0_.DTA_ENVIO as DTA_ENVIO5_5_,
emailtrans0_.NRO_EMAIL as NRO_EMAIL6_5_,
emailtrans0_.STA_EMAIL_TESTE as STA_EMAIL_TESTE7_5_,
emailtrans0_.TXT_USERNAME_ULT_ATUALIZ as TXT_USERNAME_ULT_A8_5_,
emailtrans0_.NRO_MODELO_DOC as NRO_MODELO_DOC9_5_,
emailtrans0_.COD_RH as COD_RH17_5_,
emailtrans0_.STA_EMAIL_TRANSMITIDO as STA_EMAIL_TRANSMI10_5_,
emailtrans0_.TXT_CAMPOS_MSG_BKP as TXT_CAMPOS_MSG_BK11_5_,
emailtrans0_.TXT_EMAIL as TXT_EMAIL12_5_,
emailtrans0_.TXT_EMAIL_COPIA as TXT_EMAIL_COPIA13_5_,
emailtrans0_.TXT_EMAIL_COPIA_OCULTA as TXT_EMAIL_COPIA_O14_5_,
emailtrans0_.TXT_ERRO_TRANSMISSAO as TXT_ERRO_TRANSMIS15_5_,
emailtrans0_.TXT_REMETENTE as TXT_REMETENTE16_5_
from
EMAIL.EN_EMAIL_TRANSMITIDO emailtrans0_ cross
join
EMAIL.EN_MENSAGEM_EMAIL emailmensa1_
where
emailtrans0_.NRO_EMAIL=emailmensa1_.NRO_EMAIL
and emailtrans0_.COD_RH=?
and (
TO_CLOB(emailmensa1_.TXT_MENSAGEM) like ?
)
order by
emailtrans0_.SEQ_EMAIL_TRANSMITIDO desc )
where
rownum <= ?
2019-06-03 16:49:12.542 WARN 10560 --- [nio-9500-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 932, SQLState: 42000
2019-06-03 16:49:12.542 ERROR 10560 --- [nio-9500-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-00932: tipos de dados inconsistentes: esperava CHAR obteve LONG
2019-06-03 16:49:12.549 ERROR 10560 --- [nio-9500-exec-2] o.a.c.c.C.[.[.[.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [/cm-api] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
java.sql.SQLSyntaxErrorException: ORA-00932: tipos de dados inconsistentes: esperava CHAR obteve LONG
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447) ~[ojdbc6.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396) ~[ojdbc6.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951) ~[ojdbc6.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513) ~[ojdbc6.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227) ~[ojdbc6.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531) ~[ojdbc6.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:208) ~[ojdbc6.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:886) ~[ojdbc6.jar:11.2.0.4.0]
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1175) ~[ojdbc6.jar:11.2.0.4.0]
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1296) ~[ojdbc6.jar:11.2.0.4.0]
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3613) ~[ojdbc6.jar:11.2.0.4.0]
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3657) ~[ojdbc6.jar:11.2.0.4.0]
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1495) ~[ojdbc6.jar:11.2.0.4.0]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-3.2.0.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-3.2.0.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:60) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.loader.Loader.getResultSet(Loader.java:2167) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1930) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1892) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.loader.Loader.doQuery(Loader.java:937) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:340) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2689) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2672) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2506) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.loader.Loader.list(Loader.java:2501) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:504) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:395) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:220) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1508) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1537) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1505) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.query.Query.getResultList(Query.java:135) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.springframework.data.jpa.repository.query.JpaQueryExecution$PagedExecution.doExecute(JpaQueryExecution.java:194) ~[spring-data-jpa-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:91) ~[spring-data-jpa-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:136) ~[spring-data-jpa-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:125) ~[spring-data-jpa-2.1.5.RELEASE.jar:2.1.5.RELEASE]
This kind of error "java.sql.SQLSyntaxErrorException: ORA-00932: tipos de dados inconsistentes: esperava CHAR obteve LONG" that means "expected CHAR got LONG" would be something related to the LONG datatype in Oracle be deprecated? i mean, others field that uses differents datatypes works well with similar search queries.
I tried to make use of the #Formula instead of #Column, but it didn't work:
#Formula("TOCLOB(TXT_MENSAGEM)")
private String txtMensagem;
I tried to use JPQ Query method too but the problem persists, only with this specific LONG field. My main problem is that i can't change the datatype in the Oracle because it's a client's old database from where i only can read, and i don't have permission to make changes there, so is there some workaround to compare this field with JPA?
I solved this problem with another table created to keep those data in CLOB format. As the column is of a fixed value and the consumer didn't object to it. Need to say here that i searched a lot and appears to don't have a good workaround for it yet, so if you face this problem too, think about doing the same or change definitively you column data type. Thanks all for the help.
You should be able to map Long as LOB like:
#Lob
#Column(name = "TXT_MENSAGEM")
private String txtMensagem;

using spring data jpa with spring boot issue

my entity Client
#Entity
public class Client implements Serializable {
#Id #GeneratedValue
private long code;
private String nom;
private String email;
#OneToMany(mappedBy = "client",fetch = FetchType.LAZY)
private Collection<Compte> comptes;
public Client(long code, String nom, String email, Collection<Compte> comptes) {
this.code = code;
this.nom = nom;
this.email = email;
this.comptes = comptes;
}
/...
getters and setters
}
entity Compte
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "TYPE_CPTE,",discriminatorType= DiscriminatorType.STRING,length = 2)
public abstract class Compte implements Serializable {
#Id
private String codeCompte;
private Date dataCreation;
private double solde;
#ManyToOne
#JoinColumn(name="CODE_CLI")
private Client client;
#OneToMany(mappedBy="compte")
private Collection<Operation> operations;
public Compte() {
super();
}
public Compte(String codeCompte, Date dataCreation, double solde, Client client, Collection<Operation> operations) {
this.codeCompte = codeCompte;
this.dataCreation = dataCreation;
this.solde = solde;
this.client = client;
this.operations = operations;
}
/...
getters and setters
}
entity Operation
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "TYPE_OP",discriminatorType = DiscriminatorType.STRING,length = 1)
public abstract class Operation implements Serializable{
#Id #GeneratedValue
private long numero;
private Date dateOperation;
private double montant;
#ManyToOne
#JoinColumn(name = "CODE_CPTE")
private Compte compte;
public Operation() {
super();
}
public Operation(Date dateOperation, double montant, Compte compte) {
this.dateOperation = dateOperation;
this.montant = montant;
this.compte = compte;
}
/...getters and setters
}
entity Retirer
#Entity
#DiscriminatorValue("R")
public class Retrait extends Operation {
public Retrait() {
}
public Retrait(Date dateOperation, double montant, Compte compte) {
super(dateOperation, montant, compte);
}
}
entity versement
#Entity
#DiscriminatorValue("V")
public class Versement extends Operation {
public Versement() {
}
public Versement(Date dateOperation, double montant, Compte compte) {
super(dateOperation, montant, compte);
}
}
entity Comptecourant
#Entity
#DiscriminatorValue("CE")
public class CompteEpargne extends Compte {
private double taux;
public CompteEpargne(String s, Date date, int i, Client c2, double taux) {
this.taux = taux;
}
public CompteEpargne(String codeCompte, Date dataCreation, double solde, Client client, Collection<Operation> operations, double taux) {
super(codeCompte, dataCreation, solde, client, operations);
this.taux = taux;
}
public CompteEpargne(){
super();
}
/...getters and setters
}
**entity CompteEpagne**
#Entity
#DiscriminatorValue("CC")
public class CompteCourant extends Compte {
private double decouvert;
public CompteCourant(String s, Date date, int i, Client c1, double decouvert) {
this.decouvert = decouvert;
}
public CompteCourant(String codeCompte, Date dataCreation, double solde, Client client, Collection<Operation> operations, double decouvert) {
super(codeCompte, dataCreation, solde, client, operations);
this.decouvert = decouvert;
}
public CompteCourant(){
super();
}
/...getters and setters
}
Repositorys
1
#Repository
public interface ClientRep extends JpaRepository<Client,Long> {
}
2
#Repository
public interface CompteRep extends JpaRepository<Compte,String> {
}
3
#Repository
public interface OperationRep extends JpaRepository<Operation,Long> {
#Query("select o from Operation o where o.compte.codeCompte=:x order by o.dateOperation desc ")
public Page<Operation> listOperation(String codeCpte, Pageable pageable);
}
service
public interface IBankMetier {
public Compte consulterCompte(String codeCpte);
public void verser(String codeCpte, double montant);
public void retirer(String codeCpte, double montant);
public void virement(String codeCpte1, String codeCpte2, double montant);
public Page<Operation> listOperation(String codeCpte, int page, int size);
}
implimantation
#Service
#Transactional
public class BankMetierImp implements IBankMetier {
#Autowired
private CompteRep compteRep;
#Autowired
private OperationRep operationRep;
#Override
public Compte consulterCompte(String codeCpte) {
Compte cp = compteRep.findOne(codeCpte);
if (cp == null) throw new RuntimeException("Compte introvable");
return cp;
}
#Override
public void verser(String codeCpte, double montant) {
Compte cp = consulterCompte(codeCpte);
Versement v = new Versement(new Date(), montant, cp);
operationRep.save(v);
cp.setSolde((cp.getSolde() + montant));
compteRep.save(cp);
}
#Override
public void retirer(String codeCpte, double montant) {
Compte cp = consulterCompte(codeCpte);
double facili = 0;
if (cp instanceof CompteCourant)
facili = ((CompteCourant) cp).getDecouvert();
if (cp.getSolde() + facili < montant)
throw new RuntimeException("solde insuffisant");
Retrait retrait = new Retrait(new Date(), montant, cp);
operationRep.save(retrait);
cp.setSolde((cp.getSolde() - montant));
compteRep.save(cp);
}
#Override
public void virement(String codeCpte1, String codeCpte2, double montant) {
retirer(codeCpte1, montant);
verser(codeCpte2, montant);
}
#Override
public Page<Operation> listOperation(String codeCpte, int page, int size) {
return operationRep.listOperation(codeCpte,new PageRequest(page,size));
}
}
Spring boot Application
#SpringBootApplication
public class MeinproApplication implements CommandLineRunner {
#Autowired
private ClientRep clientRep;
#Autowired
private CompteRep compteRep;
#Autowired
private OperationRep operationRep;
#Autowired
BankMetierImp bankMetier;
public static void main(String[] args) {
SpringApplication.run(MeinproApplication.class, args);
}
#Override
public void run(String... strings) throws Exception {
Client c1=clientRep.save(new Client("martin","martin#gmail.com"));
Client c2=clientRep.save(new Client("john","john#gmail.com"));
Compte cp1=compteRep.save(new CompteCourant("c1",new Date(),9000,c1,6000));
Compte cp2=compteRep.save(new CompteEpargne("c2",new Date(),63000,c2,12220));
operationRep.save(new Retrait(new Date(),6000,cp1));
operationRep.save(new Retrait(new Date(),10000,cp2));
operationRep.save(new Versement(new Date(),2000,cp1));
operationRep.save(new Versement(new Date(),20,cp2));
bankMetier.verser("c1",1000);
bankMetier.virement("c1","c2",2000);
}
}
application.properties
# DataSource settings:
spring.datasource.url=jdbc:mysql://localhost:3306/monbank
spring.datasource.username=roo
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
when I run it booom !!!!
2017-02-12 16:15:24.858 INFO 6232 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate Core {5.0.11.Final}
2017-02-12 16:15:24.860 INFO 6232 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2017-02-12 16:15:24.863 INFO 6232 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2017-02-12 16:15:24.947 INFO 6232 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-02-12 16:15:25.113 INFO 6232 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-02-12 16:15:25.938 INFO 6232 --- [ restartedMain] org.hibernate.tuple.PojoInstantiator : HHH000182: No default (no-argument) constructor for class: meinpro.entiti.Client (class must be instantiated by Interceptor)
2017-02-12 16:15:26.209 INFO 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
Hibernate: alter table compte drop foreign key FK2hw4shqsxc782lychpkr52lmv
2017-02-12 16:15:26.228 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table compte drop foreign key FK2hw4shqsxc782lychpkr52lmv
2017-02-12 16:15:26.228 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : Table 'monbank.compte' doesn't exist
Hibernate: alter table operation drop foreign key FKkr9nfjf0ipqrw5xwcf9jqq6gv
2017-02-12 16:15:26.229 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table operation drop foreign key FKkr9nfjf0ipqrw5xwcf9jqq6gv
2017-02-12 16:15:26.229 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : Table 'monbank.operation' doesn't exist
Hibernate: drop table if exists client
Hibernate: drop table if exists compte
Hibernate: drop table if exists operation
Hibernate: create table client (code bigint not null auto_increment, email varchar(255), nom varchar(255), primary key (code))
Hibernate: create table compte (type_cpte, varchar(2) not null, code_compte varchar(255) not null, data_creation datetime, solde double precision not null, decouvert double precision, taux double precision, code_cli bigint, primary key (code_compte))
2017-02-12 16:15:26.712 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: create table compte (type_cpte, varchar(2) not null, code_compte varchar(255) not null, data_creation datetime, solde double precision not null, decouvert double precision, taux double precision, code_cli bigint, primary key (code_compte))
2017-02-12 16:15:26.713 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' varchar(2) not null, code_compte varchar(255) not null, data_creation datetime,' at line 1
Hibernate: create table operation (type_op varchar(1) not null, numero bigint not null auto_increment, date_operation datetime, montant double precision not null, code_cpte varchar(255), primary key (numero))
Hibernate: alter table compte add constraint FK2hw4shqsxc782lychpkr52lmv foreign key (code_cli) references client (code)
2017-02-12 16:15:27.146 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table compte add constraint FK2hw4shqsxc782lychpkr52lmv foreign key (code_cli) references client (code)
2017-02-12 16:15:27.147 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : Table 'monbank.compte' doesn't exist
Hibernate: alter table operation add constraint FKkr9nfjf0ipqrw5xwcf9jqq6gv foreign key (code_cpte) references compte (code_compte)
2017-02-12 16:15:27.330 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table operation add constraint FKkr9nfjf0ipqrw5xwcf9jqq6gv foreign key (code_cpte) references compte (code_compte)
2017-02-12 16:15:27.331 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : Can't create table `monbank`.`#sql-23d4_77` (errno: 150 "Foreign key constraint is incorrectly formed")
2017-02-12 16:15:27.332 INFO 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2017-02-12 16:15:27.414 INFO 6232 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-02-12 16:15:27.938 INFO 6232 --- [ restartedMain] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
2017-02-12 16:15:28.776 INFO 6232 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#2ffb82a2: startup date [Sun Feb 12 16:15:18 PST 2017]; root of context hierarchy
2017-02-12 16:15:28.936 INFO 6232 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-02-12 16:15:28.938 INFO 6232 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-02-12 16:15:29.022 INFO 6232 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-02-12 16:15:29.022 INFO 6232 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-02-12 16:15:29.112 INFO 6232 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-02-12 16:15:29.263 WARN 6232 --- [ restartedMain] .t.AbstractTemplateResolverConfiguration : Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
2017-02-12 16:15:30.063 INFO 6232 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2017-02-12 16:15:30.159 INFO 6232 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-02-12 16:15:30.246 INFO 6232 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
Hibernate: insert into client (email, nom) values (?, ?)
Hibernate: insert into client (email, nom) values (?, ?)
2017-02-12 16:15:30.461 INFO 6232 --- [ restartedMain] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-02-12 16:15:30.472 ERROR 6232 --- [ restartedMain] o.s.boot.SpringApplication : Application startup failed
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:779) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:760) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:747) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at meinpro.MeinproApplication.main(MeinproApplication.java:30) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.1.RELEASE.jar:1.5.1.RELEASE]
Caused by: org.springframework.orm.jpa.JpaSystemException: ids for this class must be manually assigned before calling save(): meinpro.entiti.Compte; nested exception is org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): meinpro.entiti.Compte
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:333) ~[spring-orm-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244) ~[spring-orm-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:491) ~[spring-orm-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59) ~[spring-tx-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213) ~[spring-tx-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147) ~[spring-tx-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at com.sun.proxy.$Proxy86.save(Unknown Source) ~[na:na]
at meinpro.MeinproApplication.run(MeinproApplication.java:38) [classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:776) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
... 11 common frames omitted
Caused by: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): meinpro.entiti.Compte
at org.hibernate.id.Assigned.generate(Assigned.java:34) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:101) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:67) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:189) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:132) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:775) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:748) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:753) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1146) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298) ~[spring-orm-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at com.sun.proxy.$Proxy82.persist(Unknown Source) ~[na:na]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:508) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:504) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:489) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.6.RELEASE.jar:4.3.6.RELEASE]
... 22 common frames omitted
2017-02-12 16:15:30.478 INFO 6232 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#2ffb82a2: startup date [Sun Feb 12 16:15:18 PST 2017]; root of context hierarchy
2017-02-12 16:15:30.483 INFO 6232 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
2017-02-12 16:15:30.485 INFO 6232 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2017-02-12 16:15:30.485 INFO 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
Hibernate: alter table compte drop foreign key FK2hw4shqsxc782lychpkr52lmv
2017-02-12 16:15:30.488 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table compte drop foreign key FK2hw4shqsxc782lychpkr52lmv
2017-02-12 16:15:30.489 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : Table 'monbank.compte' doesn't exist
Hibernate: alter table operation drop foreign key FKkr9nfjf0ipqrw5xwcf9jqq6gv
2017-02-12 16:15:30.499 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table operation drop foreign key FKkr9nfjf0ipqrw5xwcf9jqq6gv
2017-02-12 16:15:30.500 ERROR 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : Can't DROP 'FKkr9nfjf0ipqrw5xwcf9jqq6gv'; check that column/key exists
Hibernate: drop table if exists client
Hibernate: drop table if exists compte
Hibernate: drop table if exists operation
2017-02-12 16:15:30.879 INFO 6232 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
Process finished with exit code 0
please help me
The error message is telling you exactly what the problem is
Caused by: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): meinpro.entiti.Compte
The id in your Compte class is not a generated value, like the other tables
#Id
private String codeCompte;
So you need to set this value yourself before you save it.
Now look at the CompteEpargne and the CompteCourant (which extend Compte) constructors
public CompteEpargne(String s, Date date, int i, Client c2, double taux) {
this.taux = taux;
}
public CompteEpargne(String codeCompte, Date dataCreation, double solde, Client client, Collection<Operation> operations, double taux) {
super(codeCompte, dataCreation, solde, client, operations);
this.taux = taux;
}
public CompteCourant(String s, Date date, int i, Client c1, double decouvert) {
this.decouvert = decouvert;
}
public CompteCourant(String codeCompte, Date dataCreation, double solde, Client client, Collection<Operation> operations, double decouvert) {
super(codeCompte, dataCreation, solde, client, operations);
this.decouvert = decouvert;
}
The first constructor of each type only sets one value, while the second calls the super constructor, which set all the values (id included). When you are saving, you are using the first constructor
Compte cp1=compteRep.save(new CompteCourant("c1",new Date(),9000,c1,6000));
Compte cp2=compteRep.save(new CompteEpargne("c2",new Date(),63000,c2,12220));
You are calling the constructor that only sets one value. So you probably need to fix how that those constructors are setting properties. Maybe you want to do something like
public CompteEpargne(String s, Date date, int i, Client c2, double taux) {
this(s, date, i, c2, new ArrayList<Operation>(), taux);
}
where you call the other constructor.
Simple Solution
Your id attribute is not set. This may be due to the fact that the DB field is not set to auto increment.
For MySQL (as you have given in Properties file) use this below sample for defining your POJO class.
#Id #GeneratedValue(strategy = GenerationType.IDENTITY) #Column(name="id", unique=true, nullable=false) public Long getId() { return this.id; }
thanks friends the problem is in the class Compte
#DiscriminatorColumn(name = "TYPE_CPTE,",discriminatorType= DiscriminatorType.STRING,length = 2)
with in the name is ="TYPE_CPTE," hhhh I dont see the comma after TYPE_CPTE
#DiscriminatorColumn(name = "TYPE_CPTE",discriminatorType= DiscriminatorType.STRING,length = 2)

Resources