繁体   English   中英

jooq - 将代码添加到生成的Record类中

[英]jooq - Add code to the generated Record class

我学习如何使用jooq。 我想知道是否可以在生成的Record类中添加一些域级方法。

假设记录是这样的:

public class ConCalCompanyRecord extends org.jooq.impl.UpdatableRecordImpl<com.aesthete.csmart.connect.model.db.gen.tables.records.ConCalCompanyRecord> implements org.jooq.Record6<java.lang.Integer, java.lang.Integer, java.lang.String, java.lang.String, java.sql.Timestamp, java.sql.Timestamp> {

// properties
// getters and setters

// I would like to add a method like this:
   public void isABlueCompany(){
     // work with the fields
   }

}

但我知道如果我这样做,只要我再次从数据库生成这个类,我的所有更改都将丢失。 那么建议的方法是什么?

包装类? 记录的子类? 如果是其中的任何一个,如何在获取时让jooq识别这些类。 例如:

connectionFacade.getDSLContext()
            .selectFrom(CON_CAL_INSTANCE)
            .where(CON_CAL_INSTANCE.DATE.between(
                    new Date(datesOfTheWeekForDate[0].toDate().getTime()), new Date(datesOfTheWeekForDate[1].toDate().getTime())))
            .orderBy(CON_CAL_INSTANCE.DATE)
            .fetch()
            .into(new RecordHandler<ConCalInstanceRecord>() {
                @Override
                public void next(ConCalInstanceRecord record) {
                    calendarEntries.addToList(new com.aesthete.csmart.connect.model.domain.records.ConCalInstance(record));
                   }
            });

在上面的例子中,我向记录类提供了一个名为ConCalInstance的包装器。 如果我需要使用包装器,我是否必须为我执行的每个查询编写这样的RecordHandler? 这样做的推荐方法是什么?

您可以使用自己的扩展覆盖jOOQ的默认代码生成器。 这在此手册中记录:

该示例显示了它的工作原理:

public class MyGenerator extends JavaGenerator {

    @Override
    protected void generateRecordClassFooter(
        TableDefinition table, 
        JavaWriter out
    ) {
        super.generateRecordClassFooter(table, out);

        if ("SOME_TABLE".equals(table.getName())) {
            out.println();
            out.tab(1).println("public void isABlueCompany() {");
            out.tab(2).println("// Your logic here");
            out.tab(1).println("}");
        }
        else if ("SOME_OTHER_TABLE".equals(table.getName())) {
            // [...]
        }
    }
}

根据Lukas的建议,我将代码添加到我生成的Record中

public class ConCalInstanceRecord extends org.jooq.impl.UpdatableRecordImpl....{

     //fields and getter and setters of the generated record..

    private ConCalInstanceBehaviour behaviour;

    public ConCalInstanceBehaviour getBehaviour(){
        if(behaviour==null){
            behaviour=new ConCalInstanceBehaviour(this);
        }
        return behaviour;
    }
}

有点像我正在谈论的包装器,但反过来说,记录包装行为类。 我现在可以将自定义行为添加到我的行为类中,而无需在每次需要添加新方法时返回到生成器。

这允许我访问这样的其他域行为......

record.getBehaviour().doSomething();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM