一起来学 SpringBoot 2.x | 第六篇:整合 Spring Data JPA

Spring Boot 菜鸟教程 2 Data JPA Spring Data JPA 用来简化创建 JPA 数据访问层和跨存储的持久层功能。 官网文档连接 http://docs.spring.io/spring-data/jpa/docs/current/reference/html/ Spring Data JPA提供的接口 Repository:最顶层的接口,是一个空的接口,目的是为了统一所有Repository的类型,且能让组 阅读详情

点击上方“芋道源码”,选择“置顶公众号”

技术文章第一时间送达!

源码精品专栏

 

摘要: 原文可阅读 http://www.iocoder.cn/Spring-Boot/battcn/v2-orm-jpa/ 「唐亚峰」欢迎转载,保留摘要,谢谢!

  • JPA

  • Spring Data JPA

  • 导入依赖

  • 连接数据库

  • JPA配置

  • 输出日志

  • 数据库类型

  • 具体编码

  • 实体类

  • Repository

  • 测试

  • 总结

  • 说点什么


SpringBoot 是为了简化 Spring 应用的创建、运行、调试、部署等一系列问题而诞生的产物,自动装配的特性让我们可以更好的关注业务本身而不是外部的XML配置,我们只需遵循规范,引入相关的依赖就可以轻易的搭建出一个 WEB 工程

上一篇介绍了Spring JdbcTemplate的使用,对比原始的JDBC而言,它更加的简洁。但随着表的增加,重复的CRUD工作让我们苦不堪言,这时候Spring Data Jpa的作用就体现出来了…..

JPA

JPA是Java Persistence API的简称,中文名Java持久层API,是官方(Sun)在JDK5.0后提出的Java持久化规范。其目的是为了简化现有JAVA EE和JAVA SE应用开发工作,以及整合现有的ORM技术实现规范统一

JPA的总体思想和现有Hibernate、TopLink、JDO等ORM框架大体一致。总的来说,JPA包括以下3方面的技术:

  • ORM映射元数据: 支持XML和注解两种元数据的形式,元数据描述对象和表之间的映射关系,框架据此将实体对象持久化到数据库表中;

  • API: 操作实体对象来执行CRUD操作,框架在后台替代我们完成所有的事情,开发者从繁琐的JDBC和SQL代码中解脱出来。

  • 查询语言: 通过面向对象而非面向数据库的查询语言查询数据,避免程序的SQL语句紧密耦合。

JPA只是一种规范,它需要第三方自行实现其功能,在众多框架中Hibernate是最为强大的一个。从功能上来说,JPA就是Hibernate功能的一个子集。Hibernate 从3.2开始,就开始兼容JPA。同时Hibernate3.2获得了Sun TCK的JPA(Java Persistence API) 兼容认证。

Spring Data JPA

常见的ORM框架中Hibernate的JPA最为完整,因此Spring Data JPA 是采用基于JPA规范的Hibernate框架基础下提供了Repository层的实现。Spring Data Repository极大地简化了实现各种持久层的数据库访问而写的样板代码量,同时CrudRepository提供了丰富的CRUD功能去管理实体类。

优点

  • 丰富的API,简单操作无需编写额外的代码

  • 丰富的SQL日志输出

缺点

  • 学习成本较大,需要学习HQL

  • 配置复杂,虽然SpringBoot简化的大量的配置,关系映射多表查询配置依旧不容易

  • 性能较差,对比JdbcTemplate、Mybatis等ORM框架,它的性能无异于是最差的

导入依赖

在 pom.xml 中添加 spring-boot-starter-data-jpa 的依赖

<!-- Spring JDBC 的依赖包,使用 spring-boot-starter-jdbc 或 spring-boot-starter-data-jpa 将会自动获得HikariCP依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MYSQL包 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 默认就内嵌了Tomcat 容器,如需要更换容器也极其简单-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 测试包,当我们使用 mvn package 的时候该包并不会被打入,因为它的生命周期只在 test 之内-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

连接数据库

在application.properties中添加如下配置。值得注意的是,SpringBoot默认会自动配置DataSource,它将优先采用HikariCP连接池,如果没有该依赖的情况则选取tomcat-jdbc,如果前两者都不可用最后选取Commons DBCP2。通过spring.datasource.type属性可以指定其它种类的连接池

spring.datasource.url=jdbc:mysql://localhost:3306/chapter5?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false
spring.datasource.password=root
spring.datasource.username=root
#spring.datasource.type
# JPA配置
spring.jpa.hibernate.ddl-auto=update
# 输出日志
spring.jpa.show-sql=true
# 数据库类型
spring.jpa.database=mysql

ddl-auto 几种属性

  • create: 每次运行程序时,都会重新创建表,故而数据会丢失

  • create-drop: 每次运行程序时会先创建表结构,然后待程序结束时清空表

  • upadte: 每次运行程序,没有表时会创建表,如果对象发生改变会更新表结构,原有数据不会清空,只会更新(推荐使用)

  • validate: 运行程序会校验数据与数据库的字段类型是否相同,字段不同会报错

具体编码

由于上面我们采用的是spring.jpa.hibernate.ddl-auto=update方式,因此这里可以跳过手动建表的操作

实体类

JPA规范注解坐落在javax.persistence包下,@Id注解一定不要引用错了,否则会报错。@GeneratedValue(strategy = GenerationType.IDENTITY)自增策略,不需要映射的字段可以通过@Transient注解排除掉

常见的几种自增策略

  • TABLE: 使用一个特定的数据库表格来保存主键

  • SEQUENCE: 根据底层数据库的序列来生成主键,条件是数据库支持序列。这个值要与generator一起使用,generator 指定生成主键使用的生成器(可能是orcale中自己编写的序列)。

  • IDENTITY: 主键由数据库自动生成(主要是支持自动增长的数据库,如mysql)

  • AUTO: 主键由程序控制,也是GenerationType的默认值。

package com.battcn.entity;

import javax.persistence.GenerationType;
import javax.persistence.Id;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import java.io.Serializable;

/**
 * @author Levin
 * @since 2018/5/7 0007
 */
@Entity(name = "t_user")
public class User implements Serializable {

    private static final long serialVersionUID = 8655851615465363473L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password;
    /**
     * TODO 忽略该字段的映射
     */
    @Transient
    private String  email;

    // TODO  省略get set
}

Repository

创建UserRepository数据访问层接口,需要继承JpaRepository<T,K>,第一个泛型参数是实体对象的名称,第二个是主键类型。只需要这样简单的配置,该UserRepository就拥常用的CRUD功能,JpaRepository本身就包含了常用功能,剩下的查询我们按照规范写接口即可,JPA支持@Query注解写HQL,也支持findAllByUsername这种根据字段名命名的方式(强烈推荐IntelliJ IDEA对JPA支持非常NICE)

package com.battcn.repository;

import com.battcn.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * t_user 操作
 *
 * @author Levin
 * @since 2018/5/7 0007
 */
@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    /**
     * 根据用户名查询用户信息
     *
     * @param username 用户名
     * @return 查询结果
     */
    List<User> findAllByUsername(String username);
}

测试

完成数据访问层接口后,最后编写一个junit测试类来检验代码的正确性。

下面的几个操作中,只有findAllByUsername是我们自己编写的代码,其它的都是继承自JpaRepository接口中的方法,更关键的是分页及排序是如此的简单实例化一个Pageable即可…

package com.battcn;

import com.battcn.entity.User;
import com.battcn.repository.UserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 * @author Levin
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class Chapter5ApplicationTests {

    private static final Logger log = LoggerFactory.getLogger(Chapter5ApplicationTests.class);

    @Autowired
    private UserRepository userRepository;

    @Test
    public void test1() throws Exception {
        final User user = userRepository.save(new User("u1", "p1"));
        log.info("[添加成功] - [{}]", user);
        final List<User> u1 = userRepository.findAllByUsername("u1");
        log.info("[条件查询] - [{}]", u1);
        Pageable pageable = PageRequest.of(0, 10, Sort.by(Sort.Order.desc("username")));
        final Page<User> users = userRepository.findAll(pageable);
        log.info("[分页+排序+查询所有] - [{}]", users.getContent());
        userRepository.findById(users.getContent().get(0).getId()).ifPresent(user1 -> log.info("[主键查询] - [{}]", user1));
        final User edit = userRepository.save(new User(user.getId(), "修改后的ui", "修改后的p1"));
        log.info("[修改成功] - [{}]", edit);
        userRepository.deleteById(user.getId());
        log.info("[删除主键为 {} 成功] - [{}]", user.getId());
    }
}

总结

更多内容请参考官方文档

目前很多大佬都写过关于 SpringBoot 的教程了,如有雷同,请多多包涵,本教程基于最新的 spring-boot-starter-parent:2.0.1.RELEASE编写,包括新版本的特性都会一起介绍…

说点什么

全文代码:https://github.com/battcn/spring-boot2-learning/tree/master/chapter5

666. 彩蛋



如果你对 Dubbo 感兴趣,欢迎加入我的知识星球一起交流。


知识星球

目前在知识星球(https://t.zsxq.com/2VbiaEu)更新了如下 Dubbo 源码解析如下:

01. 调试环境搭建
02. 项目结构一览
03. 配置 Configuration
04. 核心流程一览

05. 拓展机制 SPI

06. 线程池

07. 服务暴露 Export

08. 服务引用 Refer

09. 注册中心 Registry

10. 动态编译 Compile

11. 动态代理 Proxy

12. 服务调用 Invoke

13. 调用特性 

14. 过滤器 Filter

15. NIO 服务器

16. P2P 服务器

17. HTTP 服务器

18. 序列化 Serialization

19. 集群容错 Cluster

20. 优雅停机

21. 日志适配

22. 状态检查

23. 监控中心 Monitor

24. 管理中心 Admin

25. 运维命令 QOS

26. 链路追踪 Tracing

...
一共 60 篇++

springboot1.5.x升级到springboot2.x 解决方案 pageRequest的过时 更改为 Pageable pageable = PageRequest.of(pageIndex,pageSize,sort); 注解@NotEmpty @Email过时 重新导入@javax.validation.constraints包下的相关注解 ElasticSearch与SpringBoot整合相关错误 3.1 Es实体注解 改为@Field... 阅读详情

相关推荐

spring boot 2.1学习笔记【六】SpringBoot 2集成MySQL,Spring Data JPA

springboot 2.1 使用 springdataJPA 集成 MySQL

刘本龙的专栏 8862

芋道 Spring Boot MyBatis 入门(四)之 tkmybatis

点击上方“芋道源码做积极的人,而不是积极废人!源码精品专栏摘要: 原创出处 http://www.iocoder.cn/Spring-Boot/MyBatis/ 「芋道源码」欢迎转载,保留摘要,谢谢!1. 概述2. MyBatis + XML2.1 引入依赖2.2 Application2.3 应用配置文件2.4 MyBatis 配置文件2.5 UserDO2.6 UserMapper2.7 简...

芋艿V 519

【SpringBoot 3.x 第3节】集成Spring Data JPA:轻松搞定数据库操作!

🏆本文收录于「滚雪球学SpringBoot」专栏,手把手带你零基础入门Spring Boot,从入门到就业,助你早日登顶实现财富自由🚀;同时,欢迎大家关注&&收藏&&订阅!持续更新中,up!up!up!!

**My Coding Family** 1161

解决Consider defining a bean of type org.springframework.data.redis.core.RedisTemplate in your configu

在学习Springboot+redis整合demo时,搭建好项目启动时报如下错误: *************************** APPLICATION FAILED TO START *************************** Description: Field redisTemplate in jypay.com.spring_cloud_consul_comsu...

developerFBI的专栏 1万+

微带功分器设计与ADS-EM联合仿真实战解析

本文详细解析了微带功分器设计与ADS-EM联合仿真的实战技巧,涵盖特性阻抗计算、ADS原理图设计、版图生成与EM仿真等关键步骤。通过实际案例分享,帮助工程师掌握射频电路设计中的核心技术和调试方法,提升功分器设计效率与性能。

weixin_29280219的博客 454

海康威视iVMS-8700综合安防管理平台 文件读取漏洞复现

HIKVISION iVMS 综合安防管理平台download接口处存在任意文件读取漏洞,攻击者通过构造token绕过身份认证,读取服务器中的目录信息与敏感文件。使系统处于极不安全的状态。

0xSec 3313

beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘com.heima.model.mappers.app.ApShowBehaviorMapper’ available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@o

qq_45311792的博客 827

北斗导航 | SPP、RTK、RTD、PPP-RTK、PPP算法原理,公式及完整matlab代码

开发参考:SPP适合入门学习GNSS定位原理和最小二乘。RTK是工程高精度定位主流方案,但依赖基站。PPP适合无基站区域的广域高精度应用。PPP-RTK是融合两者优点的新一代技术,但系统复杂度最高。· 代码资源:raPPPid(VieVS PPP)是功能完整的MATLAB开源PPP工具箱,支持多系统PPP-AR。MATLAB GPS Toolbox 提供从SPP到PPP的完整功能实现。· 实际应用:农业自动驾驶、无人机航测通常使用网络RTK;大地测量、地壳形变监测常采用PPP事后处理;

尘世冰封的专栏 831

【SpringBoot总结】4. SpringBoot整合Spring Data JPA

一、大致了解下JPA和Spring-data-JPA JPA诞生的缘由是为了整合第三方ORM框架,实现持久化领域的统一,简化现有Java EE和Java SE应用的对象持久化的开发工作。JPA是一套规范,而不是具体的ORM框架,JPA的标准的定制是hibernate作者参与定制的,所以可以理解JPA是Hibernate的一个功能子集。简而言之:JPA是标准接口或持久化规范规范,Hibernate是...

小确幸的博客 5725

AHB—SRAMC项目(结构图,核心代码、Testbench架构)

文章目录一、AHB_SRAMC项目介绍1.1.AHB总线控制单元(ahb_slv_if.v)1.2.SRAM控制单元(sramc_top.v)1.3.主要的传输路径二、结构框图2.1.AHB_SRAMC结构图(重点)2.2.总线控制单元与SRAM控制单元结构图三、部分核心代码(重点理解)四、SystemVerilog Testbench架构(重点)五、目录结构 一、AHB_SRAMC项目介绍 本项...

Mr.翟的博客 3万+

SAP Joule 在顾问与开发者场景的双擎定位:Joule for Consultants 与 Joule for Developers 全面解读

SAP推出企业级AI助手Joule,分为顾问版(Joule for Consultants)和开发者版(Joule for Developers)两个版本。顾问版聚焦咨询业务,整合SAP知识库和方法论,辅助方案设计、差距分析和实施落地;开发者版嵌入开发工具链,支持代码生成、解释、测试和迁移。两者共享智能底座但面向不同场景:顾问版优化项目交付流程,开发者版提升工程效率。典型案例显示,Joule能有效缩短云转型周期,实现从业务咨询到技术落地的无缝衔接。该产品通过AI代理和知识图谱技术,为企业数字化转型提供端到端

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 358

​ Spring Data JPA

​ 创建一个普通的Maven项目。

埃泽漫笔 1345

使用 Visual Studio Code 搭建 SAP UI5 本地开发环境

工欲善其事,必先利其器。时至今日,SAP 提供了非常多的 SAP UI5 开发工具,既包含本地搭建的,也包含浏览器里远端使用的工具,比如 WebIDE 和 Business Application Studio. 我们访问下面这个链接,就能找到所有这些工具的安装或者配置步骤: https://tools.hana.ondemand.com/#sapui5 如果想选择本地开发,SAP 推荐的工具是 Visual Studio Code,也就是本文要介绍的内容。 也可以下载 WebIDE 的本地安装包,将其安

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1万+

初学SpringBoot2.x整合Spring Data JPA的坑。

初学SpringBoot2.x整合Spring Data JPA的坑。 org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field ‘id’ cannot be found on object of type ‘java.util.Optional’ - maybe not publ...

Mr_Simple_V的博客 1133

1.嵌入式控制器EC学习,编译环境搭建

工欲善其事,必先利其器。 在学习EC相关知识之前,首先需要完成EC代码编译环境的搭建,需要如下内容: Keil C51(用于EC中C代码的编译器环境) EC源代码,我们使用从网上可以下载到的 ITE_V12.4_Update 版的代码为例进行学习 代码编辑器,这个可以根据自己的习惯选择,VS Code或者Source Insight等 Keil C51下载地址: http://www.downcc.com/soft/307131.html 下载完成后请进行破解 EC源代码 ...

qq_30135687的博客 3918

30分钟用 Restful ABAP Programming(RAP)模型开发一个支持增删改查的 Fiori 应用

2016年时,Jerry曾经写过一系列关于SAP Fiori Smart Template(现在更名为Fiori Elements了)的博客,介绍了所谓的MDD开发方法论 - Metadata Driven Development,即通过开发维护了对应annotation(注解)的CDS view,结合SAP WebIDE,能够花费最少的编程代价,就能够在短时间内获得一个支持增删改查的Fiori应......

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 5958

【SpringBoot框架篇】11.Spring Data Jpa实战

文章目录简介JPASpring Data JpaHibernateJpa、Spring Data Jpa、Hibernate三者之间的关系应用实战引入依赖配置文件实体类常用注解@Entity和@Table@Id和@GeneratedValue@Column@Transient继承超类的通用字段属性@MappedSuperclass@Inheritance审计功能启用审计功能在启动类里添加注解在需要使用的类上面添加审计监听器审计功能注解添加审计人 简介 首先了解一下 JPA,Spring Data Jpa,之

皓亮君的博客 4341

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

springboot中使用Spring Data Jpa

ORM即Object-Relationl Mapping,它的作用是在关系型数据库和对象之间作一个映射,这样,我们在具体的操作数据库的时候,就不需要再去和复杂的SQL语句打交道,只要像平时操作对象一样操作它就可以了 。在ORM出现之前,我们是用jdbc来操作数据库,但jdbc没有封装,对于大项目来说,使用复杂,也难以实现MVC的概念,所以人们就开发了ORM框架来解决这些问题。比如Hibernate,Mybatis,不过Hibernate是完全的ORM框架,mybatis是半ORM框架,因为它需要手动建表和自

daimenglaoshi的博客 1072

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

深度学习工具包 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")

SpringBoot2.x+Spring Data Jpa整合简书

SpringDataJpa由Spring基于Hibernate开发的一个JPA框架。可以极大的简化JPA的写法,可以在几乎不用写实现的情况下,实现对数据的访问和操作。与SpringBoot整合更是锦上添花,下面我将讲解其用法。 1. 实体类 1 2 3 ...

chuilu8991的博客 501

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

spring-data-jpa-extra: 弹性扩展您的Spring Data JPA体验

spring-data-jpa-extra: 弹性扩展您的Spring Data JPA体验 项目介绍 spring-data-jpa-extra 是一个开源项目,旨在增强Spring Data JPA的功能,特别是针对动态查询的需求。它引入了类似MyBatis模板(如FreeMarker或Velocity)的动态SQL查询能力,使得在Spring Data之上构建更灵活的数据库交互成为可能。对...

gitblog_00965的博客 1177

springboot后台服务搭建(三 整合mysql、spring-data-jpa)

总览:https://blog.csdn.net/qq_22037575/article/details/86687765 本文概要:springboot2.x 整合 mysql、spring-data-jpa 码云:https://gitee.com/RichterGit/csdn/tree/master/springboot-radmin/003/ 目录 1.新建数据库与用户角色表 ...

红缎带的博客 675

SpringBoot整合Spring Data JPA

文章目录本篇要点JPA是啥?Spring Data JPA快速SpringBoot快速整合JPA引入依赖配置ymlddl-auto的几种属性值实体类常见的主键生成策略启动项目,生成表数据访问层测试JPA五、源码下载参考阅读 本篇要点 简单介绍JPA。 介绍快速SpringBoot快速整合JPA JPA是啥? The Java Persistence API is a standard technology that lets you “map” objects to relational da

天乔巴夏丶 614

SpringBoot2.x.x整合Spring Data JPA

一、创建工程 二、配置application.yml spring: datasource: url: jdbc:mysql://192.168.50.36:3307/jpaa username: root password: 123456 # mysql.cj报红可以在pom文件中mysql依赖中删除scope runtime driver-class-name: com.mysql.cj.jdbc.Driver jpa: hibernate:

qq_45100361的博客 316

SpringBoot整合Spring Data JPA步骤

一)修改pom文件 1.添加spring-data-jpa的启动器 2.添加mysql驱动 3.添加数据库连接池 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-...

失忆๑的博客 219

springboot2.x整合spring-data-jpa的问题

今天使用springboot整合spring-data-jpa遇到一些问题,直接使用JpaRepository的getOne()方法是会报错的。报错信息为:org.hibernate.LazyInitializationException: could not initialize proxy - no Session。在SpringBoot1.xx版本应该使用findOne()方法根据...

dd10850的博客 279
上一篇: 【追光者系列】HikariCP 源码分析之 evict、时钟回拨、连接创建生命周期
下一篇: Spring Webflux —— 源码阅读之 handler 包
公众号-芋道源码
博客等级 码龄10年 1640粉丝 377原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值