使用Hibernate完成增删改查

hibanate实现数据库批量插入或批量更新的工具方法 MySql 一、批量插入 /** * * @author 陈笑璞 * @Title: batchSaveMySQL * @Description: mysql批量插入的工具类 * @param entityManager entityManager service的getEm() * @param table 表名 * @param list 数据列表 * @param fields 字段列表 * @throws CustomEx 阅读详情

1.hibernate的简介

  1. 概念

Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。 Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用,最具革命意义的是,Hibernate可以在应用EJB的JaveEE架构中取代CMP,完成数据持久化的重任。

  1. 语言特点

①将对数据库的操作转换为对Java对象的操作,从而简化开发。通过修改一个“持久化”对象的属性从而修改数据库表中对应的记录数据。
②提供线程和进程两个级别的缓存提升应用程序性能。
③有丰富的映射方式将Java对象之间的关系转换为数据库表之间的关系。
④屏蔽不同数据库实现之间的差异。在Hibernate中只需要通过“方言”的形式指定当前使用的数据库,就可以根据底层数据库的实际情况生成适合的SQL语句。
⑤非侵入式:Hibernate不要求持久化类实现任何接口或继承任何类,POJO即可。

  1. 工作原理

1、通过Configuration().configure();读取并解析hibernate.cfg.xml配置文件。
2、由hibernate.cfg.xml中的<mappingresource=“com/xx/User.hbm.xml”/>读取解析映射信息。
3、通过config.buildSessionFactory();//得到sessionFactory。
4、sessionFactory.openSession();//得到session。
5、session.beginTransaction();//开启事务。
6、persistent operate;
7、session.getTransaction().commit();//提交事务
8、关闭session;
9、关闭sessionFactory;

  1. 优点

1、封装了jdbc,简化了很多重复性代码。
2、简化了DAO层编码工作,使开发更对象化了。
3、移植性好,支持各种数据库,如果换个数据库只要在配置文件中变换配置就可以了,不用改变hibernate代码。(跨数据库的无缝移植)
4、支持透明持久化,因为hibernate操作的是纯粹的(pojo)java类,没有实现任何接口,没有侵入性。所以说它是一个轻量级框架。

2.项目中添加Hibernate支持

2-1.添加hibernate相关依赖,web.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.hsl</groupId>
  <artifactId>T237_hibernate</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>T237_hibernate Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <!--易于改变包的版本-->
  <properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
		<junit.version>4.12</junit.version>
		<servlet.version>4.0.0</servlet.version>
		<hibernate.version>5.3.0.Final</hibernate.version>
		<mysql.driver.version>5.1.46</mysql.driver.version>
	</properties>
  <dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${servlet.version}</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate.version}</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.driver.version}</version>
		</dependency>
	</dependencies>
  <build>
    <finalName>hibernate</finalName>
    <plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.7.0</version>
				<configuration>
					<source>${maven.compiler.source}</source>
					<target>${maven.compiler.target}</target>
					<encoding>${project.build.sourceEncoding}</encoding>
				</configuration>
			</plugin>
		</plugins>
  </build>
</project>

web.xml配置

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
	id="WebApp_ID" version="3.1">
  <display-name>Archetype Created Web Application</display-name>
</web-app>


2-2.在resource目录下添加hibernate.cfg.xml(核心配置文件)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!-- 1. 数据库相关 -->
		<property name="connection.username">root</property><!--用户名-->
		<property name="connection.password">1234</property><!--密码-->
		<property name="connection.url">jdbc:mysql://localhost:3306/root?useUnicode=true&amp;characterEncoding=UTF-8
		</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

		<!-- 配置本地事务(No CurrentSessionContext configured!) -->
		<property name="hibernate.current_session_context_class">thread</property>

		<!-- 2. 调试相关 -->
		<property name="show_sql">true</property>
		<property name="format_sql">true</property>

		<!-- 3. 添加实体映射文件 -->
		<mapping resource="com/hsl/one/entity/User.hbm.xml" />
	</session-factory>
</hibernate-configuration>

2-3.在开发阶段再创建实体类和实体映射文件(*.hbm.xml)

实体类:

package com.hsl.one.entity;

import java.sql.Date;
import java.sql.Timestamp;

public class User {
	private Integer id;
	private String userName;
	private String userPwd;
	private String realName;
	private String sex;
	private Date birthday;
	private Timestamp createDatetime;
	private String remark;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserPwd() {
		return userPwd;
	}
	public void setUserPwd(String userPwd) {
		this.userPwd = userPwd;
	}
	public String getRealName() {
		return realName;
	}
	public void setRealName(String realName) {
		this.realName = realName;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public Timestamp getCreateDatetime() {
		return createDatetime;
	}
	public void setCreateDatetime(Timestamp createDatetime) {
		this.createDatetime = createDatetime;
	}
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	public User(Integer id, String userName, String userPwd, String realName, String sex, Date birthday,
			Timestamp createDatetime, String remark) {
		super();
		this.id = id;
		this.userName = userName;
		this.userPwd = userPwd;
		this.realName = realName;
		this.sex = sex;
		this.birthday = birthday;
		this.createDatetime = createDatetime;
		this.remark = remark;
	}
	public User() {
		super();
	}
	public User(String userName, String userPwd, String realName, String sex, Date birthday, Timestamp createDatetime,
			String remark) {
		super();
		this.userName = userName;
		this.userPwd = userPwd;
		this.realName = realName;
		this.sex = sex;
		this.birthday = birthday;
		this.createDatetime = createDatetime;
		this.remark = remark;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", userName=" + userName + ", userPwd=" + userPwd + ", realName=" + realName
				+ ", sex=" + sex + ", birthday=" + birthday + ", createDatetime=" + createDatetime + ", remark="
				+ remark + "]";
	}
}

   User.hbm.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!--
	clas标签下的属性:
	name:数据库中的表映射的类的全路径名
	table:要映射的表名
	
	id标签:用于标识主键的
	name:数据库表的列段映射到实体类中的属性名
	type:属性的类型
	column:数据库表中的列段
	
	
	property标签:
	name:数据库表的列段映射到实体类中的属性名
	type:属性的类型
	column:数据库表中的列段
	

 	 -->

	<class name="com.hsl.one.entity.User" table="t_hibernate_user">
		<id name="id" type="java.lang.Integer" column="id">
			<generator class="increment" />
		</id>
		<property name="userName" type="java.lang.String" column="user_name">
		</property>
		<property name="userPwd" type="java.lang.String" column="user_pwd">
		</property>
		<property name="realName" type="java.lang.String" column="real_name">
		</property>
		<property name="sex" type="java.lang.String" column="sex">
		</property>
		<property name="birthday" type="java.sql.Date" column="birthday">
		</property>
		<property insert="false" update="false" name="createDatetime"
			type="java.sql.Timestamp" column="create_datetime">
		</property>
		<property name="remark" type="java.lang.String" column="remark">
		</property>
	</class>

</hibernate-mapping>

3.实现增删改查功能

增
package com.hsl.one.text;

import java.sql.Date;
import java.sql.Timestamp;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.hsl.one.entity.User;

/**
 * hibernate的添加
 * @author Administrator
 *
 */
