Spring Boot 连接MySql数据库

使用Spring Boot和JDBC实现MySQL数据库连接与操作 Apache Maven是一个广泛使用的项目管理和构建自动化工具,它利用一个中央仓库的概念来管理项目依赖。Maven通过一个名为pom.xml的项目对象模型(Project Object Model)文件来描述项目信息和依赖配置。在pom.xml文件中,开发者可以声明项目所需的外部库及其版本,Maven将会自动从中央仓库下载这些依赖到本地仓库。Maven的依赖管理机制支持依赖范围(如编译、测试、运行时范围)和依赖传递(transitive dependencies),即依赖自身可能还需要其他库。 阅读详情


Spring Boot 连接MySql数据库


Spring Boot可以大大简化持久化任务,几乎不需要写SQL语句,在之前章节“Spring Boot 构建框架”中我们新建了一个Spring Boot应用程序,本章在原有的工程中与数据库建立连接。


Spring Boot有两种方法与数据库建立连接,一种是使用JdbcTemplate,另一种集成Mybatis,下面分别为大家介绍一下如何集成和使用这两种方式。

1. 使用JdbcTemplate

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>


在resource文件夹下添加application.properties配置文件并输入数据库参数,内容如下:

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=1000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
server.port=8012
server.session.timeout=10
server.tomcat.uri-encoding=UTF-8


新建Controller类测试数据库连接,实例如下:

package com.example.demo;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/mydb")
public class DBController {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @RequestMapping("/getUsers")
    public List<Map<String, Object>> getDbType(){
        String sql = "select * from appuser";
        List<Map<String, Object>> list =  jdbcTemplate.queryForList(sql);
        for (Map<String, Object> map : list) {
            Set<Entry<String, Object>> entries = map.entrySet( );
                if(entries != null) {
                    Iterator<Entry<String, Object>> iterator = entries.iterator( );
                    while(iterator.hasNext( )) {
                    Entry<String, Object> entry =(Entry<String, Object>) iterator.next( );
                    Object key = entry.getKey( );
                    Object value = entry.getValue();
                    System.out.println(key+":"+value);
                }
            }
        }
        return list;
    }
    
    @RequestMapping("/user/{id}")
    public Map<String,Object> getUser(@PathVariable String id){
        Map<String,Object> map = null;
        
        List<Map<String, Object>> list = getDbType();
        
        for (Map<String, Object> dbmap : list) {
            
            Set<String> set = dbmap.keySet();
            
            for (String key : set) {
                if(key.equals("id")){    
                    if(dbmap.get(key).equals(id)){
                        map = dbmap;
                    }
                }
            }
        }
        
        if(map==null)
            map = list.get(0);
        return map;
    }
    
}

运行App输入地址输出数据库数据。


2. 集成Mybatis

 添加mybatis依赖,在pom.xml文件中增加如下:

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>


在resource文件夹下添加application.properties配置文件并输入数据库参数,如下:

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=1000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
server.port=8012
server.session.timeout=10
server.tomcat.uri-encoding=UTF-8


依次添加mapper的接口类和xml文件,类分别如下:

AppMessageMapper.java

package com.example.demo.mapper;
import java.util.List;
import com.example.demo.bean.AppMessage;
public interface AppMessageMapper {
    int deleteByPrimaryKey(String id);
    int insert(AppMessage record);
    int insertSelective(AppMessage record);
    AppMessage selectByPrimaryKey(String id);
    int updateByPrimaryKeySelective(AppMessage record);
    int updateByPrimaryKey(AppMessage record);
    
    List<AppMessage> selectAll();
    List<AppMessage> getMessById(String id);
}


AppMessageMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.demo.mapper.AppMessageMapper" >
  <resultMap id="BaseResultMap" type="com.example.demo.bean.AppMessage" >
    <id column="id" property="id" jdbcType="VARCHAR" />
    <result column="message" property="message" jdbcType="VARCHAR" />
    <result column="senddate" property="senddate" jdbcType="TIMESTAMP" />
  </resultMap>
  
  <sql id="Base_Column_List" >
    id, message, senddate
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select 
    <include refid="Base_Column_List" />
    from appuser_message
    where id = #{id,jdbcType=VARCHAR}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
    delete from appuser_message
    where id = #{id,jdbcType=VARCHAR}
  </delete>
  <insert id="insert" parameterType="com.example.demo.bean.AppMessage" >
    insert into appuser_message (id, message, senddate
      )
    values (#{id,jdbcType=VARCHAR}, #{message,jdbcType=VARCHAR}, #{senddate,jdbcType=TIMESTAMP}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.example.demo.bean.AppMessage" >
    insert into appuser_message
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="message != null" >
        message,
      </if>
      <if test="senddate != null" >
        senddate,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=VARCHAR},
      </if>
      <if test="message != null" >
        #{message,jdbcType=VARCHAR},
      </if>
      <if test="senddate != null" >
        #{senddate,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.example.demo.bean.AppMessage" >
    update appuser_message
    <set >
      <if test="message != null" >
        message = #{message,jdbcType=VARCHAR},
      </if>
      <if test="senddate != null" >
        senddate = #{senddate,jdbcType=TIMESTAMP},
      </if>
    </set>
    where id = #{id,jdbcType=VARCHAR}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.example.demo.bean.AppMessage" >
    update appuser_message
    set message = #{message,jdbcType=VARCHAR},
      senddate = #{senddate,jdbcType=TIMESTAMP}
    where id = #{id,jdbcType=VARCHAR}
  </update>
  
  <select id="selectAll" resultMap="BaseResultMap">
    select 
         id, message, senddate
    from appuser_message
    order by senddate asc
  </select>
  
  <select id="getMessById" resultMap="BaseResultMap" parameterType="java.lang.String">
   select 
           id, message, senddate
   from 
        appuser_message  
       where id = #{id,jdbcType=VARCHAR}
    order by senddate asc  
  </select>
  
</mapper>


AppMessage.java

package com.example.demo.bean;
import java.util.Date;
public class AppMessage {
    private String id;
    private String message;
    private Date senddate;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id == null ? null : id.trim();
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message == null ? null : message.trim();
    }
    public Date getSenddate() {
        return senddate;
    }
    public void setSenddate(Date senddate) {
        this.senddate = senddate;
    }
}


AppMessageService.java

package com.example.demo.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.bean.AppMessage;
import com.example.demo.mapper.AppMessageMapper;
@Service
public class AppMessageService {
    
    @Autowired
    private AppMessageMapper mapper;
    
    public List<AppMessage> getMessage(){
         List<AppMessage> list = new ArrayList<AppMessage>();
         list.add(mapper.selectByPrimaryKey("xtt"));
         //list = mapper.selectAll();
         return list;
    }
    
    public List<AppMessage> getAllMessage(){
         List<AppMessage> list = new ArrayList<AppMessage>();
         list = mapper.selectAll();
         return list;
    }
    public int addMessage(AppMessage appMessage) {
        return mapper.insert(appMessage);
    }
    public List<AppMessage> getMessageById(String id) {
        return mapper.getMessById(id);
    }
    public int delMessage(String id) {
        return mapper.deleteByPrimaryKey(id);
    }
}


APPMessageController.java

package com.example.demo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.bean.AppMessage;
import com.example.demo.service.AppMessageService;
@RestController
@RequestMapping("/appmessage")
public class APPMessageController {
    @Autowired
    private AppMessageService service;
    @RequestMapping("/getThree")
    public List<AppMessage> getThreeForMessage(){
        
        List<AppMessage> list = service.getMessage();        
        return list;
    }
    
    @RequestMapping("/getAll")
    public List<AppMessage> getAllMessage(){
        
        List<AppMessage> list = service.getAllMessage();
        int num = list.size();
        if(null!=list && num>3){
            for (int i = 0; i < num-3; i++) {
                list.remove(0);
            }
        }
        return list;
    }
    @RequestMapping("/getByID")
    public List<AppMessage> getMessageById(@RequestParam("id") String id){
        List<AppMessage> list = service.getMessageById(id);
        int num = list.size();
        if(null!=list && num>5){
            for (int i = 0; i < num-5; i++) {
                list.remove(0);
            }
        }
        return list;
    }
    
    @RequestMapping(value = "/add",method = RequestMethod.POST) // 或者采用@PostMapping("/add")方法,更加节省代码的编写量
    public int addMessage(@RequestBody AppMessage appMessage){
        return service.addMessage(appMessage);
    }
    
    @RequestMapping(value="/delMessageById",method=RequestMethod.POST) // 或者采用@PostMapping("/delMessageById")方法,更加节省代码的编写量
    public int delMessageById(@RequestParam("id") String id){
            return service.delMessage(id);
    }
}


问题描述?

SpringBoot扫描包提示找不到mapper的问题,异常信息:

Consider defining a bean of type in your configuration

分析原因

Spring Boot项目的Bean装配默认规则是根据Application类所在的包位置从上往下扫描,“Application类”是指Spring Boot项目入口类。如果Application类所在的包为:com.yoodb.blog,则只会扫描com.yoodb.blog包及其所有子包,如果service或dao所在包不在com.yoodb.blog及其子包下,则不会被扫描。

解决方法

方式一:使用注解@ComponentScan(value=”com.yoodb.blog”),其中,com.yoodb.blog为包路径。

方式二:将启动类Application放在上一级包中,注意的是Application启动类必须要保证在包的根目录下。

Spring配置数据源(连接池) 一.数据源(连接池的作用)1.数据源(连接池)是提高程序性能如2.事先实例化数据源,初始部分连接资源3.使用来连接资源时从数据源获取4.使用完毕时将连接资源归还给数据源二、数据源的开发步骤步骤:① 导入数据源的坐标和数据库驱动坐标② 创建数据源对象③ 设置数据源的基本连接数据④ 使用数据源获取连接资源和归还连接资源传统方式写法1.导入依赖坐标和数据驱动坐标2.创建数据源的手动创建2.1 创建C3p0连接池2.2创建Druid连接池。 阅读详情

相关推荐

第一个搭建SpringBoot项目(连接mysql)

首先新建项目找到Spring Initializr 我使用的URL是这里最低的JDK版本是17,而且当网速不好的时候可能会显示超时,这里可以选用阿里云的镜像可以更快一些但是里面还是有一些区别的我们这里选择Java语言,Maven框架在这里我们选择一些我们需要用到的这个版本可以选低一点更加稳定进来之后我们需要先等pom文件加载,我们可以选择刷新Maven加载完之后由于我们加载了MySQL所以还不能运行可以先注释掉,然后刷新maven。

qq_63126439的博客 3801

【已解决】org.springframework.jdbc.core.JdbcTemplate in your configuration

【已解决】Consider defining a bean of type 'org.springframework.jdbc.core.JdbcTemplate' in your configuration

qq_40154083的博客 6326

Spring Boot 自动配置数据源及操作数据库(1)

光给面试题不给答案不是我的风格。这里面的面试题也只是凤毛麟角,还有答案的话会极大的增加文章的篇幅,减少文章的可读性。

2401_83817171的博客 991

Consider defining a bean of type 'org.springframework.jdbc.core.JdbcTemplate' in your configuration

报错信息: Description: Field customerRepo in com.chnvas.tour.auth.controller.AuthController required a bean of type 'org.springframework.jdbc.core.JdbcTemplate' that could not be found. Action: Consi...

嘻哈熊的专栏 1万+

Spring boot+MyBatis连接Mysql时遇到Could not create connection to database server的问题

制作了一个Spring boot 整合 mybatis连接mysql的小demo,从数据库读取数据再返回到前端,实现最基本的查询功能 但是遇到启动的时候遇到报错 Could not create connection to database server. Attempted reconnect 3 times.Giving up **1.**检查url没有发现问题 **2.**在cmd也能...

qq_39187063的博客 1319

Spring Boot连接MySQL数据库实战指南

数据库连接是Java企业级开发中的核心技术,Spring Boot通过自动配置简化了这一过程。JDBC作为Java数据库连接的标准API,配合连接池技术(如HikariCP)能有效管理数据库资源。在微服务架构下,ORM框架如Spring Data JPA进一步简化了数据持久化操作。本文以MySQL 8.0为例,详解Spring Boot项目中如何配置数据源、优化连接池参数,并实现CRUD操作。针对MySQL驱动版本、时区设置等常见问题提供解决方案,帮助开发者快速构建稳健的数据库访问层。

weixin_33883104的博客 355

【Java】在 Spring Boot 中连接 MySQL 数据库

摘要:本文详细介绍了在Spring Boot中连接MySQL数据库的完整步骤。首先需要添加spring-boot-starter-data-jpa和mysql-connector-java依赖,然后在配置文件中设置数据库连接参数。接着创建实体类映射数据库表、通过JpaRepository接口实现数据访问、编写服务层业务逻辑以及控制器处理HTTP请求。最后提供API测试方法和常见问题解决方案,包括连接失败时的排查建议。整个过程展示了Spring Boot自动配置的优势,使数据库集成变得简单高效。

u011144881的博客 1450

使用Spring Boot连接和操作数据库(MySQL、PostgreSQL等)

