Popular New Releases in Hibernate
dropwizard
v3.0.0-beta.2
querydsl
5.0.0
jetcache
liquibase
v4.9.1
speedment
3.2.10
Popular Libraries in Hibernate
by dropwizard java
8161 Apache-2.0
A damn simple library for building production-ready RESTful web services.
by thinkgem javascript
7653 Apache-2.0
JeeSite 是一个企业信息化开发基础平台,Java企业应用开源框架,Java EE(J2EE)快速开发框架,使用经典技术组合(Spring、Spring MVC、Apache Shiro、MyBatis、Bootstrap UI),包括核心模块如:组织机构、角色用户、权限授权、数据权限、内容管理、工作流等。
by apache java
5943 Apache-2.0
Apache Tomcat
by hibernate java
4916
Hibernate's core Object/Relational Mapping functionality
by jOOQ java
4882 NOASSERTION
jOOQ is the best way to write SQL in Java
by cloudfavorites html
4376
云收藏 Spring Boot 2.X 开源项目
by zhanglei-workspace java
3965
该项目为多个小项目的集合(持续更新中...)。内容类似淘宝、京东等网购管理系统以及图书管理、超市管理等系统。目的在于便于Java初级爱好者在学习完某一部分Java知识后有一个合适的项目锻炼、运用所学知识,完善知识体系。适用人群:Java基础到入门的爱好者。
by querydsl java
3754 Apache-2.0
Unified Queries for Java
by brianway java
3687
旨在打造在线最佳的 Java 学习笔记,含博客讲解和源码实例,包括 Java SE 和 Java Web
Trending New libraries in Hibernate
by didi java
430 NOASSERTION
AgileTC is an agile test case management platform
by intsmaze java
282 BSD-3-Clause
懒松鼠Flink-Boot 脚手架让Flink全面拥抱Spring生态体系,使得开发者可以以Java WEB开发模式开发出分布式运行的流处理程序,懒松鼠让跨界变得更加简单。懒松鼠旨在让开发者以更底上手成本(不需要理解分布式计算的理论知识和Flink框架的细节)便可以快速编写业务代码实现。为了进一步提升开发者使用懒松鼠脚手架开发大型项目的敏捷的度,该脚手架默认集成Spring框架进行Bean管理,同时将微服务以及WEB开发领域中经常用到的框架集成进来,进一步提升开发速度。比如集成Mybatis ORM框架,Hibernate Validator校验框架,Spring Retry重试框架等,具体见下面的脚手架特性。
by RameshMF javascript
235
Learn how to develop a full-stack CRUD application using React as frontend and spring boot as backend.
by amigoscode java
201
by xzyJavaX java
178
开源项目+个人博客
by user-xiangpeng java
177
妖气山视频管理系统-mysql版
by vanyouseea css
159 MIT
O365管理系统是一个以java语言开发的基于Microsoft Graph Restful API的多全局管理系统,理论上支持任何Office全局的管理(A1,A3,A1P,E3,E5等),你可以很方便的使用它来批量添加,批量删除,批量启用,批量禁用,搜索和查看用户,生成邀请码,邀请朋友注册,提升和收回管理员权限,更新密钥,查看订阅,分配订阅(创新用户时),查看多全局报告
by Urunov javascript
147
Spring Boot, JDBC, ORM, JPA, Hibernate, H2, MySQL, Oracle
by rawchen java
112
学生信息管理系统SIMS,Java Servlet And Jsp.
Top Authors in Hibernate
1
26 Libraries
1051
2
16 Libraries
7583
3
15 Libraries
96
4
15 Libraries
41
5
12 Libraries
112
6
9 Libraries
99
7
9 Libraries
701
8
9 Libraries
779
9
8 Libraries
228
10
8 Libraries
67
1
26 Libraries
1051
2
16 Libraries
7583
3
15 Libraries
96
4
15 Libraries
41
5
12 Libraries
112
6
9 Libraries
99
7
9 Libraries
701
8
9 Libraries
779
9
8 Libraries
228
10
8 Libraries
67
Trending Kits in Hibernate
No Trending Kits are available at this moment for Hibernate
Trending Discussions on Hibernate
Java @Override equals(): When this.getClass() != o.getClass() fails but shouldn't
Hibernate JOIN [some entity] ON unexpected token
Does hibernate set back reference in @OneToMany @ManyToOne relationship automatically?
Java 17: Maven doesn't give much information about the error that happened, why?
What should I replace the hibernate deprecated @TypeDef and @Type annotations by?
JDBC with H2 and MySQL mode: create procedure fails
Hibernate Interceptor not working after upgrading to Hibernate 5
Spring boot applicaiton unable to find SQLite jdbc driver class
Log4j2 deadlock
Invalid DateTimeFormat when inserting date in H2 in memory DB
QUESTION
Java @Override equals(): When this.getClass() != o.getClass() fails but shouldn't
Asked 2022-Apr-17 at 12:25I have this @Override for equals() in my MyClass class:
1public class MyClass extends MySuperClass
2{
3 ...
4 @Override
5 public boolean equals( Object o )
6 {
7 if ( this == o )
8 {
9 return true;
10 }
11 if ( o == null || this.getClass() != o.getClass() )
12 {
13 return false;
14 }
15 if ( !super.equals( o ) )
16 {
17 return false;
18 }
19 MyClass that = ( MyClass ) o;
20 return this.var1.equals( that.var1 ) && this.var2.equals( that.var2 );
21 }
22 ...
23}
24
Pretty standard. Matter of fact, it follows Java best practices.
Later in life I have this in another sub-package class (my controller class):
1public class MyClass extends MySuperClass
2{
3 ...
4 @Override
5 public boolean equals( Object o )
6 {
7 if ( this == o )
8 {
9 return true;
10 }
11 if ( o == null || this.getClass() != o.getClass() )
12 {
13 return false;
14 }
15 if ( !super.equals( o ) )
16 {
17 return false;
18 }
19 MyClass that = ( MyClass ) o;
20 return this.var1.equals( that.var1 ) && this.var2.equals( that.var2 );
21 }
22 ...
23}
24...
25package com.a.b.api.controllers;
26...
27import com.a.b.jpa.models.MyClass;
28...
29MyClass myObject1 = new MyClass( var1, var2 );
30MyClass myObject2 = this.myClassRepository.getById( 1 ); // SpringBoot/Jpa/Hibernate
31
32if ( myObject2.equals( myObject1 ) )
33{
34 ...do something...
35}
36...
37this.myClassRepository.save( myObject1 );
38...
39
My problem is that the .equals() is always failing here:
1public class MyClass extends MySuperClass
2{
3 ...
4 @Override
5 public boolean equals( Object o )
6 {
7 if ( this == o )
8 {
9 return true;
10 }
11 if ( o == null || this.getClass() != o.getClass() )
12 {
13 return false;
14 }
15 if ( !super.equals( o ) )
16 {
17 return false;
18 }
19 MyClass that = ( MyClass ) o;
20 return this.var1.equals( that.var1 ) && this.var2.equals( that.var2 );
21 }
22 ...
23}
24...
25package com.a.b.api.controllers;
26...
27import com.a.b.jpa.models.MyClass;
28...
29MyClass myObject1 = new MyClass( var1, var2 );
30MyClass myObject2 = this.myClassRepository.getById( 1 ); // SpringBoot/Jpa/Hibernate
31
32if ( myObject2.equals( myObject1 ) )
33{
34 ...do something...
35}
36...
37this.myClassRepository.save( myObject1 );
38...
39if ( o == null || this.getClass() != o.getClass() )
40
because java says that this.getClass() and o.getClass() are NOT equal. When I debug the code (in Intellij IDEA 2022.1 UE) I see this:
this.getClass() = MyClass@13706
but
o.getClass = com.a.b.jpa.models.MyClass@8f7462
But they are the same class! Almost every Java book, tutorial, blog, Intellij IDEA, etc. demonstrates the .equals() this way. I have tried this in Ubuntu 20.04.4 LTS java-14-openjdk-amd64 and java-17-openjdk-amd64 with the same results.
What am I doing wrong?
ANSWER
Answered 2022-Apr-14 at 15:31myObject2
is an instance of a proxy class, generated at runtime by Hibernate using Byte Buddy. The generated proxy intercepts all method invocations, that's why getClass()
returns different results.
As an alternative to getClass()
, using instanceof
might be another approach:
1public class MyClass extends MySuperClass
2{
3 ...
4 @Override
5 public boolean equals( Object o )
6 {
7 if ( this == o )
8 {
9 return true;
10 }
11 if ( o == null || this.getClass() != o.getClass() )
12 {
13 return false;
14 }
15 if ( !super.equals( o ) )
16 {
17 return false;
18 }
19 MyClass that = ( MyClass ) o;
20 return this.var1.equals( that.var1 ) && this.var2.equals( that.var2 );
21 }
22 ...
23}
24...
25package com.a.b.api.controllers;
26...
27import com.a.b.jpa.models.MyClass;
28...
29MyClass myObject1 = new MyClass( var1, var2 );
30MyClass myObject2 = this.myClassRepository.getById( 1 ); // SpringBoot/Jpa/Hibernate
31
32if ( myObject2.equals( myObject1 ) )
33{
34 ...do something...
35}
36...
37this.myClassRepository.save( myObject1 );
38...
39if ( o == null || this.getClass() != o.getClass() )
40if ( !(this instanceof MyClass && o instanceof MyClass) )
41{
42 return false;
43}
44
However keep in mind that instanceof
has its drawbacks. It violates the symmetry principle.
You shouldn't compare these objects in the first place, since a new object should be different from a Hibernate managed one that has a persistent state.
QUESTION
Hibernate JOIN [some entity] ON unexpected token
Asked 2022-Apr-02 at 10:11I use Hibernate 5.4.32.Final, when I try to execute this query via spring data:
1@Query("select new some.package.dto.TwoFieldDto(o.gln, u.email) "
2 + "from OrganizationEntity o "
3 + "join UserEntity u on u.organization.id = o.id "
4 + "where o.gln in (:glnList)")
5 List<TwoFieldDto<String, String>> findEmailListByGlnIn(List<String> glnList);
6
On starting application Hibernate throw SyntexException when it reaches to UserEntity token, and gives out unexpected token.
If I try to execute query from the UserEntity side, query compiles successfully. (Yes, I haven't get a link from OrganizationEntity to UserEntity)
Is this Hibernate version not supported JOIN ON syntex? (OrganizationEntity doesn't contain link on UserEntity, but UserEntity has it).
ANSWER
Answered 2022-Apr-02 at 10:11The @Query
annotation expects JPQL by default which has its own syntax. As far as I know, you can not do someting like JOIN .. ON
in JPQL .
I do not know the association between your entities but it should look someting like this:
1@Query("select new some.package.dto.TwoFieldDto(o.gln, u.email) "
2 + "from OrganizationEntity o "
3 + "join UserEntity u on u.organization.id = o.id "
4 + "where o.gln in (:glnList)")
5 List<TwoFieldDto<String, String>> findEmailListByGlnIn(List<String> glnList);
6@Query("select new some.package.TwoFieldDto(o.gln, u.email) "
7 + "from OrganizationEntity o "
8 + "join o.UserEntity u "
9 + "where o.gln in (:glnList)")
10
But for that to work, there has to be an association between OrganizationEntity
and UserEntity
.
As an alternative you can always use a native query, where you could do a JOIN .. ON
in your native SQL dialect:
1@Query("select new some.package.dto.TwoFieldDto(o.gln, u.email) "
2 + "from OrganizationEntity o "
3 + "join UserEntity u on u.organization.id = o.id "
4 + "where o.gln in (:glnList)")
5 List<TwoFieldDto<String, String>> findEmailListByGlnIn(List<String> glnList);
6@Query("select new some.package.TwoFieldDto(o.gln, u.email) "
7 + "from OrganizationEntity o "
8 + "join o.UserEntity u "
9 + "where o.gln in (:glnList)")
10@Query(value = "SELECT ....", nativeQuery = true)
11
But this should only be an option if you are sure that you can not do it with JPQL.
QUESTION
Does hibernate set back reference in @OneToMany @ManyToOne relationship automatically?
Asked 2022-Feb-13 at 16:26I have Order entity that has orderItems
list.
1@OneToMany(mappedBy ="order")
2List<OrderItem> orderItems;
3
OrderItem
has back reference to Order
1@OneToMany(mappedBy ="order")
2List<OrderItem> orderItems;
3@ManyToOne
4Order order;
5
When I save Order
should I manually set backreference in OrderItem
entity?
Like this
1@OneToMany(mappedBy ="order")
2List<OrderItem> orderItems;
3@ManyToOne
4Order order;
5OrderItem orderItem1 = new OrderItem( //constructor );
6OrderItem orderItem2 = new OrderItem( //constructor );
7List orderItems = Arrays.asList(orderItem1, orderItem2);
8Order order = new Order( orderItems);
9
10orderItems.forEach(orderItem -> orderItem.setOrder(order); // like this?
11
Do Hibernate and Spring data jpa set it automatically?
ANSWER
Answered 2022-Feb-13 at 16:26For creating and updating case , they will not help you to set it automatically and you have to configure the relationship by yourself.
The mappedBy
here is to define whether Order.orderItems
or OrderItem.order
is to used to provide the value for the corresponding DB column that link between them. (i.e. order_id
column in order_item
table).
If mappedBy
is defined , OrderItem.order
will be used to provide the value for the relationship. Otherwise , Order.orderItems
will be used.
For the loading case , it will help you to set it automatically.
QUESTION
Java 17: Maven doesn't give much information about the error that happened, why?
Asked 2022-Feb-04 at 20:28I'm upgrading from JDK 8 to JDK 17 and I'm trying to compile with mvn clean install -X -DskipTests
and there's no information about the error.
Btw, I'm updating the dependencies and after that I compile to see if has errors. I need to update some dependencies such as Spring, Hibernate etc. I already updated Lombok.
I added the -X or -e option but I got the same result.
What can I do to get more information about the error? The log shows that it was loading hibernate-jpa-2.1-api before failed... so that means the problem is in this dependency?
1[INFO] [loading /Users/daniela/.m2/repository/org/projectlombok/lombok/1.18.2/lombok-1.18.2.jar(/lombok/AllArgsConstructor$AnyAnnotation.class)]
2[INFO] [loading /Users/daniela/.m2/repository/org/ocpsoft/rewrite/rewrite-config-prettyfaces/2.0.4.Final/rewrite-config-prettyfaces-2.0.4.Final.jar(/com/ocpsoft/pretty/faces/annotation/URLValidator.class)]
3[INFO] [loading /Users/daniela/.m2/repository/javax/servlet/javax.servlet-api/3.1.0/javax.servlet-api-3.1.0.jar(/javax/servlet/annotation/WebInitParam.class)]
4[INFO] [loading /Users/daniela/.m2/repository/org/projectlombok/lombok/1.18.2/lombok-1.18.2.jar(/lombok/RequiredArgsConstructor$AnyAnnotation.class)]
5[INFO] [loading /Users/daniela/.m2/repository/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final.jar(/javax/persistence/PersistenceProperty.class)]
6[INFO] ------------------------------------------------------------------------
7[INFO] Reactor Summary for My App 2.61.0-SNAPSHOT:
8[INFO]
9[INFO] My App ............................. SUCCESS [ 0.005 s]
10[INFO] My App - Webapp .................... FAILURE [ 9.454 s]
11[INFO] ------------------------------------------------------------------------
12[INFO] BUILD FAILURE
13[INFO] ------------------------------------------------------------------------
14[INFO] Total time: 9.555 s
15[INFO] Finished at: 2021-09-21T10:31:24-03:00
16[INFO] ------------------------------------------------------------------------
17[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project myapp-webapp: Compilation failure -> [Help 1]
18org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project myapp-webapp: Compilation failure
19 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
20 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
21 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
22 at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
23 at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
24 at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
25 at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
26 at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
27 at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
28 at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
29 at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
30 at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
31 at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
32 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
33 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77)
34 at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
35 at java.lang.reflect.Method.invoke (Method.java:568)
36 at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
37 at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
38 at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
39 at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
40Caused by: org.apache.maven.plugin.compiler.CompilationFailureException: Compilation failure
41 at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute (AbstractCompilerMojo.java:1224)
42 at org.apache.maven.plugin.compiler.CompilerMojo.execute (CompilerMojo.java:187)
43 at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
44 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
45 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
46 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
47 at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
48 at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
49 at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
50 at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
51 at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
52 at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
53 at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
54 at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
55 at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
56 at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
57 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
58 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77)
59 at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
60 at java.lang.reflect.Method.invoke (Method.java:568)
61 at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
62 at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
63 at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
64 at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
65[ERROR]
66[ERROR]
67[ERROR] For more information about the errors and possible solutions, please read the following articles:
68[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
69[ERROR]
70[ERROR] After correcting the problems, you can resume the build with the command
71[ERROR] mvn <args> -rf :myapp-webapp
72
pom.xml (Parent)
1[INFO] [loading /Users/daniela/.m2/repository/org/projectlombok/lombok/1.18.2/lombok-1.18.2.jar(/lombok/AllArgsConstructor$AnyAnnotation.class)]
2[INFO] [loading /Users/daniela/.m2/repository/org/ocpsoft/rewrite/rewrite-config-prettyfaces/2.0.4.Final/rewrite-config-prettyfaces-2.0.4.Final.jar(/com/ocpsoft/pretty/faces/annotation/URLValidator.class)]
3[INFO] [loading /Users/daniela/.m2/repository/javax/servlet/javax.servlet-api/3.1.0/javax.servlet-api-3.1.0.jar(/javax/servlet/annotation/WebInitParam.class)]
4[INFO] [loading /Users/daniela/.m2/repository/org/projectlombok/lombok/1.18.2/lombok-1.18.2.jar(/lombok/RequiredArgsConstructor$AnyAnnotation.class)]
5[INFO] [loading /Users/daniela/.m2/repository/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final.jar(/javax/persistence/PersistenceProperty.class)]
6[INFO] ------------------------------------------------------------------------
7[INFO] Reactor Summary for My App 2.61.0-SNAPSHOT:
8[INFO]
9[INFO] My App ............................. SUCCESS [ 0.005 s]
10[INFO] My App - Webapp .................... FAILURE [ 9.454 s]
11[INFO] ------------------------------------------------------------------------
12[INFO] BUILD FAILURE
13[INFO] ------------------------------------------------------------------------
14[INFO] Total time: 9.555 s
15[INFO] Finished at: 2021-09-21T10:31:24-03:00
16[INFO] ------------------------------------------------------------------------
17[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project myapp-webapp: Compilation failure -> [Help 1]
18org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project myapp-webapp: Compilation failure
19 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
20 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
21 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
22 at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
23 at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
24 at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
25 at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
26 at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
27 at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
28 at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
29 at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
30 at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
31 at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
32 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
33 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77)
34 at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
35 at java.lang.reflect.Method.invoke (Method.java:568)
36 at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
37 at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
38 at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
39 at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
40Caused by: org.apache.maven.plugin.compiler.CompilationFailureException: Compilation failure
41 at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute (AbstractCompilerMojo.java:1224)
42 at org.apache.maven.plugin.compiler.CompilerMojo.execute (CompilerMojo.java:187)
43 at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
44 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
45 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
46 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
47 at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
48 at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
49 at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
50 at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
51 at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
52 at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
53 at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
54 at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
55 at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
56 at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
57 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
58 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77)
59 at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
60 at java.lang.reflect.Method.invoke (Method.java:568)
61 at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
62 at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
63 at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
64 at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
65[ERROR]
66[ERROR]
67[ERROR] For more information about the errors and possible solutions, please read the following articles:
68[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
69[ERROR]
70[ERROR] After correcting the problems, you can resume the build with the command
71[ERROR] mvn <args> -rf :myapp-webapp
72<properties>
73
74 <!-- Generic properties -->
75 <java.version>17</java.version>
76 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
77 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
78
79 <!-- Java EE / Java SE dependencies -->
80 <jsp.version>2.2</jsp.version>
81 <jstl.version>1.2</jstl.version>
82 <servlet.version>3.1.0</servlet.version>
83 <javax-el.version>3.0.0</javax-el.version>
84 <jaxb-impl.version>2.2.7-b63</jaxb-impl.version>
85
86 <!-- Other dependencies such as Spring, Hibernate etc -->
87
88 <maven.compiler.source>17</maven.compiler.source>
89 <maven.compiler.target>17</maven.compiler.target>
90</properties>
91
92<build>
93
94 <pluginManagement>
95
96 <plugins>
97 <plugin>
98 <groupId>org.apache.maven.plugins</groupId>
99 <artifactId>maven-compiler-plugin</artifactId>
100 <version>3.8.1</version>
101 <configuration>
102 <annotationProcessorPaths>
103 <path>
104 <groupId>org.projectlombok</groupId>
105 <artifactId>lombok</artifactId>
106 <version>${lombok.version}</version>
107 </path>
108 </annotationProcessorPaths>
109 <compilerArguments>
110 <verbose />
111 <Xlint />
112 </compilerArguments>
113 <fork>true</fork>
114 <verbose>true</verbose>
115 <source>17</source>
116 <target>17</target>
117 <showWarnings>true</showWarnings>
118 <compilerVersion>17</compilerVersion>
119 <debug>true</debug>
120 </configuration>
121 </plugin>
122
123 <plugin>
124 <groupId>org.apache.maven.plugins</groupId>
125 <artifactId>maven-war-plugin</artifactId>
126 <version>2.4</version>
127 <configuration>
128 <warName>${project.build.finalName}</warName>
129 </configuration>
130 </plugin>
131
132 <plugin>
133 <groupId>org.apache.maven.plugins</groupId>
134 <artifactId>maven-release-plugin</artifactId>
135 <version>2.5</version>
136 <dependencies>
137 <dependency>
138 <groupId>org.apache.maven.scm</groupId>
139 <artifactId>maven-scm-provider-gitexe</artifactId>
140 <version>1.9.2</version>
141 </dependency>
142 </dependencies>
143 <configuration>
144 <arguments>-Dbuild-env=${build-env}</arguments>
145 </configuration>
146 </plugin>
147
148 <plugin>
149 <groupId>org.apache.maven.plugins</groupId>
150 <artifactId>maven-javadoc-plugin</artifactId>
151 <version>2.9</version>
152 <configuration>
153 <skip>true</skip>
154 </configuration>
155 </plugin>
156
157 <plugin>
158 <artifactId>maven-clean-plugin</artifactId>
159 <version>2.6.1</version>
160 </plugin>
161
162 <plugin>
163 <artifactId>maven-resources-plugin</artifactId>
164 <version>2.7</version>
165 <executions>
166 <execution>
167 <id>copy-resources</id>
168 <phase>validate</phase>
169 <goals>
170 <goal>copy-resources</goal>
171 </goals>
172 <configuration>
173 <outputDirectory>${project.build.outputDirectory}/com/my/app/bundle</outputDirectory>
174 <resources>
175 <resource>
176 <directory>src/main/resources/my/app/bundle</directory>
177 <filtering>true</filtering>
178 </resource>
179 </resources>
180 </configuration>
181 </execution>
182 </executions>
183 </plugin>
184
185 <plugin>
186 <groupId>org.apache.maven.plugins</groupId>
187 <artifactId>maven-site-plugin</artifactId>
188 <version>3.9.1</version>
189 </plugin>
190
191 <plugin>
192 <groupId>org.apache.maven.plugins</groupId>
193 <artifactId>maven-project-info-reports-plugin</artifactId>
194 <version>3.1.2</version>
195 </plugin>
196 </plugins>
197
198 </pluginManagement>
199 <plugins>
200 <plugin>
201 <groupId>org.apache.maven.plugins</groupId>
202 <artifactId>maven-compiler-plugin</artifactId>
203 </plugin>
204
205 </plugins>
206
207 </build>
208
pom.xml (Child)
1[INFO] [loading /Users/daniela/.m2/repository/org/projectlombok/lombok/1.18.2/lombok-1.18.2.jar(/lombok/AllArgsConstructor$AnyAnnotation.class)]
2[INFO] [loading /Users/daniela/.m2/repository/org/ocpsoft/rewrite/rewrite-config-prettyfaces/2.0.4.Final/rewrite-config-prettyfaces-2.0.4.Final.jar(/com/ocpsoft/pretty/faces/annotation/URLValidator.class)]
3[INFO] [loading /Users/daniela/.m2/repository/javax/servlet/javax.servlet-api/3.1.0/javax.servlet-api-3.1.0.jar(/javax/servlet/annotation/WebInitParam.class)]
4[INFO] [loading /Users/daniela/.m2/repository/org/projectlombok/lombok/1.18.2/lombok-1.18.2.jar(/lombok/RequiredArgsConstructor$AnyAnnotation.class)]
5[INFO] [loading /Users/daniela/.m2/repository/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final.jar(/javax/persistence/PersistenceProperty.class)]
6[INFO] ------------------------------------------------------------------------
7[INFO] Reactor Summary for My App 2.61.0-SNAPSHOT:
8[INFO]
9[INFO] My App ............................. SUCCESS [ 0.005 s]
10[INFO] My App - Webapp .................... FAILURE [ 9.454 s]
11[INFO] ------------------------------------------------------------------------
12[INFO] BUILD FAILURE
13[INFO] ------------------------------------------------------------------------
14[INFO] Total time: 9.555 s
15[INFO] Finished at: 2021-09-21T10:31:24-03:00
16[INFO] ------------------------------------------------------------------------
17[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project myapp-webapp: Compilation failure -> [Help 1]
18org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project myapp-webapp: Compilation failure
19 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
20 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
21 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
22 at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
23 at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
24 at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
25 at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
26 at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
27 at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
28 at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
29 at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
30 at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
31 at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
32 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
33 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77)
34 at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
35 at java.lang.reflect.Method.invoke (Method.java:568)
36 at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
37 at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
38 at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
39 at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
40Caused by: org.apache.maven.plugin.compiler.CompilationFailureException: Compilation failure
41 at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute (AbstractCompilerMojo.java:1224)
42 at org.apache.maven.plugin.compiler.CompilerMojo.execute (CompilerMojo.java:187)
43 at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
44 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
45 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
46 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
47 at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
48 at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
49 at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
50 at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
51 at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
52 at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
53 at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
54 at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
55 at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
56 at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
57 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
58 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77)
59 at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
60 at java.lang.reflect.Method.invoke (Method.java:568)
61 at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
62 at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
63 at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
64 at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
65[ERROR]
66[ERROR]
67[ERROR] For more information about the errors and possible solutions, please read the following articles:
68[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
69[ERROR]
70[ERROR] After correcting the problems, you can resume the build with the command
71[ERROR] mvn <args> -rf :myapp-webapp
72<properties>
73
74 <!-- Generic properties -->
75 <java.version>17</java.version>
76 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
77 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
78
79 <!-- Java EE / Java SE dependencies -->
80 <jsp.version>2.2</jsp.version>
81 <jstl.version>1.2</jstl.version>
82 <servlet.version>3.1.0</servlet.version>
83 <javax-el.version>3.0.0</javax-el.version>
84 <jaxb-impl.version>2.2.7-b63</jaxb-impl.version>
85
86 <!-- Other dependencies such as Spring, Hibernate etc -->
87
88 <maven.compiler.source>17</maven.compiler.source>
89 <maven.compiler.target>17</maven.compiler.target>
90</properties>
91
92<build>
93
94 <pluginManagement>
95
96 <plugins>
97 <plugin>
98 <groupId>org.apache.maven.plugins</groupId>
99 <artifactId>maven-compiler-plugin</artifactId>
100 <version>3.8.1</version>
101 <configuration>
102 <annotationProcessorPaths>
103 <path>
104 <groupId>org.projectlombok</groupId>
105 <artifactId>lombok</artifactId>
106 <version>${lombok.version}</version>
107 </path>
108 </annotationProcessorPaths>
109 <compilerArguments>
110 <verbose />
111 <Xlint />
112 </compilerArguments>
113 <fork>true</fork>
114 <verbose>true</verbose>
115 <source>17</source>
116 <target>17</target>
117 <showWarnings>true</showWarnings>
118 <compilerVersion>17</compilerVersion>
119 <debug>true</debug>
120 </configuration>
121 </plugin>
122
123 <plugin>
124 <groupId>org.apache.maven.plugins</groupId>
125 <artifactId>maven-war-plugin</artifactId>
126 <version>2.4</version>
127 <configuration>
128 <warName>${project.build.finalName}</warName>
129 </configuration>
130 </plugin>
131
132 <plugin>
133 <groupId>org.apache.maven.plugins</groupId>
134 <artifactId>maven-release-plugin</artifactId>
135 <version>2.5</version>
136 <dependencies>
137 <dependency>
138 <groupId>org.apache.maven.scm</groupId>
139 <artifactId>maven-scm-provider-gitexe</artifactId>
140 <version>1.9.2</version>
141 </dependency>
142 </dependencies>
143 <configuration>
144 <arguments>-Dbuild-env=${build-env}</arguments>
145 </configuration>
146 </plugin>
147
148 <plugin>
149 <groupId>org.apache.maven.plugins</groupId>
150 <artifactId>maven-javadoc-plugin</artifactId>
151 <version>2.9</version>
152 <configuration>
153 <skip>true</skip>
154 </configuration>
155 </plugin>
156
157 <plugin>
158 <artifactId>maven-clean-plugin</artifactId>
159 <version>2.6.1</version>
160 </plugin>
161
162 <plugin>
163 <artifactId>maven-resources-plugin</artifactId>
164 <version>2.7</version>
165 <executions>
166 <execution>
167 <id>copy-resources</id>
168 <phase>validate</phase>
169 <goals>
170 <goal>copy-resources</goal>
171 </goals>
172 <configuration>
173 <outputDirectory>${project.build.outputDirectory}/com/my/app/bundle</outputDirectory>
174 <resources>
175 <resource>
176 <directory>src/main/resources/my/app/bundle</directory>
177 <filtering>true</filtering>
178 </resource>
179 </resources>
180 </configuration>
181 </execution>
182 </executions>
183 </plugin>
184
185 <plugin>
186 <groupId>org.apache.maven.plugins</groupId>
187 <artifactId>maven-site-plugin</artifactId>
188 <version>3.9.1</version>
189 </plugin>
190
191 <plugin>
192 <groupId>org.apache.maven.plugins</groupId>
193 <artifactId>maven-project-info-reports-plugin</artifactId>
194 <version>3.1.2</version>
195 </plugin>
196 </plugins>
197
198 </pluginManagement>
199 <plugins>
200 <plugin>
201 <groupId>org.apache.maven.plugins</groupId>
202 <artifactId>maven-compiler-plugin</artifactId>
203 </plugin>
204
205 </plugins>
206
207 </build>
208<properties>
209 <java.version>17</java.version>
210
211 <maven.compiler.source>17</maven.compiler.source>
212 <maven.compiler.target>17</maven.compiler.target>
213</properties>
214
215<profiles>
216 <profile>
217 <id>dev</id>
218 <activation>
219 <activeByDefault>true</activeByDefault>
220 </activation>
221
222 <build>
223 <finalName>myapp</finalName>
224 <plugins>
225
226 <plugin>
227 <groupId>org.apache.maven.plugins</groupId>
228 <artifactId>maven-war-plugin</artifactId>
229 </plugin>
230
231 <plugin>
232 <groupId>org.apache.maven.plugins</groupId>
233 <artifactId>maven-surefire-plugin</artifactId>
234 <configuration>
235 <includes>
236 <include>**/*IT.java</include>
237 </includes>
238 </configuration>
239 <version>2.18.1</version>
240 </plugin>
241
242 <plugin>
243 <groupId>org.apache.maven.plugins</groupId>
244 <artifactId>maven-compiler-plugin</artifactId>
245 <inherited>true</inherited>
246 </plugin>
247
248 <plugin>
249 <groupId>org.apache.maven.plugins</groupId>
250 <artifactId>maven-dependency-plugin</artifactId>
251 </plugin>
252 <plugin>
253 <artifactId>maven-release-plugin</artifactId>
254 </plugin>
255 <plugin>
256 <groupId>org.apache.maven.plugins</groupId>
257 <artifactId>maven-site-plugin</artifactId>
258 </plugin>
259 <plugin>
260 <groupId>org.apache.maven.plugins</groupId>
261 <artifactId>maven-project-info-reports-plugin</artifactId>
262 </plugin>
263 </plugins>
264 </build>
265 </profile>
266</profile>
267
Java and mvn version
1[INFO] [loading /Users/daniela/.m2/repository/org/projectlombok/lombok/1.18.2/lombok-1.18.2.jar(/lombok/AllArgsConstructor$AnyAnnotation.class)]
2[INFO] [loading /Users/daniela/.m2/repository/org/ocpsoft/rewrite/rewrite-config-prettyfaces/2.0.4.Final/rewrite-config-prettyfaces-2.0.4.Final.jar(/com/ocpsoft/pretty/faces/annotation/URLValidator.class)]
3[INFO] [loading /Users/daniela/.m2/repository/javax/servlet/javax.servlet-api/3.1.0/javax.servlet-api-3.1.0.jar(/javax/servlet/annotation/WebInitParam.class)]
4[INFO] [loading /Users/daniela/.m2/repository/org/projectlombok/lombok/1.18.2/lombok-1.18.2.jar(/lombok/RequiredArgsConstructor$AnyAnnotation.class)]
5[INFO] [loading /Users/daniela/.m2/repository/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final.jar(/javax/persistence/PersistenceProperty.class)]
6[INFO] ------------------------------------------------------------------------
7[INFO] Reactor Summary for My App 2.61.0-SNAPSHOT:
8[INFO]
9[INFO] My App ............................. SUCCESS [ 0.005 s]
10[INFO] My App - Webapp .................... FAILURE [ 9.454 s]
11[INFO] ------------------------------------------------------------------------
12[INFO] BUILD FAILURE
13[INFO] ------------------------------------------------------------------------
14[INFO] Total time: 9.555 s
15[INFO] Finished at: 2021-09-21T10:31:24-03:00
16[INFO] ------------------------------------------------------------------------
17[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project myapp-webapp: Compilation failure -> [Help 1]
18org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project myapp-webapp: Compilation failure
19 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
20 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
21 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
22 at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
23 at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
24 at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
25 at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
26 at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
27 at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
28 at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
29 at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
30 at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
31 at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
32 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
33 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77)
34 at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
35 at java.lang.reflect.Method.invoke (Method.java:568)
36 at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
37 at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
38 at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
39 at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
40Caused by: org.apache.maven.plugin.compiler.CompilationFailureException: Compilation failure
41 at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute (AbstractCompilerMojo.java:1224)
42 at org.apache.maven.plugin.compiler.CompilerMojo.execute (CompilerMojo.java:187)
43 at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
44 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
45 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
46 at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
47 at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
48 at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
49 at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
50 at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
51 at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
52 at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
53 at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
54 at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
55 at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
56 at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
57 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
58 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77)
59 at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
60 at java.lang.reflect.Method.invoke (Method.java:568)
61 at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
62 at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
63 at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
64 at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
65[ERROR]
66[ERROR]
67[ERROR] For more information about the errors and possible solutions, please read the following articles:
68[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
69[ERROR]
70[ERROR] After correcting the problems, you can resume the build with the command
71[ERROR] mvn <args> -rf :myapp-webapp
72<properties>
73
74 <!-- Generic properties -->
75 <java.version>17</java.version>
76 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
77 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
78
79 <!-- Java EE / Java SE dependencies -->
80 <jsp.version>2.2</jsp.version>
81 <jstl.version>1.2</jstl.version>
82 <servlet.version>3.1.0</servlet.version>
83 <javax-el.version>3.0.0</javax-el.version>
84 <jaxb-impl.version>2.2.7-b63</jaxb-impl.version>
85
86 <!-- Other dependencies such as Spring, Hibernate etc -->
87
88 <maven.compiler.source>17</maven.compiler.source>
89 <maven.compiler.target>17</maven.compiler.target>
90</properties>
91
92<build>
93
94 <pluginManagement>
95
96 <plugins>
97 <plugin>
98 <groupId>org.apache.maven.plugins</groupId>
99 <artifactId>maven-compiler-plugin</artifactId>
100 <version>3.8.1</version>
101 <configuration>
102 <annotationProcessorPaths>
103 <path>
104 <groupId>org.projectlombok</groupId>
105 <artifactId>lombok</artifactId>
106 <version>${lombok.version}</version>
107 </path>
108 </annotationProcessorPaths>
109 <compilerArguments>
110 <verbose />
111 <Xlint />
112 </compilerArguments>
113 <fork>true</fork>
114 <verbose>true</verbose>
115 <source>17</source>
116 <target>17</target>
117 <showWarnings>true</showWarnings>
118 <compilerVersion>17</compilerVersion>
119 <debug>true</debug>
120 </configuration>
121 </plugin>
122
123 <plugin>
124 <groupId>org.apache.maven.plugins</groupId>
125 <artifactId>maven-war-plugin</artifactId>
126 <version>2.4</version>
127 <configuration>
128 <warName>${project.build.finalName}</warName>
129 </configuration>
130 </plugin>
131
132 <plugin>
133 <groupId>org.apache.maven.plugins</groupId>
134 <artifactId>maven-release-plugin</artifactId>
135 <version>2.5</version>
136 <dependencies>
137 <dependency>
138 <groupId>org.apache.maven.scm</groupId>
139 <artifactId>maven-scm-provider-gitexe</artifactId>
140 <version>1.9.2</version>
141 </dependency>
142 </dependencies>
143 <configuration>
144 <arguments>-Dbuild-env=${build-env}</arguments>
145 </configuration>
146 </plugin>
147
148 <plugin>
149 <groupId>org.apache.maven.plugins</groupId>
150 <artifactId>maven-javadoc-plugin</artifactId>
151 <version>2.9</version>
152 <configuration>
153 <skip>true</skip>
154 </configuration>
155 </plugin>
156
157 <plugin>
158 <artifactId>maven-clean-plugin</artifactId>
159 <version>2.6.1</version>
160 </plugin>
161
162 <plugin>
163 <artifactId>maven-resources-plugin</artifactId>
164 <version>2.7</version>
165 <executions>
166 <execution>
167 <id>copy-resources</id>
168 <phase>validate</phase>
169 <goals>
170 <goal>copy-resources</goal>
171 </goals>
172 <configuration>
173 <outputDirectory>${project.build.outputDirectory}/com/my/app/bundle</outputDirectory>
174 <resources>
175 <resource>
176 <directory>src/main/resources/my/app/bundle</directory>
177 <filtering>true</filtering>
178 </resource>
179 </resources>
180 </configuration>
181 </execution>
182 </executions>
183 </plugin>
184
185 <plugin>
186 <groupId>org.apache.maven.plugins</groupId>
187 <artifactId>maven-site-plugin</artifactId>
188 <version>3.9.1</version>
189 </plugin>
190
191 <plugin>
192 <groupId>org.apache.maven.plugins</groupId>
193 <artifactId>maven-project-info-reports-plugin</artifactId>
194 <version>3.1.2</version>
195 </plugin>
196 </plugins>
197
198 </pluginManagement>
199 <plugins>
200 <plugin>
201 <groupId>org.apache.maven.plugins</groupId>
202 <artifactId>maven-compiler-plugin</artifactId>
203 </plugin>
204
205 </plugins>
206
207 </build>
208<properties>
209 <java.version>17</java.version>
210
211 <maven.compiler.source>17</maven.compiler.source>
212 <maven.compiler.target>17</maven.compiler.target>
213</properties>
214
215<profiles>
216 <profile>
217 <id>dev</id>
218 <activation>
219 <activeByDefault>true</activeByDefault>
220 </activation>
221
222 <build>
223 <finalName>myapp</finalName>
224 <plugins>
225
226 <plugin>
227 <groupId>org.apache.maven.plugins</groupId>
228 <artifactId>maven-war-plugin</artifactId>
229 </plugin>
230
231 <plugin>
232 <groupId>org.apache.maven.plugins</groupId>
233 <artifactId>maven-surefire-plugin</artifactId>
234 <configuration>
235 <includes>
236 <include>**/*IT.java</include>
237 </includes>
238 </configuration>
239 <version>2.18.1</version>
240 </plugin>
241
242 <plugin>
243 <groupId>org.apache.maven.plugins</groupId>
244 <artifactId>maven-compiler-plugin</artifactId>
245 <inherited>true</inherited>
246 </plugin>
247
248 <plugin>
249 <groupId>org.apache.maven.plugins</groupId>
250 <artifactId>maven-dependency-plugin</artifactId>
251 </plugin>
252 <plugin>
253 <artifactId>maven-release-plugin</artifactId>
254 </plugin>
255 <plugin>
256 <groupId>org.apache.maven.plugins</groupId>
257 <artifactId>maven-site-plugin</artifactId>
258 </plugin>
259 <plugin>
260 <groupId>org.apache.maven.plugins</groupId>
261 <artifactId>maven-project-info-reports-plugin</artifactId>
262 </plugin>
263 </plugins>
264 </build>
265 </profile>
266</profile>
267daniela@Danielas-Macbook ~> javac -version
268javac 17
269daniela@Danielas-Macbook ~> mvn --version
270Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
271Maven home: /usr/local/Cellar/maven/3.6.3_1/libexec
272Java version: 17
273
I changed the java version in maven to execute with JDK 8 and JDK 11 and there's no error: BUILD SUCCESS. I got the error in JDK 16 and 17.
ANSWER
Answered 2021-Oct-19 at 20:28This failure is likely due to an issue between java 17 and older lombok versions. Building with java 17.0.1, lombok 1.18.20 and maven 3.8.1 caused a vague "Compilation failure" for me as well. I upgraded to maven 3.8.3 which also failed but provided this detail on the failure:
java.lang.NullPointerException: Cannot read field "bindingsWhenTrue" because "currentBindings" is null
Searching for this failure message I found this issue on stackoverflow leading me to a bug in lombok. I upgraded to lombok 1.18.22 and that fixed the compilation failure for a successful build.
QUESTION
What should I replace the hibernate deprecated @TypeDef and @Type annotations by?
Asked 2022-Jan-18 at 14:13I've just upgraded the version I use for Hibernate to 5.6.1 and it seems it's now deprecating some Type-related annotations:
1@TypeDef(name = "json", typeClass = JsonBinaryType::class)
2
3
4@Type(type = "json")
5
I found no documentation as to what to do except that
6.0 will introduce a new series of type-safe annotations to serve the same purpose
Our quality guidelines forces us to try and solve every warning and as such I would like to replace these annotations by a non deprecated use.
ANSWER
Answered 2022-Jan-18 at 14:13It seems there is no replacement until Hibernate 6. Type and also TypeDef was marked as deprecated to mark it as removed in version 6, but so far not replacement exists. The ideology here is that deprecated does not indicate that already a new version exists, which might be not an intuitive meaning for most developers.
This was reverted now in the current 5.6.3-Final version series.
QUESTION
JDBC with H2 and MySQL mode: create procedure fails
Asked 2022-Jan-06 at 14:53I try to to store Java object locally database without use external database. For this I use JDBC with H2 via Hibernate :
1 /**
2 * @param connection the connection to set
3 */
4 public static void setConnectionHibernate() {
5 Properties connectionProps = new Properties();
6 connectionProps.put("user", "sa");
7 try {
8 Class.forName("org.h2.Driver");
9 } catch (ClassNotFoundException e) {
10 e.printStackTrace();
11 }
12 url = "jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MODE=MySQL;";
13 }
14
I store the PROCEDURE in String with this code :
1 /**
2 * @param connection the connection to set
3 */
4 public static void setConnectionHibernate() {
5 Properties connectionProps = new Properties();
6 connectionProps.put("user", "sa");
7 try {
8 Class.forName("org.h2.Driver");
9 } catch (ClassNotFoundException e) {
10 e.printStackTrace();
11 }
12 url = "jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MODE=MySQL;";
13 }
14 static final String CREATE_PROCEDURE_INITPSEUDOS = "CREATE OR REPLACE PROCEDURE init_pseudos (MaxPseudo INT) BEGIN WHILE MaxPseudo >= 0 DO"
15 +
16 " INSERT INTO Pseudos (indexPseudo)" +
17 " VALUES (MaxPseudo);" +
18 " SET MaxPseudo = MaxPseudo - 1;" +
19 " END WHILE;" +
20 " END init_pseudos;";
21
And I execute the statement with this code :
1 /**
2 * @param connection the connection to set
3 */
4 public static void setConnectionHibernate() {
5 Properties connectionProps = new Properties();
6 connectionProps.put("user", "sa");
7 try {
8 Class.forName("org.h2.Driver");
9 } catch (ClassNotFoundException e) {
10 e.printStackTrace();
11 }
12 url = "jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MODE=MySQL;";
13 }
14 static final String CREATE_PROCEDURE_INITPSEUDOS = "CREATE OR REPLACE PROCEDURE init_pseudos (MaxPseudo INT) BEGIN WHILE MaxPseudo >= 0 DO"
15 +
16 " INSERT INTO Pseudos (indexPseudo)" +
17 " VALUES (MaxPseudo);" +
18 " SET MaxPseudo = MaxPseudo - 1;" +
19 " END WHILE;" +
20 " END init_pseudos;";
21 public static void initBaseDonneePseudos() {
22 try (Connection connection = DriverManager.getConnection(url, connectionProps);
23 Statement stmt = connection.createStatement()) {
24 stmt.execute(RequetesSQL.CREATE_TABLE_PSEUDOS);
25 stmt.execute(RequetesSQL.CREATE_PROCEDURE_INITPSEUDOS);
26 stmt.execute(RequetesSQL.CREATE_FUNCTION_RECUPEREPSEUDO);
27 stmt.execute(RequetesSQL.INIT_TABLE_PSEUDOS);
28 } catch (SQLException e) {
29 e.printStackTrace();
30 }
31 }
32
I execute this test to test statement :
1 /**
2 * @param connection the connection to set
3 */
4 public static void setConnectionHibernate() {
5 Properties connectionProps = new Properties();
6 connectionProps.put("user", "sa");
7 try {
8 Class.forName("org.h2.Driver");
9 } catch (ClassNotFoundException e) {
10 e.printStackTrace();
11 }
12 url = "jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MODE=MySQL;";
13 }
14 static final String CREATE_PROCEDURE_INITPSEUDOS = "CREATE OR REPLACE PROCEDURE init_pseudos (MaxPseudo INT) BEGIN WHILE MaxPseudo >= 0 DO"
15 +
16 " INSERT INTO Pseudos (indexPseudo)" +
17 " VALUES (MaxPseudo);" +
18 " SET MaxPseudo = MaxPseudo - 1;" +
19 " END WHILE;" +
20 " END init_pseudos;";
21 public static void initBaseDonneePseudos() {
22 try (Connection connection = DriverManager.getConnection(url, connectionProps);
23 Statement stmt = connection.createStatement()) {
24 stmt.execute(RequetesSQL.CREATE_TABLE_PSEUDOS);
25 stmt.execute(RequetesSQL.CREATE_PROCEDURE_INITPSEUDOS);
26 stmt.execute(RequetesSQL.CREATE_FUNCTION_RECUPEREPSEUDO);
27 stmt.execute(RequetesSQL.INIT_TABLE_PSEUDOS);
28 } catch (SQLException e) {
29 e.printStackTrace();
30 }
31 }
32 @Nested
33 class BaseDonneeInteractionTest {
34
35 @BeforeEach
36 public void setUp() {
37 BaseDonnee.setConnectionHibernate();
38 }
39
40 @Test
41 void testInitBaseDonnee() {
42 assertDoesNotThrow(() -> BaseDonnee.initBaseDonneePseudos());
43 }
44
45 }
46
But I obtain this error
I didn't find the problem of the query, anybody have the solution to solve this ?
ANSWER
Answered 2022-Jan-06 at 14:53The problem is that in H2 there are not explicit procedures or functions as you are trying defining.
For that purpose, H2 allows you to create used defined functions instead. Please, consider reed the appropriate documentation.
Basically, you create a user defined function by declaring an ALIAS
for a bunch of Java code.
For example, in your use case, your CREATE_PROCEDURE_INITPSEUDOS
could look similar to this:
1 /**
2 * @param connection the connection to set
3 */
4 public static void setConnectionHibernate() {
5 Properties connectionProps = new Properties();
6 connectionProps.put("user", "sa");
7 try {
8 Class.forName("org.h2.Driver");
9 } catch (ClassNotFoundException e) {
10 e.printStackTrace();
11 }
12 url = "jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MODE=MySQL;";
13 }
14 static final String CREATE_PROCEDURE_INITPSEUDOS = "CREATE OR REPLACE PROCEDURE init_pseudos (MaxPseudo INT) BEGIN WHILE MaxPseudo >= 0 DO"
15 +
16 " INSERT INTO Pseudos (indexPseudo)" +
17 " VALUES (MaxPseudo);" +
18 " SET MaxPseudo = MaxPseudo - 1;" +
19 " END WHILE;" +
20 " END init_pseudos;";
21 public static void initBaseDonneePseudos() {
22 try (Connection connection = DriverManager.getConnection(url, connectionProps);
23 Statement stmt = connection.createStatement()) {
24 stmt.execute(RequetesSQL.CREATE_TABLE_PSEUDOS);
25 stmt.execute(RequetesSQL.CREATE_PROCEDURE_INITPSEUDOS);
26 stmt.execute(RequetesSQL.CREATE_FUNCTION_RECUPEREPSEUDO);
27 stmt.execute(RequetesSQL.INIT_TABLE_PSEUDOS);
28 } catch (SQLException e) {
29 e.printStackTrace();
30 }
31 }
32 @Nested
33 class BaseDonneeInteractionTest {
34
35 @BeforeEach
36 public void setUp() {
37 BaseDonnee.setConnectionHibernate();
38 }
39
40 @Test
41 void testInitBaseDonnee() {
42 assertDoesNotThrow(() -> BaseDonnee.initBaseDonneePseudos());
43 }
44
45 }
46CREATE ALIAS INIT_PSEUDOS AS $$
47import java.sql.Connection;
48import java.sql.Statement;
49import java.sql.SQLException;
50@CODE
51void init_pseudos(final Connection conn, final int maxPseudo) throws SQLException {
52 try (Statement stmt = conn.createStatement()) {
53 while (maxPseudo >= 0) do {
54 stmt.execute("INSERT INTO Pseudos (indexPseudo) VALUES (MaxPseudo);");
55 maxPseudo = maxPseudo - 1;
56 }
57 }
58}
59$$;
60
Note the following:
- As I said, you define a user defined function as Java code. That Java code should be enclosed between two
$$
delimiters. - Although I included explicitly some imports, you can use any class in the
java.util
orjava.sql
packages in your code. If you want to included explicitly some imports, or if you require classes from other packages than the mentioned, the corresponding imports should be provided right after the first$$
token. In addition, you need to include@CODE
the signal H2 where your imports end and your actual Java method starts. - If you need a reference to a
Connection
to the database in your code, it should be the first argument of your method. - Prefer to raise and not hide exceptions: it will allow your transactions to be committed or rollbacked as a whole appropriately.
You can invoke such a function as usual:
1 /**
2 * @param connection the connection to set
3 */
4 public static void setConnectionHibernate() {
5 Properties connectionProps = new Properties();
6 connectionProps.put("user", "sa");
7 try {
8 Class.forName("org.h2.Driver");
9 } catch (ClassNotFoundException e) {
10 e.printStackTrace();
11 }
12 url = "jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MODE=MySQL;";
13 }
14 static final String CREATE_PROCEDURE_INITPSEUDOS = "CREATE OR REPLACE PROCEDURE init_pseudos (MaxPseudo INT) BEGIN WHILE MaxPseudo >= 0 DO"
15 +
16 " INSERT INTO Pseudos (indexPseudo)" +
17 " VALUES (MaxPseudo);" +
18 " SET MaxPseudo = MaxPseudo - 1;" +
19 " END WHILE;" +
20 " END init_pseudos;";
21 public static void initBaseDonneePseudos() {
22 try (Connection connection = DriverManager.getConnection(url, connectionProps);
23 Statement stmt = connection.createStatement()) {
24 stmt.execute(RequetesSQL.CREATE_TABLE_PSEUDOS);
25 stmt.execute(RequetesSQL.CREATE_PROCEDURE_INITPSEUDOS);
26 stmt.execute(RequetesSQL.CREATE_FUNCTION_RECUPEREPSEUDO);
27 stmt.execute(RequetesSQL.INIT_TABLE_PSEUDOS);
28 } catch (SQLException e) {
29 e.printStackTrace();
30 }
31 }
32 @Nested
33 class BaseDonneeInteractionTest {
34
35 @BeforeEach
36 public void setUp() {
37 BaseDonnee.setConnectionHibernate();
38 }
39
40 @Test
41 void testInitBaseDonnee() {
42 assertDoesNotThrow(() -> BaseDonnee.initBaseDonneePseudos());
43 }
44
45 }
46CREATE ALIAS INIT_PSEUDOS AS $$
47import java.sql.Connection;
48import java.sql.Statement;
49import java.sql.SQLException;
50@CODE
51void init_pseudos(final Connection conn, final int maxPseudo) throws SQLException {
52 try (Statement stmt = conn.createStatement()) {
53 while (maxPseudo >= 0) do {
54 stmt.execute("INSERT INTO Pseudos (indexPseudo) VALUES (MaxPseudo);");
55 maxPseudo = maxPseudo - 1;
56 }
57 }
58}
59$$;
60CALL INIT_PSEUDOS (5);
61
Please, provide the appropriate value for the maxPseudo
argument.
Please, consider the provided code as just an example of use: you can improve the code in different ways, like using PreparedStatement
s instead of Statement
s for efficiency purposes, checking parameters for nullability, etcetera.
QUESTION
Hibernate Interceptor not working after upgrading to Hibernate 5
Asked 2021-Dec-28 at 05:27Earlier my Interceptor code was working fine for Hibernate 3. After I upgraded to Hibernate 5 and made the necessary changes, callback methods like onSave & onFlushDirty stopped working.
Regarding library changes, below Hibernate 3 jars I replaced with Hibernate 5 jars.
Hibernate 3 jars replaced-
- dom4j.jar
- hibernate-core-4.3.5.Final.jar
- hibernate-jpa-2.1-api-1.0.0.Final.jar
- jboss-logging.jar
Hibernate 5 jars added-
- byte-buddy-1.9.5.jar
- classmate-1.3.4.jar
- dom4j-2.1.1.jar
- hibernate-commons-annotations-5.1.0.Final.jar
- hibernate-core-5.4.1.Final.jar
- javax.persistence-api-2.2.jar
- javax.transaction.jar
- jboss-logging-3.3.2.Final.jar
Below is my Interceptor code-
1public class CustomInterceptor extends EmptyInterceptor {
2
3@Override
4public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
5 System.out.println("onFlushDirty called");
6 return super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types);
7}
8
9@Override
10public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
11 System.out.println("onSavecalled");
12 return super.onSave(entity, id, state, propertyNames, types);
13}
14}
15
If someone can point out what I am missing or any correction that I need to make, it would be very helpful.
Please Note- Entire Application is working smoothly except that Interceptor Callback methods are not getting called.
ANSWER
Answered 2021-Dec-28 at 05:27Could you please try with the following:
1public class CustomInterceptor extends EmptyInterceptor {
2
3@Override
4public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
5 System.out.println("onFlushDirty called");
6 return super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types);
7}
8
9@Override
10public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
11 System.out.println("onSavecalled");
12 return super.onSave(entity, id, state, propertyNames, types);
13}
14}
15Session session = sessionFactory.withOptions()
16 .interceptor(new CustomInterceptor())
17 .openSession();
18
QUESTION
Spring boot applicaiton unable to find SQLite jdbc driver class
Asked 2021-Dec-26 at 11:20In my Spring boot application I have the dependency for sqlite jdbc driver specified:
1<dependency>
2 <groupId>org.xerial</groupId>
3 <artifactId>sqlite-jdbc</artifactId>
4 <version>3.34.0</version>
5</dependency>
6
and in pom.xml properties
1<dependency>
2 <groupId>org.xerial</groupId>
3 <artifactId>sqlite-jdbc</artifactId>
4 <version>3.34.0</version>
5</dependency>
6<hibernate.version>5.1.0.Final</hibernate.version>
7
and have the below in my application.properties:
1<dependency>
2 <groupId>org.xerial</groupId>
3 <artifactId>sqlite-jdbc</artifactId>
4 <version>3.34.0</version>
5</dependency>
6<hibernate.version>5.1.0.Final</hibernate.version>
7spring.jpa.database-platform=com.springboot.sqlite.SQLDialect
8spring.jpa.hibernate.ddl-auto=update
9spring.jpa.defer-datasource-initialization = true
10
11spring.datasource.url = jdbc:sqlite:cryptobot.db
12spring.datasource.driver-class-name = org.sqlite.JDBC
13
The SQLDialect class I have provided is copied from this article. But running the application fails with
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/jpa/HibernatePersistenceProvider at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.13.jar:5.3.13] at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:541) ~[spring-beans-5.3.13.jar:5.3.13] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352) ~[spring-beans-5.3.13.jar:5.3.13] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195) ~[spring-beans-5.3.13.jar:5.3.13] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.13.jar:5.3.13] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.13.jar:5.3.13] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.13.jar:5.3.13] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.13.jar:5.3.13] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.13.jar:5.3.13] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.13.jar:5.3.13] at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.13.jar:5.3.13] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3.13.jar:5.3.13] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.13.jar:5.3.13] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-2.6.1.jar:2.6.1] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412) ~[spring-boot-2.6.1.jar:2.6.1] at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.1.jar:2.6.1] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.1.jar:2.6.1] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1290) ~[spring-boot-2.6.1.jar:2.6.1] at com.binance.bot.BinancebotApplication.main(BinancebotApplication.java:10) ~[classes/:na]
What is going wrong here?
ANSWER
Answered 2021-Dec-22 at 11:35I tried to replicate this in my local machine and here the solution.
You have to create your own dilect by extending org.hibernate.dialect
1<dependency>
2 <groupId>org.xerial</groupId>
3 <artifactId>sqlite-jdbc</artifactId>
4 <version>3.34.0</version>
5</dependency>
6<hibernate.version>5.1.0.Final</hibernate.version>
7spring.jpa.database-platform=com.springboot.sqlite.SQLDialect
8spring.jpa.hibernate.ddl-auto=update
9spring.jpa.defer-datasource-initialization = true
10
11spring.datasource.url = jdbc:sqlite:cryptobot.db
12spring.datasource.driver-class-name = org.sqlite.JDBC
13package com.mehul.SQLiteDemo.dialect;
14
15import java.sql.Types;
16
17import org.hibernate.dialect.Dialect;
18import org.hibernate.dialect.function.SQLFunctionTemplate;
19import org.hibernate.dialect.function.StandardSQLFunction;
20import org.hibernate.dialect.function.VarArgsSQLFunction;
21import org.hibernate.type.StringType;
22
23public class SQLDialect extends Dialect {
24 public SQLDialect() {
25 registerColumnType(Types.BIT, "integer");
26 registerColumnType(Types.TINYINT, "tinyint");
27 registerColumnType(Types.SMALLINT, "smallint");
28 registerColumnType(Types.INTEGER, "integer");
29 registerColumnType(Types.BIGINT, "bigint");
30 registerColumnType(Types.FLOAT, "float");
31 registerColumnType(Types.REAL, "real");
32 registerColumnType(Types.DOUBLE, "double");
33 registerColumnType(Types.NUMERIC, "numeric");
34 registerColumnType(Types.DECIMAL, "decimal");
35 registerColumnType(Types.CHAR, "char");
36 registerColumnType(Types.VARCHAR, "varchar");
37 registerColumnType(Types.LONGVARCHAR, "longvarchar");
38 registerColumnType(Types.DATE, "date");
39 registerColumnType(Types.TIME, "time");
40 registerColumnType(Types.TIMESTAMP, "timestamp");
41 registerColumnType(Types.BINARY, "blob");
42 registerColumnType(Types.VARBINARY, "blob");
43 registerColumnType(Types.LONGVARBINARY, "blob");
44 // registerColumnType(Types.NULL, "null");
45 registerColumnType(Types.BLOB, "blob");
46 registerColumnType(Types.CLOB, "clob");
47 registerColumnType(Types.BOOLEAN, "integer");
48
49 registerFunction("concat", new VarArgsSQLFunction(StringType.INSTANCE, "", "||", ""));
50 registerFunction("mod", new SQLFunctionTemplate(StringType.INSTANCE, "?1 % ?2"));
51 registerFunction("substr", new StandardSQLFunction("substr", StringType.INSTANCE));
52 registerFunction("substring", new StandardSQLFunction("substr", StringType.INSTANCE));
53 }
54
55 public boolean supportsIdentityColumns() {
56 return true;
57 }
58
59 public boolean hasDataTypeInIdentityColumn() {
60 return false; // As specify in NHibernate dialect
61 }
62
63 public String getIdentityColumnString() {
64 // return "integer primary key autoincrement";
65 return "integer";
66 }
67
68 public String getIdentitySelectString() {
69 return "select last_insert_rowid()";
70 }
71
72 public boolean supportsLimit() {
73 return true;
74 }
75
76 protected String getLimitString(String query, boolean hasOffset) {
77 return new StringBuffer(query.length() + 20).append(query).append(hasOffset ? " limit ? offset ?" : " limit ?")
78 .toString();
79 }
80
81 public boolean supportsTemporaryTables() {
82 return true;
83 }
84
85 public String getCreateTemporaryTableString() {
86 return "create temporary table if not exists";
87 }
88
89 public boolean dropTemporaryTableAfterUse() {
90 return false;
91 }
92
93 public boolean supportsCurrentTimestampSelection() {
94 return true;
95 }
96
97 public boolean isCurrentTimestampSelectStringCallable() {
98 return false;
99 }
100
101 public String getCurrentTimestampSelectString() {
102 return "select current_timestamp";
103 }
104
105 public boolean supportsUnionAll() {
106 return true;
107 }
108
109 public boolean hasAlterTable() {
110 return false; // As specify in NHibernate dialect
111 }
112
113 public boolean dropConstraints() {
114 return false;
115 }
116
117 public String getAddColumnString() {
118 return "add column";
119 }
120
121 public String getForUpdateString() {
122 return "";
123 }
124
125 public boolean supportsOuterJoinForUpdate() {
126 return false;
127 }
128
129 public String getDropForeignKeyString() {
130 throw new UnsupportedOperationException("No drop foreign key syntax supported by SQLiteDialect");
131 }
132
133 public String getAddForeignKeyConstraintString(String constraintName, String[] foreignKey, String referencedTable,
134 String[] primaryKey, boolean referencesPrimaryKey) {
135 throw new UnsupportedOperationException("No add foreign key syntax supported by SQLiteDialect");
136 }
137
138 public String getAddPrimaryKeyConstraintString(String constraintName) {
139 throw new UnsupportedOperationException("No add primary key syntax supported by SQLiteDialect");
140 }
141
142 public boolean supportsIfExistsBeforeTableName() {
143 return true;
144 }
145
146 public boolean supportsCascadeDelete() {
147 return false;
148 }
149}
150
Also update spring.jpa.database-platform=com.mehul.SQLiteDemo.dialect.SQLDialect
with your package and classname.
Note : I used <hibernate.version>5.6.3.Final</hibernate.version>
QUESTION
Log4j2 deadlock
Asked 2021-Dec-23 at 16:03My application is a sprint boot application that uses log4j2 and runs in a Wildfly server. After the zero day attak, we upgraded to the latest log4j2 version(2.16). But after the log4j upgrade, my application stops working once in a while. And when I looked at the threaddumps, I found that there is a deadlock created by log4j. Here is my log4j configuration. It was working fine before the upgrade.
1<?xml version="1.0" encoding="UTF-8" ?>
2<Configuration>
3
4 <Properties>
5 <Property name="LOGDIR">${sys:jboss.server.log.dir}/application</Property>
6 <Property name="FILE_LOG_PATTERN">%d %-5p [%-8.8t] %-25.25c{1} | [%X{correlationId}] %m%n</Property>
7 </Properties>
8
9 <Appenders>
10
11 <Console name="SYSOUT" target="SYSTEM_OUT" follow="true">
12 <PatternLayout pattern="${FILE_LOG_PATTERN}"/>
13 </Console>
14
15 <RollingFile name="CSL" fileName="${LOGDIR}/csl.log"
16 filePattern="${LOGDIR}/csl.%d{yyyy-MM-dd}.log.gz" ignoreExceptions="false">
17 <PatternLayout pattern="${FILE_LOG_PATTERN}"/>
18 <Policies>
19 <TimeBasedTriggeringPolicy/>
20 </Policies>
21 <DefaultRolloverStrategy>
22 <Delete basePath="${LOGDIR}" maxDepth="1">
23 <IfAny>
24 <IfFileName glob="csl*.log.gz" />
25 <IfFileName glob="access_log*.log" />
26 </IfAny>
27 <IfLastModified age="7d" />
28 </Delete>
29 </DefaultRolloverStrategy>
30 </RollingFile>
31
32 <RollingFile name="OTR" fileName="${LOGDIR}/otr.log"
33 filePattern="${LOGDIR}/otr.%d{yyyy-MM-dd}.log.gz" ignoreExceptions="true"
34 bufferedIO="true">
35 <PatternLayout pattern="${FILE_LOG_PATTERN}"/>
36 <Policies>
37 <TimeBasedTriggeringPolicy/>
38 </Policies>
39 <DefaultRolloverStrategy>
40 <Delete basePath="${LOGDIR}" maxDepth="1">
41 <IfFileName glob="otr*.log.gz" />
42 <IfLastModified age="23d" />
43 </Delete>
44 </DefaultRolloverStrategy>
45 </RollingFile>
46
47 </Appenders>
48
49 <Loggers>
50 <Logger name="org.apache.catalina.startup.DigesterFactory" level="error" />
51 <Logger name="org.apache.catalina.util.LifecycleBase" level="error" />
52 <Logger name="org.apache.coyote.http11.Http11NioProtocol" level="warn" />
53 <logger name="org.apache.sshd.common.util.SecurityUtils" level="warn"/>
54 <Logger name="org.apache.tomcat.util.net.NioSelectorPool" level="warn" />
55 <Logger name="org.eclipse.jetty.util.component.AbstractLifeCycle" level="error" />
56 <Logger name="org.hibernate.validator.internal.util.Version" level="warn" />
57 <logger name="org.springframework.boot.actuate.endpoint.jmx" level="warn"/>
58
59 <logger name="org.springframework" level="info"/>
60 <logger name="org.springframework.aop.framework" level="warn"/>
61 <logger name="org.apache.jasper.servlet.JspServlet" level="trace"/>
62 <logger name="com.zaxxer.hikari.pool.HikariPool" level="debug"/>
63 <logger name="com.google.code.ssm.spring.SSMCache" level="warn"/>
64
65 <logger name="com.faskan" level="info" additivity="false">
66 <appender-ref ref="OTR" />
67 <appender-ref ref="CSL" />
68 </logger>
69
70 <Root level="info">
71 <AppenderRef ref="CSL"/>
72 <AppenderRef ref="SYSOUT"/>
73 </Root>
74 </Loggers>
75
76</Configuration>
77
When analysing this issue, I came through a possible defect in log4j code. Not sure if that can result in a deadlock.
Log4J possible bug - As per the release notes, there was a fix to Enable immediate flush on RollingFileAppender when buffered i/o is not enabled. (LOG4J2-3114). But the code just does the opposite in RollingFileAppenderBuilder.
1<?xml version="1.0" encoding="UTF-8" ?>
2<Configuration>
3
4 <Properties>
5 <Property name="LOGDIR">${sys:jboss.server.log.dir}/application</Property>
6 <Property name="FILE_LOG_PATTERN">%d %-5p [%-8.8t] %-25.25c{1} | [%X{correlationId}] %m%n</Property>
7 </Properties>
8
9 <Appenders>
10
11 <Console name="SYSOUT" target="SYSTEM_OUT" follow="true">
12 <PatternLayout pattern="${FILE_LOG_PATTERN}"/>
13 </Console>
14
15 <RollingFile name="CSL" fileName="${LOGDIR}/csl.log"
16 filePattern="${LOGDIR}/csl.%d{yyyy-MM-dd}.log.gz" ignoreExceptions="false">
17 <PatternLayout pattern="${FILE_LOG_PATTERN}"/>
18 <Policies>
19 <TimeBasedTriggeringPolicy/>
20 </Policies>
21 <DefaultRolloverStrategy>
22 <Delete basePath="${LOGDIR}" maxDepth="1">
23 <IfAny>
24 <IfFileName glob="csl*.log.gz" />
25 <IfFileName glob="access_log*.log" />
26 </IfAny>
27 <IfLastModified age="7d" />
28 </Delete>
29 </DefaultRolloverStrategy>
30 </RollingFile>
31
32 <RollingFile name="OTR" fileName="${LOGDIR}/otr.log"
33 filePattern="${LOGDIR}/otr.%d{yyyy-MM-dd}.log.gz" ignoreExceptions="true"
34 bufferedIO="true">
35 <PatternLayout pattern="${FILE_LOG_PATTERN}"/>
36 <Policies>
37 <TimeBasedTriggeringPolicy/>
38 </Policies>
39 <DefaultRolloverStrategy>
40 <Delete basePath="${LOGDIR}" maxDepth="1">
41 <IfFileName glob="otr*.log.gz" />
42 <IfLastModified age="23d" />
43 </Delete>
44 </DefaultRolloverStrategy>
45 </RollingFile>
46
47 </Appenders>
48
49 <Loggers>
50 <Logger name="org.apache.catalina.startup.DigesterFactory" level="error" />
51 <Logger name="org.apache.catalina.util.LifecycleBase" level="error" />
52 <Logger name="org.apache.coyote.http11.Http11NioProtocol" level="warn" />
53 <logger name="org.apache.sshd.common.util.SecurityUtils" level="warn"/>
54 <Logger name="org.apache.tomcat.util.net.NioSelectorPool" level="warn" />
55 <Logger name="org.eclipse.jetty.util.component.AbstractLifeCycle" level="error" />
56 <Logger name="org.hibernate.validator.internal.util.Version" level="warn" />
57 <logger name="org.springframework.boot.actuate.endpoint.jmx" level="warn"/>
58
59 <logger name="org.springframework" level="info"/>
60 <logger name="org.springframework.aop.framework" level="warn"/>
61 <logger name="org.apache.jasper.servlet.JspServlet" level="trace"/>
62 <logger name="com.zaxxer.hikari.pool.HikariPool" level="debug"/>
63 <logger name="com.google.code.ssm.spring.SSMCache" level="warn"/>
64
65 <logger name="com.faskan" level="info" additivity="false">
66 <appender-ref ref="OTR" />
67 <appender-ref ref="CSL" />
68 </logger>
69
70 <Root level="info">
71 <AppenderRef ref="CSL"/>
72 <AppenderRef ref="SYSOUT"/>
73 </Root>
74 </Loggers>
75
76</Configuration>
77private Appender createAppender(final String name, final Log4j1Configuration config, final Layout layout,
78 final Filter filter, final boolean bufferedIo, boolean immediateFlush, final String fileName,
79 final String level, final String maxSize, final String maxBackups) {
80 org.apache.logging.log4j.core.Layout<?> fileLayout = null;
81 if (bufferedIo) {
82 immediateFlush = true;
83 }
84...
85
It should have been if(!bufferedIo) { immediateFlush = true; }
. And one of my appender explicitly sets bufferedIo value to true. I know that log4j does a bufferedio by default and it is not necessary to set this flag explicitly. But unfortunately the code that I am working on is a legacy code and the configuration was working fine before the upgrade.
Threaddump "default task-128" #450 prio=5 os_prio=0 tid=0x00007f31f80cf800 nid=0x14c8 waiting for monitor entry [0x00007f31a7d88000] java.lang.Thread.State: BLOCKED (on object monitor) at org.apache.logging.log4j.core.appender.OutputStreamManager.writeBytes(OutputStreamManager.java:352) - waiting to lock <0x00000000c0e70eb0> (a org.apache.logging.log4j.core.appender.OutputStreamManager) at org.apache.logging.log4j.core.layout.TextEncoderHelper.writeEncodedText(TextEncoderHelper.java:96) at org.apache.logging.log4j.core.layout.TextEncoderHelper.encodeText(TextEncoderHelper.java:65) at org.apache.logging.log4j.core.layout.StringBuilderEncoder.encode(StringBuilderEncoder.java:68) at org.apache.logging.log4j.core.layout.StringBuilderEncoder.encode(StringBuilderEncoder.java:32) at org.apache.logging.log4j.core.layout.PatternLayout.encode(PatternLayout.java:228) at org.apache.logging.log4j.core.layout.PatternLayout.encode(PatternLayout.java:60) at org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.directEncodeEvent(AbstractOutputStreamAppender.java:197) at org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.tryAppend(AbstractOutputStreamAppender.java:190) at org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.append(AbstractOutputStreamAppender.java:181) at org.apache.logging.log4j.core.config.AppenderControl.tryCallAppender(AppenderControl.java:161) at org.apache.logging.log4j.core.config.AppenderControl.callAppender0(AppenderControl.java:134) at org.apache.logging.log4j.core.config.AppenderControl.callAppenderPreventRecursion(AppenderControl.java:125) at org.apache.logging.log4j.core.config.AppenderControl.callAppender(AppenderControl.java:89) at org.apache.logging.log4j.core.config.LoggerConfig.callAppenders(LoggerConfig.java:542) at org.apache.logging.log4j.core.config.LoggerConfig.processLogEvent(LoggerConfig.java:500) at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:483) at org.apache.logging.log4j.core.config.LoggerConfig.logParent(LoggerConfig.java:533) at org.apache.logging.log4j.core.config.LoggerConfig.processLogEvent(LoggerConfig.java:502) at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:483) at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:388) at org.apache.logging.log4j.core.config.AwaitCompletionReliabilityStrategy.log(AwaitCompletionReliabilityStrategy.java:63) at org.apache.logging.log4j.core.Logger.logMessage(Logger.java:153) at org.apache.logging.slf4j.Log4jLogger.log(Log4jLogger.java:376) at org.apache.commons.logging.impl.SLF4JLocationAwareLog.error(SLF4JLocationAwareLog.java:203) at org.springframework.boot.web.support.ErrorPageFilter.handleCommittedResponse(ErrorPageFilter.java:225)
ANSWER
Answered 2021-Dec-23 at 16:03Found my answer in this thread https://developer.jboss.org/thread/241453. It is a log4j/jboss configuration issue. The fix is to either exclude jboss logging subsystem from jboss deployment configuration or get rid of the console appender. Thanks to Ralph Goers from Log4J team for guiding me towards the jboss thread.
I have closed the issue that I raised to https://issues.apache.org/jira/browse/LOG4J2-3274. The code snippet that I shared in this question was from log4j-1.2 compatibility adapter which doesn't has any impact in my code because I am already using the latest api version.
QUESTION
Invalid DateTimeFormat when inserting date in H2 in memory DB
Asked 2021-Dec-21 at 23:29I'm having a problem trying to insert values in a in-memory H2 DB.
I have this Entity:
1@Entity
2@Table(name="myTable")
3public class MyEntity {
4
5 @Id
6 @GeneratedValue(strategy = GenerationType.AUTO)
7 private long id;
8
9 @Column(name = "startDate")
10 @DateTimeFormat(pattern="yyy-MM-dd-HH.mm.ss")
11 private Date startDate;
12
13 @Column(name = "endDate")
14 @DateTimeFormat(pattern="yyy-MM-dd-HH.mm.ss")
15 private Date endDate;
16}
17
I've used the pattern yyy-MM-dd-HH.mm.ss
because the dates are in format like 2021-06-14-00.00.00
or 2021-12-31-23.59.59
.
The @DateTimeFormat
imported is org.springframework.format.annotation.DateTimeFormat;
and Date
is java.util.Date
.
To insert values in the DB I've this script:
1@Entity
2@Table(name="myTable")
3public class MyEntity {
4
5 @Id
6 @GeneratedValue(strategy = GenerationType.AUTO)
7 private long id;
8
9 @Column(name = "startDate")
10 @DateTimeFormat(pattern="yyy-MM-dd-HH.mm.ss")
11 private Date startDate;
12
13 @Column(name = "endDate")
14 @DateTimeFormat(pattern="yyy-MM-dd-HH.mm.ss")
15 private Date endDate;
16}
17INSERT INTO myTable (ID, START_DATE, END_DATE) VALUES
18(1, '2020-08-07-00.00.00', '2021-12-31-23.59.59'),
19(2, '2020-04-03-14.00.00', '2021-01-14-18.30.00'),
20(3, '2020-09-15-00.00.00', '2021-06-15-11.00.00'),
21(4, '2020-01-18-16.00.00', '2021-12-31-23.59.59');
22
But it throw an error:
1@Entity
2@Table(name="myTable")
3public class MyEntity {
4
5 @Id
6 @GeneratedValue(strategy = GenerationType.AUTO)
7 private long id;
8
9 @Column(name = "startDate")
10 @DateTimeFormat(pattern="yyy-MM-dd-HH.mm.ss")
11 private Date startDate;
12
13 @Column(name = "endDate")
14 @DateTimeFormat(pattern="yyy-MM-dd-HH.mm.ss")
15 private Date endDate;
16}
17INSERT INTO myTable (ID, START_DATE, END_DATE) VALUES
18(1, '2020-08-07-00.00.00', '2021-12-31-23.59.59'),
19(2, '2020-04-03-14.00.00', '2021-01-14-18.30.00'),
20(3, '2020-09-15-00.00.00', '2021-06-15-11.00.00'),
21(4, '2020-01-18-16.00.00', '2021-12-31-23.59.59');
22Caused by: org.h2.jdbc.JdbcSQLDataException: Imposible interpretar la constante "TIMESTAMP" "2021-12-31-23.59.59"
23Cannot parse "TIMESTAMP" constant "2021-12-31-23.59.59"; SQL statement:
24INSERT INTO myTable (ID, ...
25
26...
27
28Caused by: java.lang.NumberFormatException: 31-23.59.59
29
The text in the error which is not in english is something like "Unable to interpret constant "TIMESTAMP"".
Also I have tested a few things and, (this is important!) removing hours, minutes and seconds, the program works, so I assume is the pattern which is not correct.
This SQL script works:
1@Entity
2@Table(name="myTable")
3public class MyEntity {
4
5 @Id
6 @GeneratedValue(strategy = GenerationType.AUTO)
7 private long id;
8
9 @Column(name = "startDate")
10 @DateTimeFormat(pattern="yyy-MM-dd-HH.mm.ss")
11 private Date startDate;
12
13 @Column(name = "endDate")
14 @DateTimeFormat(pattern="yyy-MM-dd-HH.mm.ss")
15 private Date endDate;
16}
17INSERT INTO myTable (ID, START_DATE, END_DATE) VALUES
18(1, '2020-08-07-00.00.00', '2021-12-31-23.59.59'),
19(2, '2020-04-03-14.00.00', '2021-01-14-18.30.00'),
20(3, '2020-09-15-00.00.00', '2021-06-15-11.00.00'),
21(4, '2020-01-18-16.00.00', '2021-12-31-23.59.59');
22Caused by: org.h2.jdbc.JdbcSQLDataException: Imposible interpretar la constante "TIMESTAMP" "2021-12-31-23.59.59"
23Cannot parse "TIMESTAMP" constant "2021-12-31-23.59.59"; SQL statement:
24INSERT INTO myTable (ID, ...
25
26...
27
28Caused by: java.lang.NumberFormatException: 31-23.59.59
29INSERT INTO myTable (ID, START_DATE, END_DATE) VALUES
30(1, '2020-08-07', '2021-12-31'),
31(2, '2020-04-03', '2021-01-14'),
32(3, '2020-09-15', '2021-06-15'),
33(4, '2020-01-18', '2021-12-31');
34
I've checked a DateTimeFormat tester online and the current date with my pattern is 2021-12-21-17.44.32
, but even creating the table using only that date it thrown the error.
More info about the table:
The table (and also the columns) is created using spring.jpa.hibernate.ddl-auto=update
so I assume the column type is DATE
(as the entity field).
So I'm trying to insert a String with format yyy-MM-dd-HH.mm.ss
in a DATE
column (if I'm not wrong).
So, what's the problem? Is not possible to insert this pattern as date from string in an H2 in memory DB?
Thanks in advance.
ANSWER
Answered 2021-Dec-21 at 23:03If you are just trying to insert a java.util.Date
into a TIMESTAMP
column you don't need @DateTimeFormat
. You are not parsing anything, you part from the Date
object, and JPA translates it into the proper SQL datatype.
Define the column this way:
1@Entity
2@Table(name="myTable")
3public class MyEntity {
4
5 @Id
6 @GeneratedValue(strategy = GenerationType.AUTO)
7 private long id;
8
9 @Column(name = "startDate")
10 @DateTimeFormat(pattern="yyy-MM-dd-HH.mm.ss")
11 private Date startDate;
12
13 @Column(name = "endDate")
14 @DateTimeFormat(pattern="yyy-MM-dd-HH.mm.ss")
15 private Date endDate;
16}
17INSERT INTO myTable (ID, START_DATE, END_DATE) VALUES
18(1, '2020-08-07-00.00.00', '2021-12-31-23.59.59'),
19(2, '2020-04-03-14.00.00', '2021-01-14-18.30.00'),
20(3, '2020-09-15-00.00.00', '2021-06-15-11.00.00'),
21(4, '2020-01-18-16.00.00', '2021-12-31-23.59.59');
22Caused by: org.h2.jdbc.JdbcSQLDataException: Imposible interpretar la constante "TIMESTAMP" "2021-12-31-23.59.59"
23Cannot parse "TIMESTAMP" constant "2021-12-31-23.59.59"; SQL statement:
24INSERT INTO myTable (ID, ...
25
26...
27
28Caused by: java.lang.NumberFormatException: 31-23.59.59
29INSERT INTO myTable (ID, START_DATE, END_DATE) VALUES
30(1, '2020-08-07', '2021-12-31'),
31(2, '2020-04-03', '2021-01-14'),
32(3, '2020-09-15', '2021-06-15'),
33(4, '2020-01-18', '2021-12-31');
34 @Column(name = "startDate")
35 @Temporal(value=TemporalType.DATE)
36 private Date startDate;
37
38
And you should be good to go.
Update
If only DATE
pattern works, and no TIMESTAMP
patterns work, it means that the column has been defined with the wrong datatype. DATE and TIMESTAMP are two different H2 datatypes (and in all the other DDBBs but may be with different names)
Community Discussions contain sources that include Stack Exchange Network
Tutorials and Learning Resources in Hibernate
Tutorials and Learning Resources are not available at this moment for Hibernate