QueryDSL 简单的查询语句应用

关于 QueryDSL 配置和使用(详细) 关于 QueryDSL 最近写项目,使用到了 Jpa 这个 ORM 规范支持,使用注解的方式实现 Sql ,但是用过 Jpa 的同学都知道 Jpa 对于单表操作很灵活,但是对于复杂一些的 SQL 就是很不友好了,所以这个地方我们就用到了 QueryDSL 来实现复杂的 Sql(另外强行安利一波 Tk-MyBatis) 什么是 QueryDSL ? QueryDSL仅仅是一... 阅读详情

1.//queryDSL查询返回一个对象
QCustomer customer = QCustomer.customer;
JPAQuery query = newJPAQuery(entityManager);
Customer bob = query.from(customer).where(customer.firstName.eq("Bob")).uniqueResult(customer);
2.//
QCustomer customer = QCustomer.customer;
QCompany company = QCompany.company;
query.from(customer, company);

query.from(customer).where(customer.firstName.eq("Bob"), customer.lastName.eq("Wilson"));

query.from(customer).where(customer.firstName.eq("Bob").and(customer.lastName.eq("Wilson")));
//The native JPQL version of the query would be
from Customer as customer where customer.firstName = "Bob" and customer.lastName = "Wilson";

query.from(customer).where(customer.firstName.eq("Bob").or(customer.lastName.eq("Wilson")));

3.//Using joins
QCat cat = QCat.cat;
QCat mate = newQCat("mate");
QCate kitten = newQCat("kitten");
query.from(cat).innerJoin(cat.mate, mate).leftJoin(cat.kittens, kitten).list(cat);

from Cat as cat inner join cat.mate as mate left outer join cat.kittens as kitten;

query.from(cat).leftJoin(cat.kittens, kitten).on(kitten.bodyWeight.gt(10.0)).list(cat);

from Cat as cat left join cat.kittens as kitten on kitten.bodyWeight > 10.0

4.//Ordering
QCustomer customer = QCustomer.customer;
query.from(customer).orderBy(customer.lastName.asc(), customer.firstName.desc()).list(customer);

from Customer as customer order by customer.lastName asc, customer.firstName desc

5.//Grouping
query.from(customer).groupBy(customer.lastName).list(customer.lastName);

select customer.lastName from Customer as customer group by customer.lastName

6.//Delete clauses
QCustomer customer = QCustomer.customer;
// delete all customers
new JPADeleteClause(entityManager, customer).execute();
// delete all customers with a level less than 3
new JPAeDeleteClause(entityManager, customer).where(customer.level.lt(3)).execute();

7.//Update clauses
QCustomer customer = QCustomer.customer;
// rename customers named Bob to Bobby
new JPAUpdateClause(session, customer).where(customer.name.eq("Bob")).set(customer.name, "Bobby").execute();

8.//Subqueries
QDepartment department = QDepartment.department;
QDepartment d = new QDepartment("d");
query.from(department).where(department.employees.size().eq(new JPASubQuery().from(d).unique(d.employees.size().max())
)).list(department);

QEmployee employee = QEmployee.employee;
QEmployee e = newQEmployee("e");
query.from(employee).where(employee.weeklyhours.gt(
new JPASubQuery().from(employee.department.employees, e).where(e.manager.eq(employee.manager)).unique(e.weeklyhours.avg())
)).list(employee);

9.//Using Native SQL in JPA queries
/*Maven配置
<plugin>
<groupId>com.mysema.querydsl</groupId>
<artifactId>querydsl-maven-plugin</artifactId>
<version>${project.version}</version>
<executions>
<execution>
<goals>
<goal>export</goal>
</goals>
</execution>
</executions>
<configuration>
<jdbcDriver>org.apache.derby.jdbc.EmbeddedDriver</jdbcDriver>
<jdbcUrl>jdbc:derby:target/demoDB;create=true</jdbcUrl>
<packageName>com.mycompany.mydomain</packageName>
<targetFolder>${project.basedir}/target/generated-sources/java</targetFolder>
</configuration>
<dependencies>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>${derby.version}</version>
</dependency>
</dependencies>
</plugin>
*/
//Single column query
// serialization templates
SQLTemplates templates = newDerbyTemplates();
// query types (S* for SQL, Q* for domain types)
SAnimal cat = newSAnimal("cat");
SAnimal mate = newSAnimal("mate");
QCat catEntity = QCat.cat;
JPASQLQuery query = newJPASQLQuery(entityManager, templates);
List<String> names = query.from(cat).list(cat.name);

//Query multiple columns
query = newJPASQLQuery(entityManager, templates);
List<Object[]> rows = query.from(cat).list(cat.id, cat.name);

//Query all columns
List<Object[]> rows = query.from(cat).list(cat.all());

//Query in SQL, but project as entity
query = newJPASQLQuery(entityManager, templates);
List<Cat> cats = query.from(cat).orderBy(cat.name.asc()).list(catEntity);

//Query with joins
query = newJPASQLQuery(entityManager, templates);
cats = query.from(cat).innerJoin(mate).on(cat.mateId.eq(mate.id)).where(cat.dtype.eq("Cat"), mate.dtype.eq("Cat")).list(catEntity);

//Query and project into DTO
query = newJPASQLQuery(entityManager, templates);
List<CatDTO> catDTOs = query.from(cat).orderBy(cat.name.asc()).list(ConstructorExpression.create(CatDTO.class, cat.id, cat.name));

10.//Ordering
QCustomer customer = QCustomer.customer;
query.from(customer).orderBy(customer.lastName.asc(), customer.firstName.desc()).list(customer);

11.//Grouping
query.from(customer).groupBy(customer.lastName).list(customer.lastName);

12.//Delete clauses
QCustomer customer = QCustomer.customer;
// delete all customers
newJDODeleteClause(pm, customer).execute();
// delete all customers with a level less than 3
newJDODeleteClause(pm, customer).where(customer.level.lt(3)).execute();

13.//Subqueries
//JDOSubQueryinstance
QDepartment department = QDepartment.department;
QDepartment d = newQDepartment("d");
query.from(department)
.where(department.employees.size().eq(newJDOSubQuery().from(d).unique(AggregationFunctions.max(d.employees.size()))
)).list(department);

//native JDO query
SELECT this FROM com.mysema.query.jdoql.models.company.Department
WHERE this.employees.size() == SELECT max(d.employees.size()) FROM com.mysema.query.jdoql.models.company.Department d)

QEmployee employee = QEmployee.employee;
QEmployee e = newQEmployee("e");
query.from(employee).where(employee.weeklyhours.gt(newJDOSubQuery().from(employee.department.employees, e)
.where(e.manager.eq(employee.manager)).unique(AggregationFunctions.avg(e.weeklyhours)))).list(employee);

//native JDO query
SELECT this FROM com.mysema.query.jdoql.models.company.Employee
WHERE this.weeklyhours > (SELECT avg(e.weeklyhours) FROM this.department.employees e WHERE e.manager == this.manager)

14.//Window functions
query.from(employee).list(SQLExpressions.rowNumber().over().partitionBy(employee.name).orderBy(employee.id));

15.//Insert
QSurvey survey = QSurvey.survey;
newSQLInsertClause(conn, dialect, survey).columns(survey.id, survey.name).values(3, "Hello").execute()

newSQLInsertClause(conn, dialect, survey).values(4, "Hello").execute();
//subquery
new SQLInsertClause(conn, dialect, survey).columns(survey.id, survey.name).select(newSQLSubQuery().from(survey2).list(survey2.id.add(1), survey2.name))
.execute();

new SQLInsertClause(conn, dialect, survey).select(newSQLSubQuery().from(survey2).list(survey2.id.add(10), survey2.name))
.execute();
16.//Update
QSurvey survey = QSurvey.survey;
new SQLUpdateClause(conn, dialect, survey).where(survey.name.eq("XXX")).set(survey.name, "S").execute();

new SQLUpdateClause(conn, dialect, survey).set(survey.name, "S").execute()

17.//Delete
QSurvey survey = QSurvey.survey;
new SQLDelecteClause(conn, dialect, survey).where(survey.name.eq("XXX")).execute();

new SQLDelecteClause(conn, dialect, survey).execute()

18.//Batch support in DML clauses
//Update:
QSurvey survey = QSurvey.survey;
insert(survey).values(2, "A").execute();
insert(survey).values(3, "B").execute();
SQLUpdateClause update = update(survey);
update.set(survey.name, "AA").where(survey.name.eq("A")).addBatch();
update.set(survey.name, "BB").where(survey.name.eq("B")).addBatch();
//Delete:
insert(survey).values(2, "A").execute();
insert(survey).values(3, "B").execute();
SQLDeleteClause delete = delete(survey);
delete.where(survey.name.eq("A")).addBatch();
delete.where(survey.name.eq("B")).addBatch();
assertEquals(2, delete.execute());
//Insert
SQLInsertClause insert = insert(survey);
insert.set(survey.id, 5).set(survey.name, "5").addBatch();
insert.set(survey.id, 6).set(survey.name, "6").addBatch();
assertEquals(2, insert.execute());

19.
//limit
query.where(doc.title.like("*")).limit(10).list();
//offset
query.where(doc.title.like("*")).offset(3).list();

20.//Fuzzy searches
query.where(LuceneExpressions.fuzzyLike(doc.title, "Hello")).list();
21.//Applying Lucene filters to queries
query.where(doc.title.like("*")).filter(filter).list();

query.where(doc.title.like("*")).distinct(doc.title).list()
22.//Querying Hibernate Search
QUser user = QUser.user;
SearchQuery<User> query = newSearchQuery<User>(session, user);
List<User> list = query.where(user.firstName.eq("Bob")).list();

23.// Querying Mongodb
/*
<dependency>
<groupId>com.mysema.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>${querydsl.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.mysema.querydsl</groupId>
<artifactId>querydsl-mongodb</artifactId>
<version>${querydsl.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
*/
/*
<project>
<build>
<plugins>
...
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.0.9</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources/java</outputDirectory>
<processor>com.mysema.query.apt.morphia.MorphiaAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
...
</plugins>
</build>
</project>
*/

24.//Result handling

List<Tuple> result = query.from(employee).list(employee.firstName, employee.lastName);
for(Tuple row : result) {
System.out.println("firstName "+ row.get(employee.firstName));
System.out.println("lastName "+ row.get(employee.lastName));
}}

List<UserDTO> dtos = query.list(Projections.bean(UserDTO.class, user.firstName, user.lastName));


class CustomerDTO {
@QueryProjection
public  CustomerDTO(longid, String name){
...
}
}
QCustomer customer = QCustomer.customer;
JPQLQuery query = newHibernateQuery(session);
List<CustomerDTO> dtos = query.from(customer).list(new QCustomerDTO(customer.id, customer.name));

QCustomer customer = QCustomer.customer;
JPQLQuery query = new HibernateQuery(session);
List<Customer> dtos = query.from(customer).list(QCustomer.create(customer.id, customer.name));

List<Customer> dtos = query.from(customer).list(ConstructorExpression.create(Customer.class, customer.id, customer.name));

25.//Result aggregation

import staticcom.mysema.query.group.GroupBy.*;
Map<Integer, List<Comment>> results = query.from(post, comment).where(comment.post.id.eq(post.id)).transform(groupBy(post.id).as(list(comment)))

Map<Integer, Group> results = query.from(post, comment).where(comment.post.id.eq(post.id)).transform(groupBy(post.id).as(post.name, set(comment.id)));

 

querydsl中文文档 querydsl中文文档,旨在帮助使用QueryDSL的开发程序人员使用 立即下载

相关推荐

光致发光(Photoluminescence, PL)入门版

关于光致发光的实际应用做出一些解释。

sinat_40546227的博客 1万+

JPA 之 QueryDSL-JPA 使用指南

JPA 之 QueryDSL-JPA 使用指南

墨鸦的博客 2万+

解锁微信小程序Camera组件的隐藏技能:连续扫码背后的逻辑与陷阱

本文深入解析微信小程序Camera组件在连续扫码功能中的技术原理与优化方案,涵盖识别率提升、内存管理策略及典型问题排查。通过实战参数对比和代码示例,帮助开发者解决扫码枪应用中的性能损耗与界面卡顿问题,提升零售、物流等场景的工作效率。

weixin_29019241的博客 492

Spring Data Querydsl-JPA 的简单入门笔记

作用:使用QueryDSL的功能时,会依赖使用到JPAQueryFactory,而JPAQueryFactory在这里依赖使用EntityManager,所以在主类中做如下配置,使得Spring自动帮我们注入EntityManager与自动管理JPAQueryFactory。维护HQL查询官方封装类 Spring Data Querydsl 支持JPA,JDO,JDBC,Lucene,Hibernate Search,MongoDB,Collections和RDFBean作为它的后端。

weixin_46063176的博客 4920

ros_control硬件接口实战:从零构建机器人控制框架

本文详细介绍了ros_control硬件接口在机器人控制框架中的核心作用与实践方法。通过解析硬件接口类型、实现标准接口、构建主控制循环及自定义功能扩展,帮助开发者从零构建高效的机器人控制系统,提升硬件与ROS的协同效率。

lstm7chronicler的博客 500

S7-1200PLC V90伺服绝对值编码器校准功能块

S7-1200PLC通过111报文和EPOS模式实现位置轴轴控功能(FB284封装)-优快云博客文章浏览阅读173次。EASY_SINA_POS的详细使用介绍请参考下面文章链接:S7-1200PLC使用标准报文111和EPOS模式实现V90 PN总线伺服定位(Easy_SINA_Pos)_西门子sinapos-优快云博客文章浏览阅读132次。文章浏览阅读7k次。先简单说下如何获取FB284,一般有2种方法,Startdrive软件可以操作大部分西门子的驱动器,建议安装调试方便,缺点就是软件太大。

RXXW_Dor的博客 968

使用spring data Querydsl 实现动态查询功能

Table of Contents 概述 定义查询请求 google-like查询 特定字段的类sql查询 使用Spring DataQuerydsl 利用Spring Query DSL实现动态查询 实现过程中的难题 主表包含多个子表数据时的AND查询 概述 本篇博客主要将介绍的是利用spring query dsl框架实现的服务端查询解析和实现介绍。 查询功能是在各种应...

topdeveloperr的博客 6552

DB文件在编程中的作用及示例代码

通过使用DB文件,我们可以实现数据的持久化存储,并能够高效地进行数据的增删改查操作。在本文中,我们以SQLite数据库为例,演示了如何使用Python语言创建和操作DB文件的示例代码。在实际的编程中,我们可以根据具体的需求和使用的数据库系统来进行更复杂的操作和优化。通过使用DB文件,我们可以实现数据的持久化存储,确保数据在程序关闭后也能被保留,并且能够高效地进行数据检索和更新。在本文中,我们将探讨DB文件的作用,并提供一些示例代码展示如何在编程中使用DB文件。上述代码中,我们使用SQLite提供的。

CodeSpark的博客 1821

8.Elasticsearch查询表达式Query DSL

Query DSL 查询表达式(Query DSL)是一种非常灵活又富有表现力的 查询语言。 Elasticsearch 使用它可以以简单的 JSON 接口来展现 Lucene 功能的绝大部分。在你的应用中,你应该用它来编写你的查询语句。它可以使你的查询语句更灵活、更精确、易读和易调试。 要使用这种查询表达式,只需将查询语句传递给 query 参数: 比如前面的空查询,又可以写为: G...

IT云清 2563

本地快速部署谷歌开放模型Gemma教程(基于Ollama)

谷歌最近发布了新一代开源AI模型Gemma,此次发布的 Gemma 相比自家的 Gemini 更加轻量级,模型权重也一并开源。不仅可以在笔记本电脑上运行,而且还免费可商用,支持中文。运行速度飞快。

特立独行的博客 6716

基于YOLOv8的铁路轨道异物检测系统设计与实现

目标检测是计算机视觉领域的核心任务之一,旨在识别图像中特定目标的位置和类别。传统方法主要依赖手工特征(如HOG、SIFT等)和分类器(如SVM),而深度学习方法通过卷积神经网络自动学习特征表示,显著提升了检测性能。YOLO(You Only Look Once)系列算法作为单阶段目标检测的代表,以其高效的检测速度著称。YOLOv8是Ultralytics公司于2023年发布的最新版本,在精度和速度上都有进一步提升。

YOLO 574

ES QueryBuilder学习

参考:Elasticsearch java api 常用查询方法QueryBuilder构造举例:https://blog.youkuaiyun.com/u012546526/article/details/74184769QueryBuilder简单查询:https://blog.youkuaiyun.com/lom9357bye/article/details/52852533elasticsearch Query详...

zhaipengfei1231的博客 7086

2026年VIVO嵌入式岗位高频面试题(含参考答案)

摘要:VIVO嵌入式岗位考核涵盖智能手机、IoT设备、芯片适配等方向,重点考察硬件底层交互、RTOS/Linux开发、C/C++功底与问题排查能力。题目按优先级排序,分硬件架构、RTOS、C/C++、数据结构、Linux实践、行业认知6大模块,共40道题。硬件部分涉及中断、ARM架构、加速技术、BSP开发等;RTOS部分区分硬/软实时系统;C/C++部分侧重内存管理、位操作;Linux部分考察常用命令;行业部分关注鸿蒙等系统理念。题目设计贴合实际工作场景,全面评估嵌入式开发能力。

Open 52

elasticsearch Query DSL

紧接上次入门篇,这一篇主要记录elasticsearch的结构化查询 Query DSL. 结构化查询是一种灵活的,多表现形式的查询语言。 Elasticsearch在一个简单的JSON接口中用结构化查询来展现Lucene绝大多数能力。 你应当在你的产品中采用这种方式进行查询。它使得你的查询更加灵活,精准,易于阅读并且易于debug。 single API PUT /spider/ # 创建索引...

weixin_30323961的博客 124

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Elasticsearch Request Body DSL

1、将语句通过HTTP Request Body 发送给Elasticsearch 2、Query DSL ,是Elasticsearch查询的语法 示例(ignore_unavailable=true表示即使搜索的index不存在也不报错) 3、分页/排序 1)分页 From 从0开始,默认返回10个结果 获取靠后的翻页成本较高(Elasticsearch分片机制,在查询分页的时候,需要将前面...

希望我的博客,能解决你工作中的问题 507

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Elasticsearch Query DSL基础介绍

查询语法(Query DSL) Elasticsearch提供标准RESTful风格的查询DSL来定义查询。可以将查询 DSL 看作是由两种子句组成的查询的 AST (Abstract Syntax Tree) : Leaf query clauses 叶查询语句(可以理解为SQL里的where查询)在特定字段中查找特定值,例如 matc...

weixin_34138139的博客 158

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

Query DSL:

request body: 分成两类: query dsl:执行full-text查询时,基于相关度来评判其匹配结果; 查询执行过程复杂,且不会被缓存; filter dsl:执行exact查询时,基于其结果为“yes”或“no”进行评判; 速度快,且结果缓存; 查询语句的结构: { QUERY_NAME: { AGGUMENT: VALUE, ARGUMENT: VALUE,… } } { Q...

测试 526

ElasticSearch 5学习(10)——结构化查询(包括新特性)

之前我们所有的查询都属于命令行查询,但是不利于复杂的查询,而且一般在项目开发中不使用命令行查询方式,只有在调试测试时使用简单命令行查询,但是,如果想要善用搜索,我们必须使用请求体查询(request body search)API。之所以这么称呼,是因为大多数的参数以JSON格式所容纳而非查询字符串。请求体查询,并不仅仅用来处理查询,而且还可以高亮返回结果中的片段,并且给出帮助你的用户找寻最好结果...

weixin_30865427的博客 228

持久层框架常用关键字 NE GE LE GT LT EQ 等等

NE : not equal 不等于 .ne GE : greater than or equal 大于等于 .goe LE : less than or equal 小于等于 .loe GT : greater than 大于 .gt LT : less than  小于 .lt EQ : equal 等于 .eq queryDSL还有很多其他的关键字: orderBy

AshenOne余烬 5869

jpa+QueryDSL

QueryDSL 简介 QueryDSL仅仅是一个通用的查询框架,专注于通过Java API构建类型安全的SQL查询。 Querydsl可以通过一组通用的查询API为用户构建出适合不同类型ORM框架或者是SQL的查询语句,也就是说QueryDSL是基于各种ORM框架以及SQL之上的一个通用的查询框架。 借助QueryDSL可以在任何支持的ORM框架或者SQL平台上以一种通用的API方式来构建查询。目前QueryDSL支持的平台包括JPA,JDO,SQL,Java Collections,Mongodb,L

木一番的博客 5294

querydsl动态 sql_QueryDSL-JPA

QueryDSL-JPAQueryDSL简介1 QueryDSL仅仅是一个通用的查询框架,专注于通过Java API构建类型安全的SQL查询。2 Querydsl可以通过一组通用的查询API为用户构建出适合不同类型ORM框架或者是SQL的查询语句,也就是说QueryDSL是基于各种ORM框架以及SQL之上的一个通用的查询框架。3 借助QueryDSL可以在任何支持的ORM框架或者SQL平台上以一种...

weixin_39954569的博客 827

SpringDataJPA+QueryDSL玩转态动条件/投影查询

在本文之前,本应当专门有一篇博客讲解SpringDataJPA使用自带的Specification+JpaSpecificationExecutor去说明如何玩条件查询,但是看到新奇、编码更简单易懂的技术总是会让人感到惊喜,而且QueryDSL对SpringDataJPA有着完美的支持。如果你没有使用过自带的Specification去做复杂查询,不用担心,本节分享的QueryDSL技术与Sp...

Caizhfy的博客 5万+

JPA+QueryDSL

工作需要,接触到了QueryDSL,总结使用方法,参考了几个大佬的文章,对我帮助很大

Caiden_Michael 3361

QueryDSL介绍

1,QueryDSL仅仅是一个通用的查询框架,专注于通过Java API构建类型安全的SQL查询。 2,Querydsl可以通过一组通用的查询API为用户构建出适合不同类型ORM框架或者是SQL的查询语句,也就是说QueryDSL是基于各种ORM框架以及SQL之上的一个通用的查询框架。 3,借助QueryDSL可以在任何支持的ORM框架或者SQL平台上以一种通用的API方式来构建查询。目前Qu

风雨中的小书生 1万+

快速入门Springboot整合DataJPA、QueryDSL操作数据库

springboot整合jpa

玩转Java 1784

JPA 和 QueryDSL

spring boot-jpa整合QueryDSL 参考地址 QueryDSL和 JPA分别是什么,为什么合起来用 最近写项目,使用到了 Jpa 这个 ORM 规范支持,使用注解的方式实现 Sql ,但是用过 Jpa 的同学都知道 Jpa 对于单表操作很灵活,但是对于复杂一些的 SQL 就是很不友好了,所以这个地方我们就用到了 QueryDSL 来实现复杂的 Sql 总结:JPA可以通过注解方式...

飘然生的博客 4408
上一篇: MySQL-5.6.13 基本设置及其主从数据库
下一篇: ssh无密码远程登录失败终极解决方案
青青轻风
博客等级 码龄16年 1粉丝 10原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值