public class AddDome {
	public static void main(String[] args) {
		/*
		 * 1,对hibernate.cfg.xml核心配置文件进行建模
		 * 2,建模后的对象获取sessionfactory对象,sessionfactory对象中包含了数据库的相关信息
		 * 3,通过sessionfactory对象获取session会话
		 * 4,session开启事务
		 * 5,操作数据库
		 * 6,提交事务(查询中不需要)
		 * 7,释放资源
		 */
		Configuration configure=new Configuration().configure("/hibernate.cfg.xml");
		SessionFactory sessionFactory=configure.buildSessionFactory();
		Session session=sessionFactory .openSession();
		Transaction transaction=session.beginTransaction();
		User user=new User(16, "a1", "123123", "xxxx", "男",new Date(System.currentTimeMillis()) , new Timestamp(System.currentTimeMillis()), "lalalal");
		session.save(user);
		
		transaction.commit();
		session.close();
	}
}

结果展示:
在这里插入图片描述

在这里插入图片描述

删
package com.hsl.one.text;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.hsl.one.entity.User;

/**
 * hibernate的添加
 * @author Administrator
 *
 */
public class DeleteDome {
	public static void main(String[] args) {
		/*
		 * 1,对hibernate.cfg.xml核心配置文件进行建模
		 * 2,建模后的对象获取sessionfactory对象,sessionfactory对象中包含了数据库的相关信息
		 * 3,通过sessionfactory对象获取session会话
		 * 4,session开启事务
		 * 5,操作数据库
		 * 6,提交事务(查询中不需要)
		 * 7,释放资源
		 */
		Configuration configure=new Configuration().configure("/hibernate.cfg.xml");
		SessionFactory sessionFactory=configure.buildSessionFactory();
		Session session=sessionFactory .openSession();
		Transaction transaction=session.beginTransaction();
		User user=new User();
		user.setId(11);
		session.delete(user);
		transaction.commit();
		session.close();
	}
}

