Search in sources :

Example 1 with Records

use of org.jooq.Records in project jOOQ by jOOQ.

the class JavaGenerator method generateDao.

protected void generateDao(TableDefinition table, JavaWriter out) {
    UniqueKeyDefinition key = table.getPrimaryKey();
    if (key == null) {
        log.info("Skipping DAO generation", out.file().getName());
        return;
    }
    final String className = getStrategy().getJavaClassName(table, Mode.DAO);
    final List<String> interfaces = out.ref(getStrategy().getJavaClassImplements(table, Mode.DAO));
    final String tableRecord = out.ref(getStrategy().getFullJavaClassName(table, Mode.RECORD));
    final String daoImpl = out.ref(DAOImpl.class);
    final String tableIdentifier = out.ref(getStrategy().getFullJavaIdentifier(table), 2);
    String tType = (scala || kotlin ? "Unit" : "Void");
    String pType = out.ref(getStrategy().getFullJavaClassName(table, Mode.POJO));
    List<ColumnDefinition> keyColumns = key.getKeyColumns();
    if (keyColumns.size() == 1) {
        tType = getJavaType(keyColumns.get(0).getType(resolver(out)), out, Mode.POJO);
    } else if (keyColumns.size() <= Constants.MAX_ROW_DEGREE) {
        StringBuilder generics = new StringBuilder();
        forEach(keyColumns, "", ", ", (column, separator) -> {
            generics.append(out.ref(getJavaType(column.getType(resolver(out)), out)));
            if (kotlin)
                generics.append("?");
            generics.append(separator);
        });
        if (scala)
            tType = Record.class.getName() + keyColumns.size() + "[" + generics + "]";
        else
            tType = Record.class.getName() + keyColumns.size() + "<" + generics + ">";
    } else {
        tType = Record.class.getName();
    }
    tType = out.ref(tType);
    printPackage(out, table, Mode.DAO);
    generateDaoClassJavadoc(table, out);
    printClassAnnotations(out, table, Mode.DAO);
    if (generateSpringAnnotations())
        out.println("@%s", out.ref("org.springframework.stereotype.Repository"));
    if (scala)
        out.println("%sclass %s(configuration: %s) extends %s[%s, %s, %s](%s, classOf[%s], configuration)[[before= with ][separator= with ][%s]] {", visibility(), className, Configuration.class, daoImpl, tableRecord, pType, tType, tableIdentifier, pType, interfaces);
    else if (kotlin)
        out.println("%sopen class %s(configuration: %s?) : %s<%s, %s, %s>(%s, %s::class.java, configuration)[[before=, ][%s]] {", visibility(), className, Configuration.class, daoImpl, tableRecord, pType, tType, tableIdentifier, pType, interfaces);
    else
        out.println("%sclass %s extends %s<%s, %s, %s>[[before= implements ][%s]] {", visibility(), className, daoImpl, tableRecord, pType, tType, interfaces);
    // Default constructor
    // -------------------
    out.javadoc("Create a new %s without any configuration", className);
    if (scala) {
        out.println("%sdef this() = this(null)", visibility());
    } else if (kotlin) {
        out.println("%sconstructor(): this(null)", visibility());
    } else {
        out.println("%s%s() {", visibility(), className);
        out.println("super(%s, %s.class);", tableIdentifier, pType);
        out.println("}");
    }
    if (!scala && !kotlin) {
        out.javadoc("Create a new %s with an attached configuration", className);
        printDaoConstructorAnnotations(table, out);
        out.println("%s%s(%s configuration) {", visibility(), className, Configuration.class);
        out.println("super(%s, %s.class, configuration);", tableIdentifier, pType);
        out.println("}");
    }
    // -------------------------------
    if (scala) {
        out.println();
        out.print("%soverride def getId(o: %s): %s = ", visibilityPublic(), pType, tType);
    } else if (kotlin) {
        out.println();
        out.print("%soverride fun getId(o: %s): %s? = ", visibilityPublic(), pType, tType);
    } else {
        out.overrideInherit();
        printNonnullAnnotation(out);
        out.println("%s%s getId(%s object) {", visibilityPublic(), tType, pType);
    }
    if (keyColumns.size() == 1) {
        if (scala)
            out.println("o.%s", getStrategy().getJavaGetterName(keyColumns.get(0), Mode.POJO));
        else if (kotlin)
            out.println("o.%s", getStrategy().getJavaMemberName(keyColumns.get(0), Mode.POJO));
        else
            out.println("return object.%s();", generatePojosAsJavaRecordClasses() ? getStrategy().getJavaMemberName(keyColumns.get(0), Mode.POJO) : getStrategy().getJavaGetterName(keyColumns.get(0), Mode.POJO));
    } else // [#2574] This should be replaced by a call to a method on the target table's Key type
    {
        StringBuilder params = new StringBuilder();
        forEach(keyColumns, "", ", ", (column, separator) -> {
            if (scala)
                params.append("o.").append(getStrategy().getJavaGetterName(column, Mode.POJO));
            else if (kotlin)
                params.append("o.").append(getStrategy().getJavaMemberName(column, Mode.POJO));
            else
                params.append("object.").append(generatePojosAsJavaRecordClasses() ? getStrategy().getJavaMemberName(column, Mode.POJO) : getStrategy().getJavaGetterName(column, Mode.POJO)).append("()");
            params.append(separator);
        });
        if (scala || kotlin)
            out.println("compositeKeyRecord(%s)", params.toString());
        else
            out.println("return compositeKeyRecord(%s);", params.toString());
    }
    if (scala || kotlin) {
    } else
        out.println("}");
    List<Definition> embeddablesAndUnreplacedColumns = embeddablesAndUnreplacedColumns(table);
    for (Definition column : embeddablesAndUnreplacedColumns) {
        final String colName = column.getOutputName();
        final String colClass = getStrategy().getJavaClassName(column);
        final String colMemberUC = StringUtils.toUC(getStrategy().getJavaMemberName(column), getStrategy().getTargetLocale());
        final String colTypeFull = getJavaType(column, out, Mode.POJO);
        final String colTypeRecord = out.ref(getJavaType(column, out, Mode.RECORD));
        final String colType = out.ref(colTypeFull);
        final String colIdentifier = out.ref(getStrategy().getFullJavaIdentifier(column), colRefSegments(column));
        // -----------------------
        if (!printDeprecationIfUnknownType(out, colTypeFull))
            out.javadoc("Fetch records that have <code>%s BETWEEN lowerInclusive AND upperInclusive</code>", colName);
        if (scala) {
            if (column instanceof EmbeddableDefinition)
                out.println("%sdef fetchRangeOf%s(lowerInclusive: %s, upperInclusive: %s): %s[%s] = fetchRange(%s, new %s(lowerInclusive), new %s(upperInclusive))", visibility(), colMemberUC, colType, colType, List.class, pType, colIdentifier, colTypeRecord, colTypeRecord);
            else
                out.println("%sdef fetchRangeOf%s(lowerInclusive: %s, upperInclusive: %s): %s[%s] = fetchRange(%s, lowerInclusive, upperInclusive)", visibility(), colClass, colType, colType, List.class, pType, colIdentifier);
        } else if (kotlin) {
            if (column instanceof EmbeddableDefinition)
                out.println("%sfun fetchRangeOf%s(lowerInclusive: %s?, upperInclusive: %s?): %s<%s> = fetchRange(%s, if (lowerInclusive != null) %s(lowerInclusive) else null, if (upperInclusive != null) %s(upperInclusive) else null)", visibility(), colMemberUC, colType, colType, out.ref(KLIST), pType, colIdentifier, colTypeRecord, colTypeRecord);
            else
                out.println("%sfun fetchRangeOf%s(lowerInclusive: %s?, upperInclusive: %s?): %s<%s> = fetchRange(%s, lowerInclusive, upperInclusive)", visibility(), colClass, colType, colType, out.ref(KLIST), pType, colIdentifier);
        } else {
            printNonnullAnnotation(out);
            if (column instanceof EmbeddableDefinition) {
                out.println("%s%s<%s> fetchRangeOf%s(%s lowerInclusive, %s upperInclusive) {", visibility(), List.class, pType, colMemberUC, colType, colType);
                out.println("return fetchRange(%s, new %s(lowerInclusive), new %s(upperInclusive));", colIdentifier, colTypeRecord, colTypeRecord);
            } else {
                out.println("%s%s<%s> fetchRangeOf%s(%s lowerInclusive, %s upperInclusive) {", visibility(), List.class, pType, colClass, colType, colType);
                out.println("return fetchRange(%s, lowerInclusive, upperInclusive);", colIdentifier);
            }
            out.println("}");
        }
        // -----------------------
        if (!printDeprecationIfUnknownType(out, colTypeFull))
            out.javadoc("Fetch records that have <code>%s IN (values)</code>", colName);
        if (scala) {
            if (column instanceof EmbeddableDefinition)
                out.println("%sdef fetchBy%s(values: %s*): %s[%s] = fetch(%s, values.map(v => new %s(v)).toArray:_*)", visibility(), colMemberUC, colType, List.class, pType, colIdentifier, colTypeRecord);
            else
                out.println("%sdef fetchBy%s(values: %s*): %s[%s] = fetch(%s, values:_*)", visibility(), colClass, colType, List.class, pType, colIdentifier);
        } else if (kotlin) {
            String toTypedArray = PRIMITIVE_WRAPPERS.contains(colTypeFull) ? ".toTypedArray()" : "";
            if (column instanceof EmbeddableDefinition)
                out.println("%sfun fetchBy%s(vararg values: %s): %s<%s> = fetch(%s, values.map { %s(it) })", visibility(), colMemberUC, colType, out.ref(KLIST), pType, colIdentifier, colTypeRecord);
            else
                out.println("%sfun fetchBy%s(vararg values: %s): %s<%s> = fetch(%s, *values%s)", visibility(), colClass, colType, out.ref(KLIST), pType, colIdentifier, toTypedArray);
        } else {
            printNonnullAnnotation(out);
            if (column instanceof EmbeddableDefinition) {
                out.println("%s%s<%s> fetchBy%s(%s... values) {", visibility(), List.class, pType, colMemberUC, colType);
                out.println("%s[] records = new %s[values.length];", colTypeRecord, colTypeRecord);
                out.println();
                out.println("for (int i = 0; i < values.length; i++)");
                out.tab(1).println("records[i] = new %s(values[i]);", colTypeRecord);
                out.println();
                out.println("return fetch(%s, records);", colIdentifier);
            } else {
                out.println("%s%s<%s> fetchBy%s(%s... values) {", visibility(), List.class, pType, colClass, colType);
                out.println("return fetch(%s, values);", colIdentifier);
            }
            out.println("}");
        }
        // -----------------------
        ukLoop: if (column instanceof ColumnDefinition) {
            for (UniqueKeyDefinition uk : ((ColumnDefinition) column).getKeys()) {
                // If column is part of a single-column unique key...
                if (uk.getKeyColumns().size() == 1 && uk.getKeyColumns().get(0).equals(column)) {
                    if (!printDeprecationIfUnknownType(out, colTypeFull))
                        out.javadoc("Fetch a unique record that has <code>%s = value</code>", colName);
                    if (scala) {
                        out.println("%sdef fetchOneBy%s(value: %s): %s = fetchOne(%s, value)", visibility(), colClass, colType, pType, colIdentifier);
                    } else if (kotlin) {
                        out.println("%sfun fetchOneBy%s(value: %s): %s? = fetchOne(%s, value)", visibility(), colClass, colType, pType, colIdentifier);
                    } else {
                        printNullableAnnotation(out);
                        out.println("%s%s fetchOneBy%s(%s value) {", visibility(), pType, colClass, colType);
                        out.println("return fetchOne(%s, value);", colIdentifier);
                        out.println("}");
                        if (!printDeprecationIfUnknownType(out, colTypeFull))
                            out.javadoc("Fetch a unique record that has <code>%s = value</code>", colName);
                        printNonnullAnnotation(out);
                        out.println("%s%s<%s> fetchOptionalBy%s(%s value) {", visibility(), Optional.class, pType, colClass, colType);
                        out.println("return fetchOptional(%s, value);", colIdentifier);
                        out.println("}");
                    }
                    break ukLoop;
                }
            }
        }
    }
    generateDaoClassFooter(table, out);
    out.println("}");
}
Also used : RandomAccessFile(java.io.RandomAccessFile) Arrays(java.util.Arrays) TableRecordImpl(org.jooq.impl.TableRecordImpl) DSL(org.jooq.impl.DSL) SCALA(org.jooq.codegen.Language.SCALA) StringUtils.isBlank(org.jooq.tools.StringUtils.isBlank) Collectors.counting(java.util.stream.Collectors.counting) Internal(org.jooq.impl.Internal) POSTGRES(org.jooq.SQLDialect.POSTGRES) DatatypeConverter(jakarta.xml.bind.DatatypeConverter) AttributeDefinition(org.jooq.meta.AttributeDefinition) ColumnDefinition(org.jooq.meta.ColumnDefinition) RoutineDefinition(org.jooq.meta.RoutineDefinition) Matcher(java.util.regex.Matcher) IndexColumnDefinition(org.jooq.meta.IndexColumnDefinition) SelectField(org.jooq.SelectField) IdentityDefinition(org.jooq.meta.IdentityDefinition) Arrays.asList(java.util.Arrays.asList) Index(org.jooq.Index) Map(java.util.Map) BigInteger(java.math.BigInteger) SQLDialect(org.jooq.SQLDialect) Domain(org.jooq.Domain) Database(org.jooq.meta.Database) EmbeddableColumnDefinition(org.jooq.meta.EmbeddableColumnDefinition) CheckConstraintDefinition(org.jooq.meta.CheckConstraintDefinition) Set(java.util.Set) Constants(org.jooq.Constants) AggregateFunction(org.jooq.AggregateFunction) Result(org.jooq.Result) Collectors.joining(java.util.stream.Collectors.joining) GenerationOption(org.jooq.impl.QOM.GenerationOption) Stream(java.util.stream.Stream) TableField(org.jooq.TableField) SQLDataType(org.jooq.impl.SQLDataType) GeneratedAnnotationType(org.jooq.meta.jaxb.GeneratedAnnotationType) SequenceDefinition(org.jooq.meta.SequenceDefinition) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) Parameter(org.jooq.Parameter) TableDefinition(org.jooq.meta.TableDefinition) CatalogImpl(org.jooq.impl.CatalogImpl) IndexDefinition(org.jooq.meta.IndexDefinition) Sequence(org.jooq.Sequence) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Calendar(java.util.Calendar) Records(org.jooq.Records) Schema(org.jooq.Schema) BiConsumer(java.util.function.BiConsumer) RowId(org.jooq.RowId) LinkedHashSet(java.util.LinkedHashSet) MYSQL(org.jooq.SQLDialect.MYSQL) Record(org.jooq.Record) Mode(org.jooq.codegen.GeneratorStrategy.Mode) TypeVariable(java.lang.reflect.TypeVariable) IOException(java.io.IOException) StringUtils(org.jooq.tools.StringUtils) File(java.io.File) YUGABYTEDB(org.jooq.SQLDialect.YUGABYTEDB) VIRTUAL(org.jooq.impl.QOM.GenerationOption.VIRTUAL) SchemaDefinition(org.jooq.meta.SchemaDefinition) LazySupplier(org.jooq.impl.LazySupplier) TableImpl(org.jooq.impl.TableImpl) CatalogDefinition(org.jooq.meta.CatalogDefinition) UniqueKey(org.jooq.UniqueKey) Row(org.jooq.Row) IntStream.rangeClosed(java.util.stream.IntStream.rangeClosed) Time(java.sql.Time) Table(org.jooq.Table) DataTypeDefinition(org.jooq.meta.DataTypeDefinition) DAOImpl(org.jooq.impl.DAOImpl) PackageDefinition(org.jooq.meta.PackageDefinition) DefaultDataType(org.jooq.impl.DefaultDataType) UDT(org.jooq.UDT) PostgresDatabase(org.jooq.meta.postgres.PostgresDatabase) SortOrder(org.jooq.SortOrder) DataType(org.jooq.DataType) DSL.name(org.jooq.impl.DSL.name) IdentityHashMap(java.util.IdentityHashMap) JooqLogger(org.jooq.tools.JooqLogger) SQLDialectNotSupportedException(org.jooq.exception.SQLDialectNotSupportedException) Collections.nCopies(java.util.Collections.nCopies) TimeZone(java.util.TimeZone) Name(org.jooq.Name) Timestamp(java.sql.Timestamp) Collection(java.util.Collection) Check(org.jooq.Check) Field(org.jooq.Field) CloseResult(org.jooq.codegen.GeneratorWriter.CloseResult) PostgresRoutineDefinition(org.jooq.meta.postgres.PostgresRoutineDefinition) Collectors(java.util.stream.Collectors) UpdatableRecordImpl(org.jooq.impl.UpdatableRecordImpl) TypedElementDefinition(org.jooq.meta.TypedElementDefinition) JAVA(org.jooq.codegen.Language.JAVA) DomainDefinition(org.jooq.meta.DomainDefinition) Reflect(org.jooq.tools.reflect.Reflect) List(java.util.List) Modifier(java.lang.reflect.Modifier) Function.identity(java.util.function.Function.identity) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) IntStream(java.util.stream.IntStream) UniqueKeyDefinition(org.jooq.meta.UniqueKeyDefinition) KOTLIN(org.jooq.codegen.Language.KOTLIN) UDTField(org.jooq.UDTField) DefaultDataTypeDefinition(org.jooq.meta.DefaultDataTypeDefinition) HashMap(java.util.HashMap) STORED(org.jooq.impl.QOM.GenerationOption.STORED) EnumType(org.jooq.EnumType) ForeignKey(org.jooq.ForeignKey) Function(java.util.function.Function) PackageImpl(org.jooq.impl.PackageImpl) Definition(org.jooq.meta.Definition) HashSet(java.util.HashSet) Identity(org.jooq.Identity) TableLike(org.jooq.TableLike) EmbeddableRecordImpl(org.jooq.impl.EmbeddableRecordImpl) EmbeddableDefinition(org.jooq.meta.EmbeddableDefinition) AbstractRoutine(org.jooq.impl.AbstractRoutine) Function2(org.jooq.Function2) ArrayDefinition(org.jooq.meta.ArrayDefinition) UDTDefinition(org.jooq.meta.UDTDefinition) AbstractTypedElementDefinition.getDataType(org.jooq.meta.AbstractTypedElementDefinition.getDataType) JavaTypeResolver(org.jooq.meta.JavaTypeResolver) ParameterDefinition(org.jooq.meta.ParameterDefinition) UDTRecordImpl(org.jooq.impl.UDTRecordImpl) ConstraintDefinition(org.jooq.meta.ConstraintDefinition) LazySchema(org.jooq.impl.LazySchema) DESC(org.jooq.SortOrder.DESC) SchemaImpl(org.jooq.impl.SchemaImpl) Date(java.sql.Date) ReflectException(org.jooq.tools.reflect.ReflectException) AbstractTypedElementDefinition(org.jooq.meta.AbstractTypedElementDefinition) Configuration(org.jooq.Configuration) Collectors.toList(java.util.stream.Collectors.toList) Catalog(org.jooq.Catalog) UDTImpl(org.jooq.impl.UDTImpl) StopWatch(org.jooq.tools.StopWatch) OrderField(org.jooq.OrderField) TableOptions(org.jooq.TableOptions) EnumDefinition(org.jooq.meta.EnumDefinition) ForeignKeyDefinition(org.jooq.meta.ForeignKeyDefinition) Collections(java.util.Collections) UniqueKeyDefinition(org.jooq.meta.UniqueKeyDefinition) Configuration(org.jooq.Configuration) AttributeDefinition(org.jooq.meta.AttributeDefinition) ColumnDefinition(org.jooq.meta.ColumnDefinition) RoutineDefinition(org.jooq.meta.RoutineDefinition) IndexColumnDefinition(org.jooq.meta.IndexColumnDefinition) IdentityDefinition(org.jooq.meta.IdentityDefinition) EmbeddableColumnDefinition(org.jooq.meta.EmbeddableColumnDefinition) CheckConstraintDefinition(org.jooq.meta.CheckConstraintDefinition) SequenceDefinition(org.jooq.meta.SequenceDefinition) TableDefinition(org.jooq.meta.TableDefinition) IndexDefinition(org.jooq.meta.IndexDefinition) SchemaDefinition(org.jooq.meta.SchemaDefinition) CatalogDefinition(org.jooq.meta.CatalogDefinition) DataTypeDefinition(org.jooq.meta.DataTypeDefinition) PackageDefinition(org.jooq.meta.PackageDefinition) PostgresRoutineDefinition(org.jooq.meta.postgres.PostgresRoutineDefinition) TypedElementDefinition(org.jooq.meta.TypedElementDefinition) DomainDefinition(org.jooq.meta.DomainDefinition) UniqueKeyDefinition(org.jooq.meta.UniqueKeyDefinition) DefaultDataTypeDefinition(org.jooq.meta.DefaultDataTypeDefinition) Definition(org.jooq.meta.Definition) EmbeddableDefinition(org.jooq.meta.EmbeddableDefinition) ArrayDefinition(org.jooq.meta.ArrayDefinition) UDTDefinition(org.jooq.meta.UDTDefinition) ParameterDefinition(org.jooq.meta.ParameterDefinition) ConstraintDefinition(org.jooq.meta.ConstraintDefinition) AbstractTypedElementDefinition(org.jooq.meta.AbstractTypedElementDefinition) EnumDefinition(org.jooq.meta.EnumDefinition) ForeignKeyDefinition(org.jooq.meta.ForeignKeyDefinition) EmbeddableDefinition(org.jooq.meta.EmbeddableDefinition) ColumnDefinition(org.jooq.meta.ColumnDefinition) IndexColumnDefinition(org.jooq.meta.IndexColumnDefinition) EmbeddableColumnDefinition(org.jooq.meta.EmbeddableColumnDefinition) Record(org.jooq.Record) Arrays.asList(java.util.Arrays.asList) ArrayList(java.util.ArrayList) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList)

Aggregations

DatatypeConverter (jakarta.xml.bind.DatatypeConverter)1 File (java.io.File)1 IOException (java.io.IOException)1 RandomAccessFile (java.io.RandomAccessFile)1 Modifier (java.lang.reflect.Modifier)1 TypeVariable (java.lang.reflect.TypeVariable)1 BigInteger (java.math.BigInteger)1 Date (java.sql.Date)1 Time (java.sql.Time)1 Timestamp (java.sql.Timestamp)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Arrays.asList (java.util.Arrays.asList)1 Calendar (java.util.Calendar)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 Collections.nCopies (java.util.Collections.nCopies)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 IdentityHashMap (java.util.IdentityHashMap)1