🏆 本文精选收录于《滚雪球学SpringBoot》专栏,专为零基础学习者量身打造。从Spring基础到项目实战,手把手带你掌握核心技术,助力你快速提升,迈向职场巅峰,开启财富自由之路🚀!无论你是刚入门的小白,还是已有基础的开发者,都能在这里找到适合自己的学习路径!    🌟 关注、收藏、订阅,持续更新中!和我们一起高速成长,突破自我!💡

**My Coding Family** 1945

springboot连接mysql_Spring Boot高级教程之Spring Boot连接MySql数据库

Spring Boot可以大大简化持久化任务,几乎不需要写SQL语句,在之前章节“Spring Boot 构建框架”中我们新建了一个Spring Boot应用程序,本章在原有的工程中与数据库建立连接。Spring Boot有两种方法与数据库建立连接,一种是使用JdbcTemplate,另一种集成Mybatis,下面分别为大家介绍一下如何集成和使用这两种方式。1. 使用JdbcTemplatemys...

weixin_32944341的博客 723

Labview程序框架介绍

当掌握LabVIEW基础知识并达到,理解单个小型模块程序会相对轻松。而若想进一步探索大型程序,就必然需要了解程序框架相关内容。LabVIEW常用的程序架构包括等。在多年工作中,我接触过的众多高级工程师所开发的大型程序,基本都基于这些架构搭建。接下来,将为大家详细介绍这些框架。

Misterlhw的博客 4617

【Unity】制作简易三维场景

本文介绍如何制作一个三维场景

CiNian_的博客 5331

Spring Boot 3 集成 MyBatis 连接 MySQL 数据库

Spring Boot 3 默认使用 HikariCP 连接池,通过。如果 XML 与 Mapper 接口不在同一包,需在。如果 XML 文件未被编译到。确保 MySQL 数据库。

wh_xia_jun的专栏 1357

Cadence Virtuoso VIVA波形分析:从背景色修改到线宽调整的完整指南

本文详细介绍了Cadence Virtuoso VIVA波形分析工具的核心使用技巧,包括背景色修改、线宽调整等高级功能。通过具体操作步骤和配置方法,帮助工程师优化波形显示效果,提升工作效率。特别强调了与Calculator组件的配合使用,以及专业波形图的输出技巧。

weixin_27330481的博客 620

Spring boot创建项目和连接Mysql数据库整合

通过本文的指导,你已经成功地创建了一个Spring Boot项目,并将其与MySQL数据库进行了连接。你可以根据需要进一步扩展这个项目,添加更多的实体类、Repository接口、Service类和Controller类来构建完整的Web应用程序。同时,你也可以使用Spring Boot提供的各种功能和特性来优化和增强你的应用程序。

hejitao的博客 2266

2025认证杯数学建模第二阶段B题完整论文(代码齐全):谣言在社交网络上的传播

这需要我们深入理解抽样检测所得的次品率的不确定性及其对生产决策的影响。对于问题二的决策分析,我们可将其细分为四个关键的决策节点,分别是零件 1 的质量检测、零件 2 的质量检测、成品的质量检测,以及成品检测不合格时的拆解处理。该策略的实施,保证了在算法迭代过程中,表现最为优异的个体能够得到保留,并顺利传递至下一代,从而保障了算法在寻求最优解过程中的收敛性和优化效果。因此,我们采用假设检验的方法,将次品分布构造成 t 分布,从而确定在相应置信度的条件下,抽样次数 n 和次品数 k 所需满足的要求。

2301_81596622的博客 1007

配置思科交换机冗余链路汇聚

本文对交换机端口汇聚配置进行说明

istrangeboy&begin zero的博客 6684

springboo如何连接mysql_Spring Boot——三种方式连接数据库

使用数据库是开发应用的基本基础,那么,使用Spring Boot如何连接数据库呢?前提,需要知道如何建一个Spring Boot项目,可参照:https://www.jianshu.com/p/d6e6c84cd190一、准备工作:1、建一个简单的数据库,名为springboot_db,在其下建一个表,名为t_author,脚本如下:CREATE DATABASE /*!32312 IF NOT ...

weixin_31306591的博客 1043

通达信短周期指标盘中实时监控与预警选股实战

本文详细介绍了通达信短周期指标在盘中实时监控与预警选股中的实战应用。通过分时指标改造、多股同列监控技巧及预警策略优化,帮助短线交易者捕捉转瞬即逝的交易机会,提升选股效率与准确性。重点解析了如何避免假信号干扰及系统卡顿问题,并探讨了从预警到自动交易的进阶应用。