结果显示:
在这里插入图片描述
在这里插入图片描述

改

两种方式:

package com.hsl.one.text;

import java.sql.Date;
import java.sql.Timestamp;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.hsl.one.entity.User;

/**
 * hibernate的修改
 * @author Administrator
 *
 */
public class EditDome {
	public static void main(String[] args) {
		/*
		 * 1,对hibernate.cfg.xml核心配置文件进行建模
		 * 2,建模后的对象获取sessionfactory对象,sessionfactory对象中包含了数据库的相关信息
		 * 3,通过sessionfactory对象获取session会话
		 * 4,session开启事务
		 * 5,操作数据库
		 * 6,提交事务(查询中不需要)
		 * 7,释放资源
		 */
		Configuration configure=new Configuration().configure("/hibernate.cfg.xml");
		SessionFactory sessionFactory=configure.buildSessionFactory();
		Session session=sessionFactory .openSession();
		Transaction transaction=session.beginTransaction();
		//第一种方式:
//		User user=new User("lala", "123456", "xxxx", "男",new Date(System.currentTimeMillis()) , new Timestamp(System.currentTimeMillis()), "gungun");
//		user.setId(14);
//		session.update(user);
		//第二种方式:
		User user=session.get(User.class, 12);
		user.setRealName("qaz");
		user.setSex("女");
		
		transaction.commit();
		session.close();
	}
}

结果展示:
在这里插入图片描述

在这里插入图片描述

查
package com.hsl.one.text;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * hibernate的查询
 * @author Administrator
 *
 */
public class SelectDome {
	public static void main(String[] args) {
		/*
		 * 1,对hibernate.cfg.xml核心配置文件进行建模
		 * 2,建模后的对象获取sessionfactory对象,sessionfactory对象中包含了数据库的相关信息
		 * 3,通过sessionfactory对象获取session会话
		 * 4,session开启事务
		 * 5,操作数据库
		 * 6,提交事务(查询中不需要)
		 * 7,释放资源
		 */
		Configuration configure=new Configuration().configure("/hibernate.cfg.xml");
		SessionFactory sessionFactory=configure.buildSessionFactory();
		Session session=sessionFactory .openSession();
	List list=session.createQuery("from User").list();
	for (Object object : list) {
		System.out.println(object);
	}
	session.close();
	}
}

结果展示:
在这里插入图片描述

IDEA 使用 hibernate 1. 添加 hibernate 依赖 打开项目结构 选择模块选项卡 添加 hibernate 依赖 添加配置文件,如果已经有配置文件可以直接选择该文件,没有也可以直接新建一个: 新建完后默认配置文件如下: 2. 完成配置文件 配置文件的一个例子,hibernate 还有很多参数配置,可以去官网查看: <?xml version='1.0' encoding='UTF-8'?&gt... 阅读详情

相关推荐

(hibernate_10增删改查DAO

hibernate_10增删改查DAO

关于Hibanate注解的使用与方法

关于Hibanate注解的使用与方法 详见 博主Qiao_Zhi的文章 https://www.cnblogs.com/qlqwjy/p/9545453.html

百无禁忌 442

封装了一个Hibernate增删改查的工具类

一个工具类实现了增删改查 util comm.util beanutils 方便了获取session和sessionFactory

hibernate缓存:一级缓存和二级缓存

1.什么是缓存?  缓存是介于物理数据源与应用程序之间,是对数据库中的数据复制一份临时放在内存中的容器,其作用是为了减少应用程序对物理数据源访问的次数,从而提高了应用程序的运行性能。Hibernate在进行读取数据的时候,根据缓存机制在相应的缓存中查询,如果在缓存中找到了需要的数据(我们把这称做“缓存命中"),则就直接把命中的数据作为结果加以利用,避免了大量发送SQL语句到...

aodaidi6752的博客 293

微信支付开发之平台给用户转账到零钱的功能

请求消息中应包含商家批次单号、转账名称、appid、转账总金额、转账总笔数、转账openid、收款用户姓名等信息。批次已受理成功,若发起批量转账的30分钟后,转账批次单仍处于该状态,可能原因是商户账户余额不足等。【转账场景ID】 该批次转账使用的转账场景,如不填写则使用商家的默认场景,如无默认场景可为空,可前往“商家转账到零钱-前往功能”中申请。【转账总笔数】 一个转账批次单最多发起一千笔转账。【商家批次单号】 商户系统内部的商家批次单号,要求此参数只能由数字、大小写字母组成,在商户系统内部唯一。

程序员weixin_sodomany的博客 3449

智能织梦:基于Rokid AR眼镜的家庭情感记忆增强系统设计与实践

本文介绍了基于Rokid AR眼镜的'智能织梦'系统,通过增强现实技术捕捉和重现家庭情感记忆。系统利用多模态传感器和轻量级情感识别模型,自动记录家庭互动中的情感峰值时刻,并生成沉浸式记忆片段。测试数据显示,该系统显著提升了家庭情感互动的频率和质量,特别适用于多代同堂家庭和记忆唤醒场景。

sre5engineer的博客 536

Hibernate入门第一讲——Hibernate框架的快速入门

Hibernate框架介绍什么是Hibernate我们可以从度娘上摘抄这样有关Hibernate的介绍: Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。Hibernate可以

李阿昀的博客 12万+

跟着团子学SAP PS:BOM和项目结构的联动-BOM Transfer CN33

关于项目中的物料组件挂接你需要了解的一点功能

Lucas1211的博客 2万+

Hibernate简单讲解

所谓的ORM就是利用描述对象和数据库表之间映射的元数据,自动把java应用程序中的对象持久化到关系型数据库的表中。通过操作java对象,就可以完成对数据库表的操作。可以把ORM理解为关系型数据和对象的一个纽带,开发人员只需关注纽带一段映射的对象即可。Hibernate框架使用ORM思想对数据库进行crud操作在web阶段学习的javabean,更准确的叫法应该是实体类ORM:Object Relational Mapping,对象关系映射。让实体类和数据库表对应,让实体类属性和表中字段对应。

weixin_42694511的博客 5026

什么是 MDB-RS232,为什么需要 MDB-RS232适配器 ?

在您需要设计一个售货机,首先需要选择适合您机器的主板,比如安卓主板、树莓派、工控机或者PLC等,这些主板都是没有MDB接口的,而支付设备,比如你选择的纸币器,硬币器,都是MDB接口。那您就需要这个 MDB 适配器,来把MDB接口的支付设备连接到这些串口的主板上,进行通信和控制。MDB-RS232旨在将MDB 协议转换为 RS232 协议,并执行必要的电压转换以及数据路由工作。,能够让主板轻松执行其他任务,不需要考虑协议的具体软硬件的兼容和稳定性问题。专业的设计指导和协助协议分析,丰富的开发文档。

waferstar的博客 1382

量化交易新手必看:如何用vnpy+Tushare轻松获取A股历史数据(附完整代码)

本文为量化交易新手提供了使用vnpy和Tushare构建A股历史数据获取系统的完整指南。通过详细的代码示例,手把手教你搭建环境、封装数据获取引擎,并实现日线等数据的格式转换与本地存储,为策略回测与分析奠定坚实的数据基础。

weixin_29098117的博客 377

idea从0开始使用hibernate完成增删改查

文章目录环境配置 环境配置 1.使用idea创建maven项目,添加相关依赖 <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.1.0.Final...

远行的博客 1018

单细胞测序流程(十)KEGG通路富集分析与可视化圈图实战解析

本文详细解析了单细胞测序数据分析中KEGG通路富集分析与可视化圈图的完整实战流程。从差异表达基因列表出发,通过R语言进行KEGG富集分析,并利用Perl脚本进行基因ID转换,最终使用GOplot包绘制高级可视化圈图,帮助研究者将基因列表转化为有意义的生物学故事。

i7j8k9l的博客 405

使用hibernate 完成考题类的增删改查(前序)

sql如下: DROP TABLE IF EXISTS `exam_test`; CREATE TABLE `exam_test` ( `id` int(11) NOT NULL AUTO_INCREMENT, `content` text NOT NULL, `choose_a` varchar(255) NOT NULL, `choose_b` varch...

diconke7343的博客 143

CKS-CN考试之路----02

其实我们根据题目也可以知道秘钥是叫clever-cactus。稍作等待后,确认pod的状态,如果是1/1基本就没问题了。这步不一定做.目的是确定秘钥的名字。

Q先生 654

腾讯微搭低代码开发实战电子书:医疗挂号小程序

本书通过一个完整的“医疗挂号小程序”项目,深度讲解腾讯微搭(WeDa)低代码平台在复杂业务场景下的实战应用。从登录体系搭建、用户注册,到就诊人管理、科室排班与预约下单,全程遵循“配置+逻辑+实战”的思路,带领读者从零实现具备商业级可用性的医疗挂号小程序,掌握低代码开发的核心技巧与业务落地能力。

低代码布道师的博客 951

hibernate中的增删改查

         在hibernate中的增删改查的实现。hibernate是OR框架,也就是对象关系框架,有了 hibernate我们就不用再去写SQL语言,我们只需要操纵对象去进行增删改查。这里今天写的就是在如何应用hibernate实现增删改查。第一个我们首先看看增,增在SQL里面就是insert,也就是插入,在hibernate中,我们只需要,操纵一个对象进行sava,然后再commit事

kobe_lzq的专栏 1566

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

Hibernate增删改查(通过id查询)

Hibernate增删改查(通过id查询) package com.hbsi.hibernate.utils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration

1万+

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

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

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

Hibernate——(2)增删改查

案例名称:Hibernate完成增删改查 案例描述:抽取出工具类并完成删除、修改、查询功能。 具体过程: 1、使用上面的例子(Hibernate——(1)Hibernate入门http://blog.youkuaiyun.com/dawanganban/article/details/13748235) 2、新建HibernateUtils :用于封装创建Session的方法。

程序员的那些事 662

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

使用Hibernate的基本步骤和常用jar包

1、导入jar包 Pom.xml 中导入需要使用的jar包(可以直接百度maven repository查找你需要的jar包) <!--hibernate的核心jar包--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate...

zhang150114的博客 1856

spring入门(11)-spring与hibernate整合完成增删改查的操作(封装HibernateTemplate模版类对象)

今天是spring的最后一节课,这节课老师讲了spring与hibernate整合完成增删改查的操作,这是很重要的一节课,这也是第一次真正的实现spring结合Hibernate和数据库连接上,下面是这次课的过程实现: 首先是数据库建表:采用Oracle数据库,在Scott用户里新建USERS表, 所用jar包: 实现源码如下: Users.java [jav

xyjikl 539

eclipse中使用hibernate对mysql进行增删改查

数据库操作前后的一些必须的操作进行数据库操作前: //生成会话工厂 SessionFactory sf = new Configuration().configure().buildSessionFactory(); //从会话工厂中获取一个会话 Session s = sf.openSession(); //开始事务 s.beginTransacti...

weixin_34061555的博客 142

【Hibernate总结系列】使用举例

本节讲述如何使用Hibernate实现记录的增、删、改和查功能。1 查询       在Hibernate中使用查询时,一般使用Hql查询语句。HQL(Hibernate Query Language),即Hibernate的查询语言跟SQL非常相像。不过HQL与SQL的最根本的区别,就是它是面向对象的。使用HQL时需要注意以下几点:l         大小写敏感因为HQL

技术收藏 616

hibernate的helloworld版

项目目录结构图: 一、添加mysql驱动jar包及hibernate的jar包(hibernate-release-4.2.3.Fina---->lib----->required下的所有) 二、创建数据的表 三、编写表对应的实体类即person类 四、编写类与表关联的Person-hbm.xml文件 五、编写hibernate.cfg.xml文件 六、编写HibernateTes

你究竟是想一辈子卖糖水,还是希望获得改变世界的机会? 1522

hibernate 初级1

## Hibernate框架第一天 ## ---------- **今天任务** 1. 使用Hibernate框架完成对客户的增删改查的操作 ---------- **教学导航** 1. 能够说出Hibernate的执行流程 2. 能够独立使用Hibernate框架完成增删改查的操作 ---------- **框架和CRM项目的整体介绍** 1. 什么是CR

qq_20147577的博客 772

hibernate入门

1. 什么是hibernate ORM框架/持久层框架 jdbc的一个框架 object reference mapping 通过管理对象来改变数据库中的数据 通过管理对象来操作数据库 优势:跨数据库的无缝移植 注1:Object Relational Mapping 1、加载驱动 2、建立连接 3、获取预定义处理对象 preparestatment 4、执行sql 5、处理结果集 6、关闭 如...

chen的博客 154
上一篇: struts中的文件上传
下一篇: layui的基本元素之一-----按钮
water_java
博客等级 码龄7年 9粉丝 124原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值