文档章节

非spring框架下使用querydsl

penngo
 penngo
发布于 01/07 12:55
字数 1241
阅读 274
收藏 5

Querydsl是一个采用API代替拼凑字符串来构造查询语句,可跟 Hibernate 和 JPA 等框架结合使用。网上很多教程都是结合spring JPA框架下使用的教程,本文介绍的是非spring环境下querydsl JPA整合使用。
1、使用eclipse生成jpa实体类,IDEA也能生成同样JPA实体类。

鼠标右键打开JPA Tools工具:

创建数据库链接:

选择那些数据库表需要生成JPA实体类:

关联表生成:

设置实体生成属性:

单个实体属性修改

生成的JPA实体类AdminLog.java

package com.test.db.entity;

import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;


/**
 * The persistent class for the admin_log database table.
 * 
 */
@Entity
@Table(name="admin_log")
@NamedQuery(name="AdminLog.findAll", query="SELECT a FROM AdminLog a")
public class AdminLog implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(unique=true, nullable=false)
	private String id;

	@Column(name="action_id", length=20)
	private String actionId;

	@Column(name="client_ip", length=15)
	private String clientIp;

	@Column(name="controller_id", length=20)
	private String controllerId;

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name="create_date")
	private Date createDate;

	@Column(name="create_user", length=50)
	private String createUser;

	@Column(name="func_name", length=50)
	private String funcName;

	@Column(name="module_name", length=50)
	private String moduleName;

	@Column(name="right_name", length=50)
	private String rightName;

	@Column(length=200)
	private String url;

	public AdminLog() {
	}

	public String getId() {
		return this.id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getActionId() {
		return this.actionId;
	}

	public void setActionId(String actionId) {
		this.actionId = actionId;
	}

	public String getClientIp() {
		return this.clientIp;
	}

	public void setClientIp(String clientIp) {
		this.clientIp = clientIp;
	}

	public String getControllerId() {
		return this.controllerId;
	}

	public void setControllerId(String controllerId) {
		this.controllerId = controllerId;
	}

	public Date getCreateDate() {
		return this.createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	public String getCreateUser() {
		return this.createUser;
	}

	public void setCreateUser(String createUser) {
		this.createUser = createUser;
	}

	public String getFuncName() {
		return this.funcName;
	}

	public void setFuncName(String funcName) {
		this.funcName = funcName;
	}

	public String getModuleName() {
		return this.moduleName;
	}

	public void setModuleName(String moduleName) {
		this.moduleName = moduleName;
	}

	public String getRightName() {
		return this.rightName;
	}

	public void setRightName(String rightName) {
		this.rightName = rightName;
	}

	public String getUrl() {
		return this.url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

}

2、生成querydsl查询类
maven pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.test.db</groupId>
	<artifactId>dbtest</artifactId>
	<packaging>jar</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>dbtest</name>
	<url>http://maven.apache.org</url>
	<properties>
		<querydsl.version>4.2.1</querydsl.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.querydsl</groupId>
			<artifactId>querydsl-sql</artifactId>
			<version>${querydsl.version}</version>
		</dependency>
		<dependency>
			<groupId>com.querydsl</groupId>
			<artifactId>querydsl-apt</artifactId>
			<version>${querydsl.version}</version>
		</dependency>
		<dependency>
			<groupId>com.querydsl</groupId>
			<artifactId>querydsl-jpa</artifactId>
			<version>${querydsl.version}</version>
		</dependency>
		<dependency>
			<groupId>com.querydsl</groupId>
			<artifactId>querydsl-sql-codegen</artifactId>
			<version>${querydsl.version}</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.eclipse.persistence</groupId>
			<artifactId>org.eclipse.persistence.jpa</artifactId>
			<version>2.6.0</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.6.1</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.11</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.10</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>5.4.0.Final</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<!--  生成jpa实体插件 -->
			<plugin>
				<groupId>com.querydsl</groupId>
				<artifactId>querydsl-maven-plugin</artifactId>
				<version>${querydsl.version}</version>
				<executions>
					<execution>
						<phase>generate-sources</phase>
						<goals>
							<goal>jpa-export</goal>
						</goals>
						<configuration>
							<targetFolder>${project.basedir}/target/generated-sources/java</targetFolder>
							<packages>com.test.db.entity</packages>
						</configuration>
					</execution>
				</executions>
			</plugin>
 			<!--  生成jpa实体插件 -->
 			<!-- 
 			<plugin>
		      <groupId>com.mysema.maven</groupId>
		      <artifactId>apt-maven-plugin</artifactId>
		      <version>1.1.3</version>
		      <executions>
		        <execution>
		          <goals>
		            <goal>process</goal>
		          </goals>
		          <configuration>
		            <outputDirectory>target/generated-sources/java</outputDirectory>
		            <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
		          </configuration>
		        </execution>
		      </executions>
		    </plugin>
		     -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

执行命令mvn compile或mvn eclipse:eclipse生成jpa实体对应的querydsl查询类

AdminLog.java对应的querydsl对应查询类

package com.test.db.entity;

import static com.querydsl.core.types.PathMetadataFactory.*;

import com.querydsl.core.types.dsl.*;

import com.querydsl.core.types.PathMetadata;
import javax.annotation.Generated;
import com.querydsl.core.types.Path;


/**
 * QAdminLog is a Querydsl query type for AdminLog
 */
@Generated("com.querydsl.codegen.EntitySerializer")
public class QAdminLog extends EntityPathBase<AdminLog> {

    private static final long serialVersionUID = 392071999L;

    public static final QAdminLog adminLog = new QAdminLog("adminLog");

    public final StringPath actionId = createString("actionId");

    public final StringPath clientIp = createString("clientIp");

    public final StringPath controllerId = createString("controllerId");

    public final DateTimePath<java.util.Date> createDate = createDateTime("createDate", java.util.Date.class);

    public final StringPath createUser = createString("createUser");

    public final StringPath funcName = createString("funcName");

    public final StringPath id = createString("id");

    public final StringPath moduleName = createString("moduleName");

    public final StringPath rightName = createString("rightName");

    public final StringPath url = createString("url");

    public QAdminLog(String variable) {
        super(AdminLog.class, forVariable(variable));
    }

    public QAdminLog(Path<? extends AdminLog> path) {
        super(path.getType(), path.getMetadata());
    }

    public QAdminLog(PathMetadata metadata) {
        super(AdminLog.class, metadata);
    }

}

3、查询例子

JPA持久化META-INF\persistence.xml配置文件,EntityManagerFactory创建实例时,需要读取该配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">
    <persistence-unit name="jpa" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
            <!-- .MySQLInnoDBDialect -->
        	<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL8Dialect"/>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
			<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/yiiboot?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=Asia/Shanghai&amp;useSSL=true" />
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password" value="123" />

            <property name="connection.provider_class" value="com.alibaba.druid.support.hibernate.DruidConnectionProvider" />
            <!-- 配置初始化大小、最小、最大 -->
            <property name="initialSize" value="1" />
            <property name="minIdle" value="1" />
            <property name="maxActive" value="20" />
            <!-- 配置获取连接等待超时的时间 -->
            <property name="maxWait" value="60000" />

            <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
            <property name="timeBetweenEvictionRunsMillis" value="60000" />

            <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
            <property name="minEvictableIdleTimeMillis" value="300000" />
        </properties>
    </persistence-unit>
</persistence>

测试代码

package com.test.db.main;

import java.util.List;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.test.db.entity.AdminModule;
import com.test.db.entity.QAdminModule;

public class JpaTest {
	public static void main(String[] args) throws Exception{
		String persistenceUnitName = "jpa";
		EntityManagerFactory entityManagerFactory = 
		Persistence.createEntityManagerFactory(persistenceUnitName);
		JPAQueryFactory queryFactory = new JPAQueryFactory(entityManagerFactory.createEntityManager());
		QAdminModule adminModule = QAdminModule.adminModule;
		List<AdminModule> list = queryFactory.selectFrom(adminModule).fetch();
		list.forEach(module->{
			System.out.println(module.getId() + "," + module.getDisplayLabel() + "," + module.getCreateDate());
		});
	}
}

querydsl官方文档:http://www.querydsl.com/static/querydsl/latest/reference/html/ch02.html#jpa_integration
java类库:https://www.21doc.net/java/awesomejava#database

 

 

 

 

© 著作权归作者所有

共有 人打赏支持
penngo
粉丝 80
博文 104
码字总数 60124
作品 2
广州
高级程序员
私信 提问
Spring Data MongoDB 1.0.0 M4 发布

Spring Data MongoDB 1.0.0 M4 发布了,该版本主要亮点: Support for map-reduce operations in MongoTemplate Provided means to use externalized queries to be executed by repositori......

红薯
2011/09/05
1K
3
第一章:Maven环境下如何配置QueryDSL环境

QueryDSL是一个通用的查询框架,框架的核心原则是创建安全类型的查询,开始QueryDSL仅支持Hibernate(HQL),在不断开源人士加入QueryDSL团队后,陆续发布了针对JPA,JDO,JDBC,Lucene,Hib...

恒宇少年
2017/07/01
0
0
Spring Data Neo4j 2.0.0.RC1 发布

Spring Data 项目的目的是为了简化构建基于 Spring 框架应用的数据访问计数,包括非关系数据库、Map-Reduce 框架、云数据服务等等;另外也包含对关系数据库的访问支持。 而 Spring Data Neo4...

红薯
2011/11/15
958
0
第四十九章:SpringBoot2.0新特性 - 你get到WebMvcConfigurer两种配置方式了吗?

初升级版本,在已经使用的系统内还是存在一些兼容性的问题,有很多变化!!!也存在一些过时的方法、配置文件信息以及类,我们在之前版本的中可以使用抽象类来处理相关的配置,由于版本最低支...

恒宇少年
2018/03/17
0
0
国内开源 java cms,Jspxcms 2.0 发布

Jspxcms-2.0.0-RELEASE正式版发布了。 Jspxcms是基于java技术开发的国产开源cms,是制作、维护网站的利器。国内cms 主要以php技术为主,基于java的cms数量不多,功能和易用性也有一定差距。J...

jspxcms
2013/04/08
15.8K
39

没有更多内容

加载失败,请刷新页面

加载更多

大数据教程(11.9)hive操作基础知识

上一篇博客分享了hive的简介和初体验,本节博主将继续分享一些hive的操作的基础知识。 DDL操作 (1)创建表 #建表语法CREATE [EXTERNAL] TABLE [IF NOT EXISTS] table_name [(col_name ...

em_aaron
今天
0
0
OSChina 周四乱弹 —— 我家猫真会后空翻

Osc乱弹歌单(2019)请戳(这里) 【今日歌曲】 @我没有抓狂 :#今天听这个# 我艇牛逼,百听不厌,太好听辣 分享 Led Zeppelin 的歌曲《Stairway To Heaven》 《Stairway To Heaven》- Led Z...

小小编辑
今天
1
0
node调用dll

先安装python2.7 安装node-gyp cnpm install node-gyp -g 新建一个Electron-vue项目(案例用Electron-vue) vue init simulatedgreg/electron-vue my-project 安装electron-rebuild cnpm ins......

Chason-洪
今天
3
0
scala学习(一)

学习Spark之前需要学习Scala。 参考学习的书籍:快学Scala

柠檬果过
今天
3
0
通俗易懂解释网络工程中的技术,如STP,HSRP等

导读 在面试时,比如被问到HSRP的主备切换时间时多久,STP几个状态的停留时间,自己知道有这些东西,但在工作中不会经常用到,就老是记不住,觉得可能还是自己基础不够牢固,知识掌握不够全面...

问题终结者
昨天
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部