聊聊querydsl的生成類

本文主要聊一下querydsl的生成類sql

maven

<dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-sql</artifactId>
            <version>4.1.4</version>
        </dependency>
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-apt</artifactId>
            <version>4.1.4</version>
        </dependency>
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-jpa</artifactId>
            <version>4.1.4</version>
        </dependency>

plugin

<plugin>
                <groupId>com.querydsl</groupId>
                <artifactId>querydsl-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>process</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>target/generated-sources</outputDirectory>
                            <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

生成Q類

mvn compile

不過因爲是生成在target裏頭的,總體感受對IDE不是太友好,另外這種生成代碼的方式,有點雞肋,每當修改字段或者增刪字段時,就得從新生成一次,很是費勁。若是要生成,仍是基於字節碼動態生成的靠譜一點,至少方便一些。maven

手寫Q類

對於字段少的類,能夠本身手寫,Q類,以下:code

@Generated("com.querydsl.sql.codegen.MetaDataSerializer")
public class QDemo extends RelationalPathBase<QDemo> {

    public final NumberPath<Long> id = createNumber("id",Long.class);
    public final NumberPath<Long> countNum = createNumber("countNum",Long.class);
    public final StringPath  name = createString("name");

    public static QDemo qDemo = new QDemo(QDemo.class.getSimpleName(),null,"demo");

    public QDemo(String path, String schema, String table){
        super(Demo.class, path, schema, table);
        addMeta();
    }
    
    public void addMeta(){
        addMetadata(countNum, ColumnMetadata.named("count_num"));
        addMetadata(name, ColumnMetadata.named("name"));
    }
}

小結

querydsl強大是強大,可是Q類這麼一搞,有點搞複雜了,想徹底屏蔽sql是不可能的,有必定適用場景,但不是萬能。get

doc

相關文章
相關標籤/搜索