From 823270d94cc38bab315166df56b0e829cd230e15 Mon Sep 17 00:00:00 2001 From: Koen Aers Date: Wed, 29 Oct 2025 11:34:27 +0100 Subject: [PATCH 1/2] HBX-3196: Improve the implementation of classes BasicPOJOClass, Cfg2JavaTool, ComponentPOJOClass and EntityPOJOClass Signed-off-by: Koen Aers --- .../internal/export/java/BasicPOJOClass.java | 183 +++++------ .../internal/export/java/Cfg2JavaTool.java | 68 ++-- .../export/java/ComponentPOJOClass.java | 36 +-- .../internal/export/java/EntityPOJOClass.java | 302 ++++++++---------- 4 files changed, 264 insertions(+), 325 deletions(-) diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/java/BasicPOJOClass.java b/orm/src/main/java/org/hibernate/tool/internal/export/java/BasicPOJOClass.java index b0e39cd6ea..3a44651cb0 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/export/java/BasicPOJOClass.java +++ b/orm/src/main/java/org/hibernate/tool/internal/export/java/BasicPOJOClass.java @@ -17,11 +17,7 @@ */ package org.hibernate.tool.internal.export.java; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; import org.hibernate.internal.util.StringHelper; import org.hibernate.mapping.Array; @@ -37,17 +33,21 @@ import org.hibernate.mapping.Selectable; import org.hibernate.mapping.Set; import org.hibernate.mapping.SimpleValue; -import org.hibernate.mapping.Value; import org.hibernate.tool.internal.export.common.DefaultValueVisitor; import org.hibernate.tool.internal.util.NameConverter; +import static org.hibernate.tool.internal.export.java.MetaAttributeConstants.CLASS_DESCRIPTION; +import static org.hibernate.tool.internal.export.java.MetaAttributeConstants.SCOPE_CLASS; +import static org.hibernate.tool.internal.export.java.MetaAttributeConstants.CLASS_MODIFIER; +import static org.hibernate.tool.internal.export.java.MetaAttributeConstants.INTERFACE; + /** * Abstract implementation of POJOClass. To be extended by ComponentPOJO and EntityPOJO * @author max * @author Amit Bhayani * */ -abstract public class BasicPOJOClass implements POJOClass, MetaAttributeConstants { +abstract public class BasicPOJOClass implements POJOClass { protected ImportContext importContext; protected MetaAttributable meta; @@ -69,16 +69,14 @@ protected void init() { MetaAttribute metaAttribute = meta.getMetaAttribute("extra-import"); if(metaAttribute!=null) { - Iterator values = metaAttribute.getValues().iterator(); - while ( values.hasNext() ) { - String element = (String) values.next(); - importContext.importType(element); - } + for (String element : metaAttribute.getValues()) { + importContext.importType(element); + } } } protected String getPackageDeclaration(String pkgName) { - if (pkgName!=null && pkgName.trim().length()!=0 ) { + if (pkgName!=null && !pkgName.trim().isEmpty()) { return "package " + pkgName + ";"; } else { @@ -104,7 +102,7 @@ public String getShortName() { public String getQualifiedDeclarationName() { String generatedName = qualifyInnerClass(getGeneratedClassName()); String qualifier = StringHelper.qualifier( getMappedClassName() ); - if ( !"".equals( qualifier ) ) { + if (!qualifier.isEmpty()) { return qualifier + "." + generatedName; } else { @@ -125,9 +123,9 @@ protected String getGeneratedClassName() if(StringHelper.isEmpty(generatedClass) ) { generatedClass = getMappedClassName(); } - if(generatedClass==null) return ""; // will occur for - return generatedClass; - } + // will occur for + return Objects.requireNonNullElse(generatedClass, ""); + } protected String qualifyInnerClass(String className) { @@ -198,7 +196,7 @@ public boolean isInterface() { public String getExtendsDeclaration() { String extendz = getExtends(); - if ( extendz == null || extendz.trim().length() == 0 ) { + if ( extendz == null || extendz.trim().isEmpty()) { return ""; } else { @@ -208,7 +206,7 @@ public String getExtendsDeclaration() { public String getImplementsDeclaration() { String implementz = getImplements(); - if ( implementz == null || implementz.trim().length() == 0 ) { + if ( implementz == null || implementz.trim().isEmpty()) { return ""; } else { @@ -225,10 +223,10 @@ public String generateEquals(String thisName, String otherName, boolean useGener public abstract Iterator getAllPropertiesIterator(); protected String generateEquals(String thisName, String otherName, Iterator allPropertiesIterator, boolean useGenerics) { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); while ( allPropertiesIterator.hasNext() ) { Property property = (Property) allPropertiesIterator.next(); - if ( buf.length() > 0 ) buf.append( "\n && " ); + if (!buf.isEmpty()) buf.append( "\n && " ); String javaTypeName = c2j.getJavaTypeName( property, useGenerics, this ); buf.append( internalgenerateEquals( @@ -237,7 +235,7 @@ protected String generateEquals(String thisName, String otherName, Iterator subElements = component.getProperties().iterator(); - buildRecursiveAttributeOverride( subElements, null, property, annotations ); + buildRecursiveAttributeOverride( subElements, null, annotations ); annotations.setLength( annotations.length() - 2 ); annotations.append( " } )" ); } @@ -378,11 +372,8 @@ public String generateAnnColumnAnnotation(Property property) { else { annotations.append("@").append( importType("org.hibernate.annotations.Columns") ).append("( { " ); for (Selectable selectable : property.getColumns()) { - if ( selectable.isFormula() ) { - //TODO formula in multicolumns not supported by annotations - //annotations.append("/* TODO formula in multicolumns not supported by annotations */"); - } - else { + //TODO formula in multicolumns not supported by annotations + if ( !selectable.isFormula() ) { annotations.append( "\n " ); buildColumnAnnotation( selectable, annotations, insertable, updatable ); annotations.append( ", " ); @@ -395,7 +386,7 @@ public String generateAnnColumnAnnotation(Property property) { return annotations.toString(); } - private void buildRecursiveAttributeOverride(Iterator subElements, String path, Property property, StringBuffer annotations) { + private void buildRecursiveAttributeOverride(Iterator subElements, String path, StringBuffer annotations) { while ( subElements.hasNext() ) { Property subProperty = (Property) subElements.next(); if ( subProperty.isComposite() ) { @@ -407,14 +398,12 @@ private void buildRecursiveAttributeOverride(Iterator subElements, String pat } path = path + subProperty.getName(); Component component = (Component) subProperty.getValue(); - buildRecursiveAttributeOverride( component.getProperties().iterator(), path, subProperty, annotations ); + buildRecursiveAttributeOverride( component.getProperties().iterator(), path, annotations ); } else { Selectable selectable = subProperty.getColumns().get(0); - if ( selectable.isFormula() ) { - //TODO formula in multicolumns not supported by annotations - } - else { + //TODO formula in multicolumns not supported by annotations + if ( !selectable.isFormula() ) { annotations.append( "\n " ).append("@") .append( importType("jakarta.persistence.AttributeOverride") ).append("(name=\"" ); if ( path != null ) { @@ -423,7 +412,7 @@ private void buildRecursiveAttributeOverride(Iterator subElements, String pat annotations.append( subProperty.getName() ).append( "\"" ) .append( ", column=" ); buildColumnAnnotation( - selectable, annotations, subProperty.isInsertable(), subProperty.isUpdateable() + selectable, annotations, subProperty.isInsertable(), subProperty.isUpdatable() ); annotations.append( " ), " ); } @@ -433,13 +422,21 @@ private void buildRecursiveAttributeOverride(Iterator subElements, String pat private void buildColumnAnnotation(Selectable selectable, StringBuffer annotations, boolean insertable, boolean updatable) { if ( selectable.isFormula() ) { - annotations.append("@").append( importType("org.hibernate.annotations.Formula") ) - .append("(value=\"" ).append( selectable.getText() ).append( "\")" ); + annotations + .append("@") + .append( importType("org.hibernate.annotations.Formula") ) + .append("(value=\"" ) + .append( selectable.getText() ) + .append( "\")" ); } else { Column column = (Column) selectable; - annotations.append( "@" + importType("jakarta.persistence.Column") + "(name=\"" ).append( column.getName() ).append( "\"" ); - + annotations + .append("@") + .append(importType("jakarta.persistence.Column")) + .append("(name=\"") + .append( column.getName() ) + .append( "\"" ); appendCommonColumnInfo( annotations, column, insertable, updatable ); if (column.getPrecision() != null) { @@ -578,7 +575,6 @@ public String getGetterSignature(Property p) { } /** - * @param p * @return foo -> Foo, FOo -> FOo */ public String getPropertyName(Property p) { @@ -598,31 +594,25 @@ public String getCollectionNameFor(Property property) { * FOo -> FOo */ static public String beanCapitalize(String fieldname) { - if ( fieldname == null || fieldname.length() == 0 ) { + if ( fieldname == null || fieldname.isEmpty()) { return fieldname; } if ( fieldname.length() > 1 && Character.isUpperCase( fieldname.charAt( 1 ) ) ) { return fieldname; } - char chars[] = fieldname.toCharArray(); + char[] chars = fieldname.toCharArray(); chars[0] = Character.toUpperCase( chars[0] ); return new String( chars ); } public boolean isComponent(Property property) { - Value value = property.getValue(); - if ( value != null && value instanceof Component ) { - return true; - } - else { - return false; - } + return property.getValue() instanceof Component; } public String generateHashCode(Property property, String result, String thisName, boolean jdk5) { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); if ( c2j.getMetaAsBool( property, "use-in-equals" ) ) { String javaTypeName = c2j.getJavaTypeName( property, jdk5, this ); boolean isPrimitive = c2j.isPrimitive( javaTypeName ); @@ -635,7 +625,7 @@ public String generateHashCode(Property property, String result, String thisName if("char".equals(javaTypeName)||"int".equals(javaTypeName)||"short".equals(javaTypeName)||"byte".equals(javaTypeName)) { buf.append( thisValue ); } else if("boolean".equals(javaTypeName)) { - buf.append("(" + thisValue + "?1:0)"); + buf.append("(").append(thisValue).append("?1:0)"); } else { buf.append( "(int) "); buf.append( thisValue ); @@ -646,12 +636,14 @@ public String generateHashCode(Property property, String result, String thisName if(javaTypeName.endsWith("[]")) { if(jdk5) { buf.append( result ) - .append( " = 37 * " ) - .append( result ) - .append( " + " ); - buf.append( "( " ) - .append( getGetterSignature( property ) ) - .append( "() == null ? 0 : " + importType("java.util.Arrays") + ".hashCode(" ) + .append( " = 37 * " ) + .append( result ) + .append( " + " ) + .append("( ") + .append(getGetterSignature(property)) + .append("() == null ? 0 : ") + .append(importType("java.util.Arrays")) + .append(".hashCode(") .append( thisName ) .append( "." ) .append( getGetterSignature( property ) ) @@ -686,7 +678,7 @@ public String generateHashCode(Property property, String result, String thisName private String internalGenerateArrayHashcode(Property property, String javaTypeName, String result, String thisName) { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); String propertyHashVarName = property.getName() + "Hashcode"; String propertyArrayName = property.getName() + "Property"; @@ -718,7 +710,7 @@ private String internalGenerateArrayHashcode(Property property, String javaTypeN .append( " = 1;\n" ); // for (int i=0; i it = c.getProperties().iterator(); - while ( it.hasNext() ) { - Property prop = (Property) it.next(); - if(isRequiredInConstructor(prop)) { - return true; - } - } + } else if (field.getValue() instanceof Component c) { + for (Property prop : c.getProperties()) { + if (isRequiredInConstructor(prop)) { + return true; + } + } } } @@ -854,9 +843,8 @@ protected boolean isRequiredInConstructor(Property field) { public boolean needsMinimalConstructor() { List propClosure = getPropertyClosureForMinimalConstructor(); if(propClosure.isEmpty()) return false; // minimal=default - if(propClosure.equals(getPropertyClosureForFullConstructor())) return false; // minimal=full - return true; - } + return !propClosure.equals(getPropertyClosureForFullConstructor()); // minimal=full + } public boolean needsFullConstructor() { return !getPropertyClosureForFullConstructor().isEmpty(); @@ -877,7 +865,7 @@ public DefaultInitializor(String type, boolean initToZero) { } public String getDefaultValue(String comparator, String genericDeclaration, ImportContext importContext) { - StringBuffer val = new StringBuffer("new " + importContext.importType(type)); + StringBuilder val = new StringBuilder("new " + importContext.importType(type)); if(genericDeclaration!=null) { val.append(genericDeclaration); } @@ -917,10 +905,9 @@ public String getFieldInitialization(Property p, boolean useGenerics) { } if(c2j.getJavaTypeName(p, false)==null) { throw new IllegalArgumentException(); - } else if (p.getValue() instanceof Collection) { - Collection col = (Collection) p.getValue(); - - DefaultInitializor initialization = (DefaultInitializor) col.accept(new DefaultValueVisitor(true) { + } else if (p.getValue() instanceof Collection col) { + + DefaultInitializor initialization = (DefaultInitializor) col.accept(new DefaultValueVisitor(true) { public Object accept(Bag o) { return new DefaultInitializor("java.util.ArrayList", true); @@ -970,7 +957,7 @@ public Object accept(Array o) { } if(useGenerics) { - decl = c2j.getGenericCollectionDeclaration((Collection) p.getValue(), true, importContext); + decl = c2j.getGenericCollectionDeclaration((Collection) p.getValue(), importContext); } return initialization.getDefaultValue(comparator, decl, this); } else { diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/java/Cfg2JavaTool.java b/orm/src/main/java/org/hibernate/tool/internal/export/java/Cfg2JavaTool.java index 63c2eab1c2..6c46a65f01 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/export/java/Cfg2JavaTool.java +++ b/orm/src/main/java/org/hibernate/tool/internal/export/java/Cfg2JavaTool.java @@ -105,11 +105,9 @@ public boolean getMetaAsBool(MetaAttributable pc, String attribute, boolean defa * Convert string into something that can be rendered nicely into a javadoc * comment. * Prefix each line with a star ('*'). - * - * @param string */ public String toJavaDoc(String string, int indent) { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); if ( string != null ) { String[] lines = StringUtil.split( string, "\n\r\f" ); @@ -151,15 +149,6 @@ private String toName(Class c) { } } - /** - * Method that tries to get the typename for a property WITHOUT reflection. - */ - /*public String getJavaTypeName(Property p) { - String javaTypeName = getJavaTypeName( p, false ); - return javaTypeName; - }*/ - - /** * Returns the typename for a property, using generics if this is a Set type and useGenerics is set to true. */ @@ -171,16 +160,16 @@ public String getJavaTypeName(Property p, boolean useGenerics, ImportContext imp String overrideType = getMetaAsString( p, "property-type" ); if ( !StringHelper.isEmpty( overrideType ) ) { String importType = importContext.importType(overrideType); - if ( useGenerics && importType.indexOf( "<" )<0) { + if ( useGenerics && !importType.contains("<")) { if ( p.getValue() instanceof Collection ) { - String decl = getGenericCollectionDeclaration( (Collection) p.getValue(), true, importContext ); + String decl = getGenericCollectionDeclaration( (Collection) p.getValue(), importContext ); return importType + decl; } } return importType; } else { - String rawType = getRawTypeName( p, useGenerics, true, importContext ); + String rawType = getRawTypeName( p, useGenerics, importContext ); if(rawType==null) { throw new IllegalStateException("getJavaTypeName *must* return a value"); } @@ -209,37 +198,34 @@ && new TypeConfiguration() .getRegisteredType(typeName) != null; } - private String getRawTypeName(Property p, boolean useGenerics, boolean preferRawTypeNames, ImportContext importContext) { + private String getRawTypeName(Property p, boolean useGenerics, ImportContext importContext) { Value value = p.getValue(); try { - if ( value instanceof Array ) { // array has a string rep.inside. - Array a = (Array) value; - - if ( a.isPrimitiveArray() ) { + if (value instanceof Array a) { // array has a string rep.inside. + if ( a.isPrimitiveArray() ) { return toName( value.getType().getReturnedClass() ); } else if (a.getElementClassName()!=null){ return a.getElementClassName() + "[]"; } else { - return getJavaTypeName(a.getElement(), preferRawTypeNames) + "[]"; + return getJavaTypeName(a.getElement()) + "[]"; } } - if ( value instanceof Component ) { // same for component. - Component component = ( (Component) value ); - if(component.isDynamic()) return "java.util.Map"; + if (value instanceof Component component) { // same for component. + if(component.isDynamic()) return "java.util.Map"; return component.getComponentClassName(); } if ( useGenerics ) { if ( value instanceof Collection ) { - String decl = getGenericCollectionDeclaration( (Collection) value, preferRawTypeNames, importContext ); - return getJavaTypeName(value, preferRawTypeNames) + decl; + String decl = getGenericCollectionDeclaration( (Collection) value, importContext ); + return getJavaTypeName(value) + decl; } } - return getJavaTypeName( value, preferRawTypeNames ); + return getJavaTypeName( value); } catch (Exception e) { //e.printStackTrace(); @@ -255,37 +241,32 @@ else if (a.getElementClassName()!=null){ } } - public String getGenericCollectionDeclaration(Collection collection, boolean preferRawTypeNames, ImportContext importContext) { + public String getGenericCollectionDeclaration(Collection collection, ImportContext importContext) { Value element = collection.getElement(); - String elementType = importContext.importType(getJavaTypeName(element, preferRawTypeNames)); + String elementType = importContext.importType(getJavaTypeName(element)); String genericDecl = elementType; if(collection.isIndexed()) { IndexedCollection idxCol = (IndexedCollection) collection; if(!idxCol.isList()) { Value idxElement = idxCol.getIndex(); - String indexType = importContext.importType(getJavaTypeName(idxElement, preferRawTypeNames)); + String indexType = importContext.importType(getJavaTypeName(idxElement)); genericDecl = indexType + "," + elementType; } - } - String decl = "<" + genericDecl + ">"; - return decl; + } + return "<" + genericDecl + ">"; } - /** - * @param simpleValue - * @return - */ public Properties getFilteredIdentifierGeneratorProperties(SimpleValue simpleValue) { Properties p = ((EnhancedValue)simpleValue).getIdentifierGeneratorProperties(); return Cfg2HbmTool.getFilteredIdentifierGeneratorProperties(p, new Properties()); } - private String getJavaTypeName(Value value, boolean preferRawTypeNames) { + private String getJavaTypeName(Value value) { return (String) value.accept( new JavaTypeFromValueVisitor() ); } public String asParameterList(Iterator fields, boolean useGenerics, ImportContext ic) { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); while ( fields.hasNext() ) { Property field = (Property)fields.next(); buf.append( getJavaTypeName( field, useGenerics, ic ) ) @@ -305,7 +286,7 @@ public String asParameterList(Iterator fields, boolean useGenerics, ImportCon * TODO: handle this in a template ? */ public String asArgumentList(Iterator fields) { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); while ( fields.hasNext() ) { Property field = (Property)fields.next(); buf.append( keyWordCheck(field.getName()) ); @@ -323,7 +304,7 @@ public String asArgumentList(Iterator fields) { * TODO: handle this in a template ? */ public String asNaturalIdParameterList(PersistentClass clazz) { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); for (Property field : clazz.getRootClass().getProperties()) { if ( field.isNaturalIdentifier() ) { buf.append( getJavaTypeName( field, false ) ) @@ -344,7 +325,7 @@ public String asArgumentList(List fields) { } public String asFinderArgumentList(Map parameterTypes, ImportContext ctx) { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); Iterator> iter = parameterTypes.entrySet().iterator(); while ( iter.hasNext() ) { Entry entry = iter.next(); @@ -356,8 +337,7 @@ public String asFinderArgumentList(Map parameterTypes, ImportCont .getBasicTypeRegistry() .getRegisteredType((String) entry.getValue()); } catch(Throwable t) { - type = null; - typename = (String) entry.getValue(); + typename = (String) entry.getValue(); } } diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/java/ComponentPOJOClass.java b/orm/src/main/java/org/hibernate/tool/internal/export/java/ComponentPOJOClass.java index 1ee2ca1a79..2710370159 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/export/java/ComponentPOJOClass.java +++ b/orm/src/main/java/org/hibernate/tool/internal/export/java/ComponentPOJOClass.java @@ -24,11 +24,15 @@ import java.util.List; import org.hibernate.mapping.Component; +import org.hibernate.mapping.MetaAttribute; import org.hibernate.mapping.Property; +import static org.hibernate.tool.internal.export.java.MetaAttributeConstants.EXTENDS; +import static org.hibernate.tool.internal.export.java.MetaAttributeConstants.IMPLEMENTS; + public class ComponentPOJOClass extends BasicPOJOClass { - private Component clazz; + private final Component clazz; public ComponentPOJOClass(Component component, Cfg2JavaTool cfg) { super(component, cfg); @@ -45,44 +49,38 @@ public String getExtends() { if ( isInterface() ) { if ( clazz.getMetaAttribute( EXTENDS ) != null ) { - if ( !"".equals( extendz ) ) { - extendz += ","; - } - extendz += getMetaAsString( EXTENDS, "," ); + extendz += getMetaAsString( EXTENDS, "," ); } } else if ( clazz.getMetaAttribute( EXTENDS ) != null ) { extendz = getMetaAsString( EXTENDS, "," ); } - return "".equals( extendz ) ? null : extendz; + return extendz.isEmpty() ? null : extendz; } public String getImplements() { List interfaces = new ArrayList(); // implement proxy, but NOT if the proxy is the class it self! + // interfaces can't implement stuff if ( !isInterface() ) { - if ( clazz.getMetaAttribute( IMPLEMENTS ) != null ) { - for (Object value : clazz.getMetaAttribute(IMPLEMENTS).getValues()) { - interfaces.add((String)value); - } + MetaAttribute implementz = clazz.getMetaAttribute( IMPLEMENTS ); + if ( implementz != null ) { + interfaces.addAll(implementz.getValues()); } interfaces.add( Serializable.class.getName() ); // TODO: is this "nice" ? shouldn't it be a user choice ? } - else { - // interfaces can't implement suff - } - if ( interfaces.size() > 0 ) { - StringBuffer sbuf = new StringBuffer(); + if (!interfaces.isEmpty()) { + StringBuilder sb = new StringBuilder(); for ( Iterator iter = interfaces.iterator(); iter.hasNext() ; ) { - //sbuf.append(JavaTool.shortenType(iter.next().toString(), pc.getImports() ) ); - sbuf.append( iter.next() ); - if ( iter.hasNext() ) sbuf.append( "," ); + //sb.append(JavaTool.shortenType(iter.next().toString(), pc.getImports() ) ); + sb.append( iter.next() ); + if ( iter.hasNext() ) sb.append( "," ); } - return sbuf.toString(); + return sb.toString(); } else { return null; diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/java/EntityPOJOClass.java b/orm/src/main/java/org/hibernate/tool/internal/export/java/EntityPOJOClass.java index 6af08e0b29..e57a83a77c 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/export/java/EntityPOJOClass.java +++ b/orm/src/main/java/org/hibernate/tool/internal/export/java/EntityPOJOClass.java @@ -58,9 +58,12 @@ import org.hibernate.tool.internal.util.ValueUtil; import org.hibernate.type.ForeignKeyDirection; +import static org.hibernate.tool.internal.export.java.MetaAttributeConstants.EXTENDS; +import static org.hibernate.tool.internal.export.java.MetaAttributeConstants.IMPLEMENTS; + public class EntityPOJOClass extends BasicPOJOClass { - private PersistentClass clazz; + private final PersistentClass clazz; public EntityPOJOClass(PersistentClass clazz, Cfg2JavaTool cfg) { super(clazz, cfg); @@ -83,17 +86,14 @@ public String getExtends() { extendz = clazz.getSuperclass().getClassName(); } if ( clazz.getMetaAttribute( EXTENDS ) != null ) { - if ( !"".equals( extendz ) ) { + if ( !extendz.isEmpty() ) { extendz += ","; } extendz += getMetaAsString( EXTENDS, "," ); } } else if ( clazz.getSuperclass() != null ) { - if ( c2j.getPOJOClass(clazz.getSuperclass()).isInterface() ) { - // class cannot extend it's superclass because the superclass is marked as an interface - } - else { + if (!( c2j.getPOJOClass(clazz.getSuperclass()).isInterface() )) { extendz = clazz.getSuperclass().getClassName(); } } @@ -101,7 +101,7 @@ else if ( clazz.getMetaAttribute( EXTENDS ) != null ) { extendz = getMetaAsString( EXTENDS, "," ); } - return "".equals( extendz ) ? null : extendz; + return extendz.isEmpty() ? null : extendz; } @@ -122,13 +122,9 @@ public String getImplements() { } interfaces.add( Serializable.class.getName() ); // TODO: is this "nice" ? shouldn't it be a user choice ? } - else { - // interfaces can't implement suff - } - - if ( interfaces.size() > 0 ) { - StringBuffer sbuf = new StringBuffer(); + if (!interfaces.isEmpty()) { + StringBuilder sbuf = new StringBuilder(); for ( Iterator iter = interfaces.iterator(); iter.hasNext() ; ) { //sbuf.append(JavaTool.shortenType(iter.next().toString(), pc.getImports() ) ); sbuf.append( iter.next() ); @@ -170,14 +166,9 @@ else if ( pc.hasEmbeddedIdentifier() ) { List pl = pc.getProperties(); for(Property element : pl) { - if ( element.getValue() instanceof Component + if ( element.getValue() instanceof Component component && element.getPropertyAccessorName().equals( "embedded" )) { - Component component = (Component) element.getValue(); - // need to "explode" property to get proper sequence in java code. - List embeddedProperties = component.getProperties(); - for(Property p : embeddedProperties) { - properties.add(p); - } + properties.addAll(component.getProperties()); } else { properties.add(element); } @@ -240,11 +231,10 @@ public String generateAnnIdGenerator() { wholeString.append( AnnotationBuilder.createAnnotation( importType("jakarta.persistence.EmbeddedId") ).getResult()); } - else if ( identifier instanceof EnhancedBasicValue ) { - EnhancedBasicValue enhancedBasicValue = (EnhancedBasicValue) identifier; - strategy = enhancedBasicValue.getIdentifierGeneratorStrategy(); + else if (identifier instanceof EnhancedBasicValue enhancedBasicValue) { + strategy = enhancedBasicValue.getIdentifierGeneratorStrategy(); properties = c2j.getFilteredIdentifierGeneratorProperties(enhancedBasicValue); - StringBuffer idResult = new StringBuffer(); + StringBuilder idResult = new StringBuilder(); AnnotationBuilder builder = AnnotationBuilder.createAnnotation( importType("jakarta.persistence.Id") ); idResult.append(builder.getResult()); idResult.append(" "); @@ -259,6 +249,11 @@ else if ( identifier instanceof EnhancedBasicValue ) { idResult.append(builder.getResult()); } else if ( "sequence".equals( strategy ) ) { + String sequenceGeneratorName = null; + if (properties != null) { + sequenceGeneratorName = properties.getProperty( + org.hibernate.id.enhanced.SequenceStyleGenerator.SEQUENCE_PARAM, null ); + } builder.resetAnnotation( importType("jakarta.persistence.GeneratedValue") ) .addAttribute( "strategy", staticImport("jakarta.persistence.GenerationType", "SEQUENCE" ) ) .addQuotedAttribute( "generator", clazz.getClassName()+"IdGenerator" ); @@ -266,7 +261,7 @@ else if ( "sequence".equals( strategy ) ) { builder.resetAnnotation( importType("jakarta.persistence.SequenceGenerator") ) .addQuotedAttribute( "name", clazz.getClassName()+"IdGenerator" ) - .addQuotedAttribute( "sequenceName", properties.getProperty( org.hibernate.id.enhanced.SequenceStyleGenerator.SEQUENCE_PARAM, null ) ); + .addQuotedAttribute( "sequenceName", sequenceGeneratorName ); // TODO HA does not support initialValue and allocationSize wholeString.append( builder.getResult() ); } @@ -319,46 +314,49 @@ private void buildAnnTableGenerator(StringBuffer wholeString, Properties propert AnnotationBuilder builder = AnnotationBuilder.createAnnotation( importType("jakarta.persistence.TableGenerator") ); builder.addQuotedAttribute( "name", clazz.getClassName()+"IdGenerator" ); builder.addQuotedAttribute( "table", properties.getProperty( "generatorTableName", "hibernate_sequences" ) ); - if ( ! isPropertyDefault( PersistentIdentifierGenerator.CATALOG, properties ) ) { + if (propertyDoesNotHaveDefaultValue( PersistentIdentifierGenerator.CATALOG, properties ) ) { builder.addQuotedAttribute( "catalog", properties.getProperty( PersistentIdentifierGenerator.CATALOG, "") ); } - if ( ! isPropertyDefault( PersistentIdentifierGenerator.SCHEMA, properties ) ) { + if (propertyDoesNotHaveDefaultValue( PersistentIdentifierGenerator.SCHEMA, properties ) ) { builder.addQuotedAttribute( "schema", properties.getProperty( PersistentIdentifierGenerator.SCHEMA, "") ); } - if (! isPropertyDefault( TableGenerator.SEGMENT_VALUE_PARAM, properties ) ) { + if (propertyDoesNotHaveDefaultValue( TableGenerator.SEGMENT_VALUE_PARAM, properties ) ) { builder.addQuotedAttribute( "pkColumnValue", properties.getProperty( TableGenerator.SEGMENT_VALUE_PARAM, "") ); } - if ( ! isPropertyDefault( TableGenerator.INCREMENT_PARAM, properties, "50" ) ) { + if (propertyDoesNotHaveDefaultValue( TableGenerator.INCREMENT_PARAM, properties, "50" ) ) { builder.addAttribute( "allocationSize", properties.getProperty( TableGenerator.INCREMENT_PARAM, "50" ) ); } - if (! isPropertyDefault( TableGenerator.SEGMENT_COLUMN_PARAM, properties ) ) { + if (propertyDoesNotHaveDefaultValue( TableGenerator.SEGMENT_COLUMN_PARAM, properties ) ) { builder.addQuotedAttribute( "pkColumnName", properties.getProperty( TableGenerator.SEGMENT_COLUMN_PARAM, "") ); } - if (! isPropertyDefault( TableGenerator.VALUE_COLUMN_PARAM, properties ) ) { + if (propertyDoesNotHaveDefaultValue( TableGenerator.VALUE_COLUMN_PARAM, properties) ) { builder.addQuotedAttribute( "valueColumnName", properties.getProperty( TableGenerator.VALUE_COLUMN_PARAM, "") ); } - wholeString.append( builder.getResult() + "\n " ); + wholeString.append(builder.getResult()).append("\n "); } - private boolean isPropertyDefault(String property, Properties properties) { - return StringHelper.isEmpty( properties.getProperty( property ) ); + private boolean propertyDoesNotHaveDefaultValue(String property, Properties properties) { + return propertyDoesNotHaveDefaultValue(property, properties, null); } - private boolean isPropertyDefault(String property, Properties properties, String defaultValue) { - String propertyValue = properties.getProperty( property ); - return propertyValue != null && propertyValue.equals( defaultValue ); + private boolean propertyDoesNotHaveDefaultValue(String property, Properties properties, String defaultValue) { + String propertyValue = properties.getProperty(property); + if (defaultValue == null) { + return StringHelper.isNotEmpty(propertyValue); + } else { + return !defaultValue.equals(propertyValue); + } } public String generateJoinColumnsAnnotation(Property property, Metadata md) { boolean insertable = property.isInsertable(); - boolean updatable = property.isUpdateable(); + boolean updatable = property.isUpdatable(); Value value = property.getValue(); int span; Iterator selectablesIterator; Iterator referencedSelectablesIterator = null; - if (value != null && value instanceof Collection) { - Collection collection = (Collection) value; - span = collection.getKey().getColumnSpan(); + if (value instanceof Collection collection) { + span = collection.getKey().getColumnSpan(); selectablesIterator = collection.getKey().getSelectables().iterator(); } else { @@ -380,16 +378,18 @@ public String generateJoinColumnsAnnotation(Property property, Metadata md) { buildJoinColumnAnnotation( selectable, null, annotations, insertable, updatable ); } else { - Iterator selectables = selectablesIterator; - annotations.append("@").append( importType("jakarta.persistence.JoinColumns") ).append("( { " ); - buildArrayOfJoinColumnAnnotation( selectables, referencedSelectablesIterator, annotations, insertable, updatable ); + annotations.append("@").append( importType("jakarta.persistence.JoinColumns") ).append("( { " ); + buildArrayOfJoinColumnAnnotation(selectablesIterator, referencedSelectablesIterator, annotations, insertable, updatable ); annotations.append( " } )" ); } return annotations.toString(); } private void buildArrayOfJoinColumnAnnotation( - Iterator columns, Iterator referencedColumnsIterator, StringBuffer annotations, boolean insertable, + Iterator columns, + Iterator referencedColumnsIterator, + StringBuffer annotations, + boolean insertable, boolean updatable ) { while ( columns.hasNext() ) { @@ -399,11 +399,8 @@ private void buildArrayOfJoinColumnAnnotation( referencedColumn = referencedColumnsIterator.next(); } - if ( selectable.isFormula() ) { - //TODO formula in multicolumns not supported by annotations - //annotations.append("/* TODO formula in multicolumns not supported by annotations */"); - } - else { + //TODO formula in multicolumns not supported by annotations + if (!( selectable.isFormula() )) { annotations.append( "\n " ); buildJoinColumnAnnotation( selectable, referencedColumn, annotations, insertable, updatable ); annotations.append( ", " ); @@ -413,12 +410,13 @@ private void buildArrayOfJoinColumnAnnotation( } private void buildJoinColumnAnnotation( - Selectable selectable, Selectable referencedColumn, StringBuffer annotations, boolean insertable, boolean updatable - ) { - if ( selectable.isFormula() ) { - //TODO not supported by HA - } - else { + Selectable selectable, + Selectable referencedColumn, + StringBuffer annotations, + boolean insertable, + boolean updatable) { + //TODO not supported by HA + if (!( selectable.isFormula() )) { Column column = (Column) selectable; annotations.append("@").append( importType("jakarta.persistence.JoinColumn") ) .append("(name=\"" ).append( column.getName() ).append( "\"" ); @@ -438,32 +436,22 @@ public String[] getCascadeTypes(Property property) { List types = new ArrayList(); while ( st.hasMoreElements() ) { String element = ( (String) st.nextElement() ).toLowerCase(); - if ( "persist".equals( element ) ) { - types.add(importType( "jakarta.persistence.CascadeType" ) + ".PERSIST"); - } - else if ( "merge".equals( element ) ) { - types.add(importType( "jakarta.persistence.CascadeType") + ".MERGE"); - } - else if ( "delete".equals( element ) ) { - types.add(importType( "jakarta.persistence.CascadeType") + ".REMOVE"); - } - else if ( "refresh".equals( element ) ) { - types.add(importType( "jakarta.persistence.CascadeType") + ".REFRESH"); - } - else if ( "all".equals( element ) ) { - types.add(importType( "jakarta.persistence.CascadeType") + ".ALL"); - } + switch (element) { + case "persist" -> types.add(importType("jakarta.persistence.CascadeType") + ".PERSIST"); + case "merge" -> types.add(importType("jakarta.persistence.CascadeType") + ".MERGE"); + case "delete" -> types.add(importType("jakarta.persistence.CascadeType") + ".REMOVE"); + case "refresh" -> types.add(importType("jakarta.persistence.CascadeType") + ".REFRESH"); + case "all" -> types.add(importType("jakarta.persistence.CascadeType") + ".ALL"); + } } - return (String[]) types.toArray( new String[types.size()] ); + return types.toArray(new String[0]); } public String generateManyToOneAnnotation(Property property) { - StringBuffer buffer = new StringBuffer(AnnotationBuilder.createAnnotation( importType("jakarta.persistence.ManyToOne") ) - .addAttribute( "cascade", getCascadeTypes(property)) - .addAttribute( "fetch", getFetchType(property)) - .getResult()); - buffer.append(getHibernateCascadeTypeAnnotation(property)); - return buffer.toString(); + return AnnotationBuilder.createAnnotation(importType("jakarta.persistence.ManyToOne")) + .addAttribute("cascade", getCascadeTypes(property)) + .addAttribute("fetch", getFetchType(property)) + .getResult() + getHibernateCascadeTypeAnnotation(property); } public boolean isSharedPkBasedOneToOne(OneToOne oneToOne){ @@ -473,14 +461,13 @@ public boolean isSharedPkBasedOneToOne(OneToOne oneToOne){ joinSelectables.add( joinSelectablesIt.next() ); } - if ( joinSelectables.size() == 0 ) + if (joinSelectables.isEmpty()) return false; - Iterator idSelectablesIt = getIdentifierProperty().getSelectables().iterator(); - while ( idSelectablesIt.hasNext() ) { - if (!joinSelectables.contains(idSelectablesIt.next()) ) - return false; - } + for (Selectable selectable : getIdentifierProperty().getSelectables()) { + if (!joinSelectables.contains(selectable)) + return false; + } return true; } @@ -498,7 +485,7 @@ public String generateOneToOneAnnotation(Property property, Metadata md) { ab.addQuotedAttribute("mappedBy", getOneToOneMappedBy(md, oneToOne)); } - StringBuffer buffer = new StringBuffer(ab.getResult()); + StringBuilder buffer = new StringBuilder(ab.getResult()); buffer.append(getHibernateCascadeTypeAnnotation(property)); if ( pkIsAlsoFk && oneToOne.getForeignKeyType().equals(ForeignKeyDirection.FROM_PARENT) ){ @@ -512,34 +499,36 @@ public String generateOneToOneAnnotation(Property property, Metadata md) { public String getHibernateCascadeTypeAnnotation(Property property) { StringTokenizer st = new StringTokenizer( property.getCascade(), ", ", false ); String cascadeType = null; - StringBuffer cascade = new StringBuffer(); + StringBuilder cascade = new StringBuilder(); while ( st.hasMoreElements() ) { String element = ( (String) st.nextElement() ).toLowerCase(); - if ( "all-delete-orphan".equals( element ) ) { - if (cascadeType == null) cascadeType = importType( "org.hibernate.annotations.CascadeType"); - cascade.append( cascadeType ).append(".ALL").append(", ") - .append( cascadeType ).append(".DELETE_ORPHAN").append(", "); - } - else if ( "delete-orphan".equals( element ) ) { - if (cascadeType == null) cascadeType = importType( "org.hibernate.annotations.CascadeType"); - cascade.append( cascadeType ).append(".DELETE_ORPHAN").append(", "); - } - else if ( "save-update".equals( element ) ) { - if (cascadeType == null) cascadeType = importType( "org.hibernate.annotations.CascadeType"); - cascade.append( cascadeType ).append(".MERGE").append(", "); - } - else if ( "replicate".equals( element ) ) { - if (cascadeType == null) cascadeType = importType( "org.hibernate.annotations.CascadeType"); - cascade.append( cascadeType ).append(".REPLICATE").append(", "); - } - else if ( "lock".equals( element ) ) { - if (cascadeType == null) cascadeType = importType( "org.hibernate.annotations.CascadeType"); - cascade.append( cascadeType ).append(".LOCK").append(", "); - } - else if ( "evict".equals( element ) ) { - if (cascadeType == null) cascadeType = importType( "org.hibernate.annotations.CascadeType"); - cascade.append( cascadeType ).append(".EVICT").append(", "); - } + switch (element) { + case "all-delete-orphan" -> { + if (cascadeType == null) cascadeType = importType("org.hibernate.annotations.CascadeType"); + cascade.append(cascadeType).append(".ALL").append(", ") + .append(cascadeType).append(".DELETE_ORPHAN").append(", "); + } + case "delete-orphan" -> { + if (cascadeType == null) cascadeType = importType("org.hibernate.annotations.CascadeType"); + cascade.append(cascadeType).append(".DELETE_ORPHAN").append(", "); + } + case "save-update" -> { + if (cascadeType == null) cascadeType = importType("org.hibernate.annotations.CascadeType"); + cascade.append(cascadeType).append(".MERGE").append(", "); + } + case "replicate" -> { + if (cascadeType == null) cascadeType = importType("org.hibernate.annotations.CascadeType"); + cascade.append(cascadeType).append(".REPLICATE").append(", "); + } + case "lock" -> { + if (cascadeType == null) cascadeType = importType("org.hibernate.annotations.CascadeType"); + cascade.append(cascadeType).append(".LOCK").append(", "); + } + case "evict" -> { + if (cascadeType == null) cascadeType = importType("org.hibernate.annotations.CascadeType"); + cascade.append(cascadeType).append(".EVICT").append(", "); + } + } } if ( cascade.length() >= 2 ) { String hibernateCascade = importType("org.hibernate.annotations.Cascade"); @@ -579,9 +568,8 @@ public Object getDecoratedObject() { public String generateCollectionAnnotation(Property property, Metadata md) { StringBuffer annotation = new StringBuffer(); Value value = property.getValue(); - if ( value != null && value instanceof Collection) { - Collection collection = (Collection) value; - if ( collection.isOneToMany() ) { + if (value instanceof Collection collection) { + if ( collection.isOneToMany() ) { String mappedBy = null; AnnotationBuilder ab = AnnotationBuilder.createAnnotation( importType( "jakarta.persistence.OneToMany") ); ab.addAttribute( "cascade", getCascadeTypes( property ) ); @@ -621,7 +609,7 @@ public String generateCollectionAnnotation(Property property, Metadata md) { annotation.append(", catalog=\"").append( table.getCatalog() ).append("\""); } String uniqueConstraint = generateAnnTableUniqueConstraint(table); - if ( uniqueConstraint.length() > 0 ) { + if (!uniqueConstraint.isEmpty()) { annotation.append(", uniqueConstraints=").append(uniqueConstraint); } annotation.append( ", joinColumns = { "); @@ -630,7 +618,7 @@ public String generateCollectionAnnotation(Property property, Metadata md) { null, annotation, property.isInsertable(), - property.isUpdateable() + property.isUpdatable() ); annotation.append( " }"); annotation.append( ", inverseJoinColumns = { "); @@ -639,7 +627,7 @@ public String generateCollectionAnnotation(Property property, Metadata md) { null, annotation, property.isInsertable(), - property.isUpdateable() + property.isUpdatable() ); annotation.append( " }"); annotation.append(")"); @@ -647,7 +635,7 @@ public String generateCollectionAnnotation(Property property, Metadata md) { } String hibernateCascade = getHibernateCascadeTypeAnnotation( property ); - if (hibernateCascade.length() > 0) annotation.append("\n ").append(hibernateCascade); + if (!hibernateCascade.isEmpty()) annotation.append("\n ").append(hibernateCascade); } return annotation.toString(); } @@ -668,19 +656,16 @@ private String getManyToManyMappedBy(Metadata md, Collection collection) { while ( ! isOtherSide && properties.hasNext() ) { Property collectionProperty = properties.next(); Value collectionValue = collectionProperty.getValue(); - if ( collectionValue != null && collectionValue instanceof Collection ) { - Collection realCollectionValue = (Collection) collectionValue; - if ( ! realCollectionValue.isOneToMany() ) { + if (collectionValue instanceof Collection realCollectionValue) { + if ( ! realCollectionValue.isOneToMany() ) { if ( joinColumns.size() == realCollectionValue.getElement().getColumnSpan() ) { isOtherSide = true; - Iterator it = realCollectionValue.getElement().getSelectables().iterator(); - while ( it.hasNext() ) { - Selectable selectable = it.next(); - if (! joinColumns.contains( selectable ) ) { - isOtherSide = false; - break; - } - } + for (Selectable selectable : realCollectionValue.getElement().getSelectables()) { + if (!joinColumns.contains(selectable)) { + isOtherSide = false; + break; + } + } if (isOtherSide) { mappedBy = collectionProperty.getName(); } @@ -707,17 +692,15 @@ private String getOneToManyMappedBy(Metadata md, Collection collection) { while ( ! isOtherSide && properties.hasNext() ) { Property manyProperty = properties.next(); Value manyValue = manyProperty.getValue(); - if ( manyValue != null && manyValue instanceof ManyToOne ) { + if (manyValue instanceof ManyToOne) { if ( joinColumns.size() == manyValue.getColumnSpan() ) { isOtherSide = true; - Iterator it = manyValue.getSelectables().iterator(); - while ( it.hasNext() ) { - Selectable selectable = it.next(); - if (! joinColumns.contains( selectable ) ) { - isOtherSide = false; - break; - } - } + for (Selectable selectable : manyValue.getSelectables()) { + if (!joinColumns.contains(selectable)) { + isOtherSide = false; + break; + } + } if (isOtherSide) { mappedBy = manyProperty.getName(); } @@ -749,17 +732,15 @@ private String getOneToOneMappedBy(Metadata md, OneToOne oneToOne) { while ( ! isOtherSide && properties.hasNext() ) { Property oneProperty = properties.next(); Value manyValue = oneProperty.getValue(); - if ( manyValue != null && ( manyValue instanceof OneToOne || manyValue instanceof ManyToOne ) ) { + if ((manyValue instanceof OneToOne || manyValue instanceof ManyToOne)) { if ( joinSelectables.size() == manyValue.getColumnSpan() ) { isOtherSide = true; - Iterator it = manyValue.getSelectables().iterator(); - while ( it.hasNext() ) { - Selectable selectable = it.next(); - if (! joinSelectables.contains( selectable ) ) { - isOtherSide = false; - break; - } - } + for (Selectable selectable : manyValue.getSelectables()) { + if (!joinSelectables.contains(selectable)) { + isOtherSide = false; + break; + } + } if (isOtherSide) { mappedBy = oneProperty.getName(); } @@ -815,15 +796,13 @@ private boolean isFormula(Property field) { boolean foundFormula = false; if(value!=null && value.getColumnSpan()>0) { - Iterator selectablesIterator = value.getSelectables().iterator(); - while ( selectablesIterator.hasNext() ) { - Selectable element = selectablesIterator.next(); - if(!(element instanceof Formula)) { - return false; - } else { - foundFormula = true; - } - } + for (Selectable element : value.getSelectables()) { + if (!(element instanceof Formula)) { + return false; + } else { + foundFormula = true; + } + } } else { return false; } @@ -885,16 +864,11 @@ protected List getPropertiesForMinimalConstructor(PersistentClass pc) protected boolean isAssignedIdentifier(PersistentClass pc, Property property) { if(property.equals(pc.getIdentifierProperty())) { - if(property.getValue() instanceof EnhancedValue) { - EnhancedValue sv = (EnhancedValue) property.getValue(); - if("assigned".equals(sv.getIdentifierGeneratorStrategy())) { - return true; - } + if(property.getValue() instanceof EnhancedValue sv) { + return "assigned".equals(sv.getIdentifierGeneratorStrategy()); } else if (property.getValue().isSimpleValue()) { ValueUtil v = new ValueUtil((SimpleValue)property.getValue()); - if("assigned".equals(v.getIdentifierGeneratorStrategy())) { - return true; - } + return "assigned".equals(v.getIdentifierGeneratorStrategy()); } } return false; From d55ee1b5c01f89ff4c2f8e48d35a4d95f5fb05ff Mon Sep 17 00:00:00 2001 From: Koen Aers Date: Wed, 29 Oct 2025 15:26:30 +0100 Subject: [PATCH 2/2] HBX-3197: Improve the implementation of classes Cfg2HbmTool, DocHelper and DocFolder Signed-off-by: Koen Aers --- .../tool/internal/export/doc/DocFolder.java | 13 +- .../tool/internal/export/doc/DocHelper.java | 180 +++++++----------- .../tool/internal/export/hbm/Cfg2HbmTool.java | 127 +++++------- 3 files changed, 127 insertions(+), 193 deletions(-) diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/doc/DocFolder.java b/orm/src/main/java/org/hibernate/tool/internal/export/doc/DocFolder.java index eb72da8176..0eaf0caf1a 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/export/doc/DocFolder.java +++ b/orm/src/main/java/org/hibernate/tool/internal/export/doc/DocFolder.java @@ -41,17 +41,15 @@ public class DocFolder { /** * The File instance. */ - private File file; + private final File file; /** * Holds a list with the folders that are between this folder and root. */ - private List pathFolders = new ArrayList(); + private final List pathFolders = new ArrayList<>(); /** * Constructor for the root folder. - * - * @param pFileRoot the File that represents the root for the documentation. */ public DocFolder(File root) { super(); @@ -100,11 +98,8 @@ public DocFolder(String pName, DocFolder pParent) { + file.getAbsolutePath() ); } } - - if (parent != null) { - pathFolders.addAll(parent.getPathFolders() ); - pathFolders.add(this); - } + pathFolders.addAll(parent.getPathFolders() ); + pathFolders.add(this); } /** diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/doc/DocHelper.java b/orm/src/main/java/org/hibernate/tool/internal/export/doc/DocHelper.java index 43aef36c3b..bf61e16c0d 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/export/doc/DocHelper.java +++ b/orm/src/main/java/org/hibernate/tool/internal/export/doc/DocHelper.java @@ -82,47 +82,47 @@ public int compare(Property left, Property right) { * Map with Tables keyed by Schema FQN. The keys are Strings and the values * are Lists of Tables */ - private Map> tablesBySchema = + private final Map> tablesBySchema = new HashMap>(); /** * Map with classes keyed by package name. PackageName is String key and * values are List of POJOClass */ - private Map> classesByPackage = + private final Map> classesByPackage = new HashMap>(); /** * Lits of all POJOClass */ - private List classes = + private final List classes = new ArrayList(); /** * Map where the keys are column names (tableFQN.column) and the values are * lists with the Value instances where those columns referenced. */ - private Map> valuesByColumn = + private final Map> valuesByColumn = new HashMap>(); /** * Holds intances of Property keyed by Value objects. */ - private Map> propsByValue = + private final Map> propsByValue = new HashMap>(); /** * List with all the tables. */ - private List tables = new ArrayList
(); + private final List
tables = new ArrayList
(); /** * Map that holds the Schema FQN for each Table. The keys are Table * instances and the values are Strings with the Schema FQN for that table. */ - private Map tableSchemaNames = new HashMap(); + private final Map tableSchemaNames = new HashMap(); - private Metadata metadata; + private final Metadata metadata; public DocHelper(Metadata metadata, Properties properties, Cfg2JavaTool cfg2JavaTool) { @@ -141,107 +141,80 @@ public DocHelper(Metadata metadata, Properties properties, Cfg2JavaTool cfg2Java if (defaultSchema == null) { defaultSchema = DEFAULT_NO_SCHEMA_NAME; } - - Iterator
tablesIter = metadata.collectTableMappings().iterator(); - while (tablesIter.hasNext()) { - Table table = tablesIter.next(); + for (Table table : metadata.collectTableMappings()) { + if (!table.isPhysicalTable()) { + continue; + } + tables.add(table); - if (!table.isPhysicalTable()) { - continue; - } - tables.add(table); + StringBuilder sb = new StringBuilder(); - StringBuffer sb = new StringBuffer(); + String catalog = table.getCatalog(); + if (catalog == null) { + catalog = defaultCatalog; + } + if (catalog != null) { + sb.append(catalog).append("."); + } - String catalog = table.getCatalog(); - if (catalog == null) { - catalog = defaultCatalog; - } - if (catalog != null) { - sb.append(catalog + "."); - } + String schema = table.getSchema(); + if (schema == null) { + schema = defaultSchema; + } - String schema = table.getSchema(); - if (schema == null) { - schema = defaultSchema; - } + sb.append(schema); - sb.append(schema); + String qualSchemaName = sb.toString(); - String qualSchemaName = sb.toString(); + tableSchemaNames.put(table, qualSchemaName); - tableSchemaNames.put(table, qualSchemaName); + List
tableList = tablesBySchema.computeIfAbsent(qualSchemaName, k -> new ArrayList<>()); + tableList.add(table); - List
tableList = tablesBySchema.get(qualSchemaName); - if (tableList == null) { - tableList = new ArrayList
(); - tablesBySchema.put(qualSchemaName, tableList); - } - tableList.add(table); - - for(Column column : table.getColumns()) { - String columnFQN = getQualifiedColumnName(table, column); - List values = valuesByColumn.get(columnFQN); - if (values == null) { - values = new ArrayList(); - valuesByColumn.put(columnFQN, values); - } - values.add(column.getValue()); - } - } + for (Column column : table.getColumns()) { + String columnFQN = getQualifiedColumnName(table, column); + List values = valuesByColumn.computeIfAbsent(columnFQN, k -> new ArrayList<>()); + values.add(column.getValue()); + } + } Map components = new HashMap(); - Iterator classesItr = metadata.getEntityBindings().iterator(); - while (classesItr.hasNext()) { - PersistentClass clazz = classesItr.next(); + for (PersistentClass clazz : metadata.getEntityBindings()) { + POJOClass pojoClazz = cfg2JavaTool.getPOJOClass(clazz); + ConfigurationNavigator.collectComponents(components, pojoClazz); - POJOClass pojoClazz = cfg2JavaTool.getPOJOClass(clazz); - ConfigurationNavigator.collectComponents(components, pojoClazz); + this.processClass(pojoClazz); - this.processClass(pojoClazz); + for (Property property : clazz.getProperties()) { + Value value = property.getValue(); + List props = propsByValue.computeIfAbsent(value, k -> new ArrayList<>()); + props.add(property); + } + } - for (Property property : clazz.getProperties()) { - Value value = property.getValue(); - List props = propsByValue.get(value); - if (props == null) { - props = new ArrayList(); - propsByValue.put(value, props); - } - props.add(property); - } - } - - Iterator iterator = components.values().iterator(); - while (iterator.hasNext()) { - Component component = (Component) iterator.next(); - ComponentPOJOClass element = - new ComponentPOJOClass(component, cfg2JavaTool); - this.processClass(element); - } + for (Component component : components.values()) { + ComponentPOJOClass element = + new ComponentPOJOClass(component, cfg2JavaTool); + this.processClass(element); + } } /** * Populate classes List and classesByPackage Map - * - * @param pojoClazz */ private void processClass(POJOClass pojoClazz) { classes.add(pojoClazz); String packageName = pojoClazz.getPackageName(); - if ("".equals(packageName)) { + if (packageName == null || packageName.isEmpty()) { packageName = DEFAULT_NO_PACKAGE; } - List classList = classesByPackage.get(packageName); - if (classList == null) { - classList = new ArrayList(); - classesByPackage.put(packageName, classList); - } - classList.add(pojoClazz); + List classList = classesByPackage.computeIfAbsent(packageName, k -> new ArrayList()); + classList.add(pojoClazz); } /** @@ -257,8 +230,6 @@ public Map> getTablesBySchema() { /** * return a Map which has List of POJOClass as value keyed by package name * as String. - * - * @return */ public Map> getClassesByPackage() { return classesByPackage; @@ -277,8 +248,6 @@ public List getSchemas() { /** * Return a sorted List of packages - * - * @return */ public List getPackages() { List packages = new ArrayList(classesByPackage.keySet()); @@ -295,8 +264,7 @@ public List getPackages() { * @return a list with all the tables. */ public List
getTables(String schema) { - List
list = tablesBySchema.get(schema); - return list; + return tablesBySchema.get(schema); } /** @@ -309,7 +277,7 @@ public List
getTables(String schema) { public List getClasses(String packageName) { List clazzes = classesByPackage.get(packageName); List orderedClasses = new ArrayList(clazzes); - Collections.sort(orderedClasses, POJOCLASS_COMPARATOR); + orderedClasses.sort(POJOCLASS_COMPARATOR); return orderedClasses; } @@ -324,12 +292,10 @@ public List
getTables() { /** * Return a sorted List of all POJOClass - * - * @return */ public List getClasses() { List orderedClasses = new ArrayList(classes); - Collections.sort(orderedClasses, POJOCLASS_COMPARATOR); + orderedClasses.sort(POJOCLASS_COMPARATOR); return orderedClasses; } @@ -422,14 +388,14 @@ public int getLength(Column column) { public int getPrecision(Column column) { return column.getPrecision() == null ? - TypeUtils.DEFAULT_COLUMN_PRECISION : - column.getPrecision().intValue(); + TypeUtils.DEFAULT_COLUMN_PRECISION : + column.getPrecision(); } public int getScale(Column column) { return column.getScale() == null ? - TypeUtils.DEFAULT_COLUMN_SCALE : - column.getScale().intValue(); + TypeUtils.DEFAULT_COLUMN_SCALE : + column.getScale(); } public Iterator getPrimaryKeyColumnIterator(Table table) { @@ -469,14 +435,12 @@ public List getValues(Table table, Column column) { public List getProperties(Table table, Column column) { List result = new ArrayList(); - Iterator values = getValues(table, column).iterator(); - while (values.hasNext()) { - Value value = values.next(); - List props = propsByValue.get(value); - if (props != null) { - result.addAll(props); - } - } + for (Value value : getValues(table, column)) { + List props = propsByValue.get(value); + if (props != null) { + result.addAll(props); + } + } return result; } @@ -490,10 +454,8 @@ public List getProperties(Table table, Column column) { */ // TODO We haven't taken into account Array? public POJOClass getComponentPOJO(Property property) { - if (property.getValue() instanceof Component) { - Component comp = (Component) property.getValue(); - ComponentPOJOClass componentPOJOClass = new ComponentPOJOClass(comp, new Cfg2JavaTool()); - return componentPOJOClass; + if (property.getValue() instanceof Component comp) { + return new ComponentPOJOClass(comp, new Cfg2JavaTool()); } else { return null; } @@ -515,7 +477,7 @@ public List getInheritanceHierarchy(POJOClass pc) { public List getOrderedProperties(POJOClass pojoClass) { List orderedProperties = getAllProperties(pojoClass); - Collections.sort(orderedProperties, PROPERTY_COMPARATOR); + orderedProperties.sort(PROPERTY_COMPARATOR); return orderedProperties; } @@ -532,7 +494,7 @@ public List getSimpleProperties(POJOClass pojoClass) { public List getOrderedSimpleProperties(POJOClass pojoClass) { List orderedProperties = getSimpleProperties(pojoClass); - Collections.sort(orderedProperties, PROPERTY_COMPARATOR); + orderedProperties.sort(PROPERTY_COMPARATOR); return orderedProperties; } diff --git a/orm/src/main/java/org/hibernate/tool/internal/export/hbm/Cfg2HbmTool.java b/orm/src/main/java/org/hibernate/tool/internal/export/hbm/Cfg2HbmTool.java index b6620085fd..7f87bc222d 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/export/hbm/Cfg2HbmTool.java +++ b/orm/src/main/java/org/hibernate/tool/internal/export/hbm/Cfg2HbmTool.java @@ -31,7 +31,6 @@ import org.hibernate.cfg.Environment; import org.hibernate.engine.OptimisticLockStyle; import org.hibernate.engine.spi.FilterDefinition; -import org.hibernate.id.PersistentIdentifierGenerator; import org.hibernate.mapping.Any; import org.hibernate.mapping.Collection; import org.hibernate.mapping.Column; @@ -66,7 +65,7 @@ */ public class Cfg2HbmTool { - private final class HasEntityPersisterVisitor implements PersistentClassVisitor { + private static final class HasEntityPersisterVisitor implements PersistentClassVisitor { private final String name; private HasEntityPersisterVisitor(String name) { @@ -78,7 +77,7 @@ public Object accept(Subclass subclass) { } private Object bool(boolean b) { - return Boolean.valueOf( b ); + return b; } public Object accept(JoinedSubclass subclass) { @@ -100,31 +99,27 @@ public Object accept(RootClass class1) { /** * Remove any internal keys from the set, eg, any Keys that are prefixed by - * 'target_', {@link PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER} and return the filtered collection. - * - * @param properties - * @return + * 'target_' and return the filtered collection. */ public static Properties getFilteredIdentifierGeneratorProperties(Properties properties, Properties environmentProperties) { if (properties != null){ Properties fProp = new Properties(); - Iterator itr = properties.keySet().iterator(); - while (itr.hasNext() ) { - String key = (String) itr.next(); - if ("schema".equals(key)) { - String schema = properties.getProperty(key); - if (!isDefaultSchema(schema, environmentProperties)) { - fProp.put(key, schema); - } - } else if ("catalog".equals(key)) { - String catalog = properties.getProperty(key); - if (!isDefaultCatalog(catalog, environmentProperties)) { - fProp.put(key, catalog); - } - } else if (! key.startsWith("target_")) { - fProp.put(key, properties.get(key)); - } - } + for (Object o : properties.keySet()) { + String key = (String) o; + if ("schema".equals(key)) { + String schema = properties.getProperty(key); + if (!isDefaultSchema(schema, environmentProperties)) { + fProp.put(key, schema); + } + } else if ("catalog".equals(key)) { + String catalog = properties.getProperty(key); + if (!isDefaultCatalog(catalog, environmentProperties)) { + fProp.put(key, catalog); + } + } else if (!key.startsWith("target_")) { + fProp.put(key, properties.get(key)); + } + } return fProp; } return null; @@ -177,21 +172,16 @@ public String getCollectionElementTag(Property property){ public boolean isUnsavedValue(Property property) { SimpleValue sv = (SimpleValue) property.getValue(); - return ((sv.getNullValue()==null) || "undefined".equals(sv.getNullValue())) ? false : true; + return (sv.getNullValue() != null) && !"undefined".equals(sv.getNullValue()); } public String getUnsavedValue(Property property) { return ( (SimpleValue) property.getValue() ).getNullValue(); } - /** - * - * @param property - * @return - */ public boolean isIdentifierGeneratorProperties(Property property) { Properties val = this.getIdentifierGeneratorProperties(property); - return (val==null) ? false : true; + return val != null; } public Properties getIdentifierGeneratorProperties(Property property) { @@ -213,10 +203,6 @@ public Properties getIdentifierGeneratorProperties(Property property) { return result; } - /** - * @param property - * @return - */ public Set getFilteredIdentifierGeneratorKeySet(Property property, Properties props) { return getFilteredIdentifierGeneratorProperties(this.getIdentifierGeneratorProperties(property), props).keySet(); } @@ -228,10 +214,9 @@ public boolean isOneToMany(Property property) { public boolean isOneToMany(Value value) { if(value instanceof Collection) { return ( (Collection)value ).isOneToMany(); - }else if(value instanceof OneToMany){ - return true; } - return false; + else + return value instanceof OneToMany; } public boolean isManyToMany(Property property) { @@ -284,9 +269,7 @@ public boolean isTemporalValue(Property property) { return true; } else if ("timestamp".equals(typeName) || "java.sql.Timestamp".equals(typeName)) { return true; - } else if ("time".equals(typeName) || "java.sql.Time".equals(typeName)) { - return true; - } + } else return "time".equals(typeName) || "java.sql.Time".equals(typeName); } return false; } @@ -322,7 +305,7 @@ public String getCollectionLazy(Collection value){ public boolean isFilterDefinitions(Metadata md) { Map filterdefs = md.getFilterDefinitions(); - return filterdefs == null || filterdefs.isEmpty() ? false : true; + return filterdefs != null && !filterdefs.isEmpty(); } public boolean isClassLevelOptimisticLockMode(PersistentClass pc) { @@ -347,11 +330,7 @@ else if ( oMode == OptimisticLockStyle.NONE ) { public boolean hasFetchMode(Property property) { String fetch = getFetchMode(property); - if(fetch==null || "default".equals(fetch)) { - return false; - } else { - return true; - } + return fetch != null && !"default".equals(fetch); } public String getFetchMode(Property property) { FetchMode fetchMode = property.getValue().getFetchMode(); @@ -372,7 +351,7 @@ public String columnAttributes(Column col) { } public String columnAttributes(Column column, boolean isPrimaryKeyColumn) { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); if (column.getPrecision() != null) { sb.append("precision=\"").append(column.getPrecision() ).append("\" "); } @@ -436,30 +415,29 @@ public boolean needsDiscriminator(PersistentClass clazz) { public boolean needsTable(PersistentClass clazz) { - Boolean accept = (Boolean) clazz.accept(new PersistentClassVisitor(){ - - public Object accept(Subclass subclass) { - return Boolean.FALSE; - } - - public Object accept(JoinedSubclass subclass) { - return Boolean.TRUE; - } - - public Object accept(SingleTableSubclass subclass) { - return Boolean.FALSE; - } - - public Object accept(UnionSubclass subclass) { - return Boolean.TRUE; - } - - public Object accept(RootClass class1) { - return Boolean.TRUE; - } - }); - - return accept.booleanValue(); + + return (Boolean) clazz.accept(new PersistentClassVisitor(){ + + public Object accept(Subclass subclass) { + return Boolean.FALSE; + } + + public Object accept(JoinedSubclass subclass) { + return Boolean.TRUE; + } + + public Object accept(SingleTableSubclass subclass) { + return Boolean.FALSE; + } + + public Object accept(UnionSubclass subclass) { + return Boolean.TRUE; + } + + public Object accept(RootClass class1) { + return Boolean.TRUE; + } + }); } public boolean isSubclass(PersistentClass clazz) { @@ -473,12 +451,11 @@ public boolean isJoinedSubclass(PersistentClass clazz) { public boolean hasCustomEntityPersister(PersistentClass clazz) { ServiceRegistry sr = clazz.getServiceRegistry(); PersisterClassResolver pcr = sr.getService(PersisterClassResolver.class); + if (pcr == null) return false; Class entityPersisterClass = pcr.getEntityPersisterClass(clazz); if(entityPersisterClass==null) return false; final String name = entityPersisterClass.getName(); - - Boolean object = (Boolean) clazz.accept( new HasEntityPersisterVisitor( name ) ); - return object.booleanValue(); + return (Boolean) clazz.accept(new HasEntityPersisterVisitor(name)); } public String getHibernateTypeName(Property p) {