HHH-16813 don't add @Generated annotations if it's going to cause a compilation failure

This commit is contained in:
Gavin King 2023-06-17 12:26:38 +02:00
parent b1998782e9
commit 56cf0c414c
3 changed files with 27 additions and 13 deletions

View File

@ -98,6 +98,10 @@ public final class ClassWriter {
StringWriter sw = new StringWriter();
try ( PrintWriter pw = new PrintWriter(sw) ) {
if ( entity.getElement() instanceof TypeElement ) {
pw.println(writeStaticMetaModelAnnotation(entity));
}
if (context.addGeneratedAnnotation()) {
pw.println(writeGeneratedAnnotation(entity, context));
}
@ -105,10 +109,6 @@ public final class ClassWriter {
pw.println(writeSuppressWarnings());
}
if ( entity.getElement() instanceof TypeElement ) {
pw.println(writeStaticMetaModelAnnotation(entity));
}
printClassDeclaration(entity, pw, context);
pw.println();
@ -203,18 +203,26 @@ public final class ClassWriter {
private static String writeGeneratedAnnotation(Metamodel entity, Context context) {
StringBuilder generatedAnnotation = new StringBuilder();
generatedAnnotation.append( "@" )
generatedAnnotation
.append( "@" )
.append( entity.importType( "jakarta.annotation.Generated" ) )
.append( "(value = \"" )
.append( JPAMetaModelEntityProcessor.class.getName() );
.append( "(" );
if ( context.addGeneratedDate() ) {
generatedAnnotation.append( "\", date = \"" )
generatedAnnotation
.append( "value = " );
}
generatedAnnotation
.append( "\"" )
.append( JPAMetaModelEntityProcessor.class.getName() )
.append( "\"" );
if ( context.addGeneratedDate() ) {
generatedAnnotation
.append( ", date = " )
.append( "\"" )
.append( SIMPLE_DATE_FORMAT.get().format( new Date() ) )
.append( "\")" );
}
else {
generatedAnnotation.append( "\")" );
.append( "\"" );
}
generatedAnnotation.append( ")" );
return generatedAnnotation.toString();
}

View File

@ -90,6 +90,12 @@ public class JPAMetaModelEntityProcessor extends AbstractProcessor {
boolean addGeneratedAnnotation = Boolean.parseBoolean( tmp );
context.setAddGeneratedAnnotation( addGeneratedAnnotation );
}
else {
PackageElement jakartaAnnotationPackage =
context.getProcessingEnvironment().getElementUtils()
.getPackageElement( "jakarta.annotation" );
context.setAddGeneratedAnnotation( jakartaAnnotationPackage != null );
}
tmp = env.getOptions().get( JPAMetaModelEntityProcessor.ADD_GENERATION_DATE );
boolean addGenerationDate = Boolean.parseBoolean( tmp );

View File

@ -28,7 +28,7 @@ public class GeneratedAnnotationTest extends CompilationTest {
// need to check the source because @Generated is not a runtime annotation
String metaModelSource = getMetaModelSourceAsString( TestEntity.class );
String generatedString = "@Generated(value = \"org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor\")";
String generatedString = "@Generated(\"org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor\")";
assertTrue( "@Generated should be added to the metamodel.", metaModelSource.contains( generatedString ) );
}
}