weixin_29230805的博客 888

【系统设计】使用Spring Boot连接MySQL数据库

在现代的Web开发中,数据库是不可或缺的一部分。Spring Boot作为一个快速开发的框架,提供了非常便捷的方式来连接和操作数据库。本文将详细介绍如何使用Spring Boot连接MySQL数据库,并附上相关代码示例。

qq_45729306的博客 3029

实战分享:如何用Jetson Nano+HM30图传搭建低空YOLOv5检测系统(附VNC避坑指南)

本文详细介绍了如何利用Jetson Nano和HM30图传搭建低空YOLOv5检测系统,重点解决了无人机应用中的硬件连接和VNC延迟优化问题。通过对比WiFi直连与图传方案的优劣,提供了网络配置、VNC优化及YOLOv5模型加速的实战技巧,帮助开发者实现高效稳定的低空目标检测系统。

weixin_29174385的博客 110

第十二章 供水管网水力模型软件介绍

本文介绍了国内外主要供水管网建模软件及其特点,重点分析了某高建模软件V14的创新功能。国际主流软件包括开源的EPANET、商业软件InfoWorksWS、WaterGEMS和MIKEURBAN,各具特色但存在应用局限。某高V14软件实现了管网GIS与模型一体化管理,采用一G多网、一网多模、一模多案、网模合一技术路线,支持全信息模型建立和动态数据更新。其创新点包括水量分配理念革新(精确/模糊匹配、三种用水模式)和首创Web服务功能。通过并发计算、GPU加速等技术优化性能,具有较高性价比。

weixin_45258875的博客 207

【Spring Boot】MyBatis入门:连接Mysql数据库、测试单元、连接的常见错误

本文以MyBatis框架为核心,系统讲解了其作为持久层框架的核心价值与快速入门实践。首先介绍MyBatis专注于简化JDBC开发,通过映射机制实现数据库与Java对象的高效交互。随后通过Spring Boot项目实战演示:配置MyBatis与MySQL依赖、创建包含deleteFlag等字段的UserInfo实体类、编写Mapper接口并使用@Select注解实现数据查询。针对单元测试中出现的空指针问题,指出需添加@SpringBootTest注解以加载Spring上下文。

Code哈哈笑的博客 2176

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

Spring Boot 入门:如何连接 MySQL 数据库

Mapper 接口是 MyBatis 的 “入口”,定义查询、新增等方法,不用写实现类(MyBatis 自动生成)。今天我们完成了从 “模拟数据” 到 “真实数据库” 的跨越,学会了:用 SQL 脚本批量创建数据库、表和测试数据,高效且便于团队协作;用 YAML 格式配置 Spring Boot,结构更清晰,减少配置冗余;用 MyBatis 写 Mapper 接口和 XML,灵活控制 SQL 语句;用 ApiFox 测试接口,快速验证数据库操作结果。

weixin_42847133的博客 1275

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Spring Boot中配置MySQL数据库的连接数

如果我们需要更复杂的配置或想要完全自定义数据源,我们可以创建一个配置类并使用@Bean注解来定义我们的数据源。但是,对于大多数应用来说,使用或文件中的配置就足够了。

s44359487yad的博客 1466

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

springboot 数据库假面_Spring Boot 连接MySql数据库

Spring Boot 以后也许会成为入门Spring的首选!记一下Spring Boot 成功连接Mysql数据库的方法步骤!一、新建Maven工程,不全Maven所需文件夹,在pom.xml引入SpringBoot的依赖包!可以参照:http://www.cnblogs.com/liangblog/p/5207855.html二、有两种方法与数据库建立连接,一种是集成Mybatis,另一种用J...

weixin_39992417的博客 138

spring连接mysql实例_spring boot 实例之 连接数据库

前面的体验告一段落了。这里开始,做些实际业务的服务。一般情况,服务是需要连接数据库的。我们先从数据库连接开始。选择MySQL数据库新建模块在前面的bhparent下面建立一个模块选择类型模块名称先来个用户管理的服务,命名为bh-user。选择填写信息稍微调整下目录目录pom.xml文件内容xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 h...

weixin_35740814的博客 471
上一篇: SQL中EXISTS的用法
下一篇: javascript如何设置DIV背景色为随机色
Java_2017_csdn
博客等级 码龄10年 329粉丝 49原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值