MyBatis的入门

MyBatis入门到精通——入门篇 目录一、什么是 MyBatis?二、入门案例(1)创建maven项目(2)引入依赖包(3)创建数据库执行sql脚本三、入门程序源码(1)User.java(2)UserMapper.java(3)MybatisUtils.java(4)UserMapperTest.java(6)UserMapper.xml(7)mybatis-config.xml(8)pom.xml 四、程序单元测试结果五、程序完整源码获取在此之前,需要提前配置好java环境变量和maven环境变量。 (3)创建数据库执行sql 阅读详情

MyBatis是什么

  • 开源的持久层框架。
  • jdbc 易掌握,性能好,代码繁琐,易出错
  • hibernate 难掌握,性能不好,代码非常简洁,虽然不用写sql,但经常需要优化sql
  • mybatis 比较容易掌握,性能一般,代码简洁,需要写sql

开发步骤

  1. 导包 mybatis,mysql,junit
  2. 添加配置文件 (SqlMapConfig.xml)
  3. 实体类,属性名要与表的字段名一样(大小写可以忽略)
  4. 添加映射文件(告诉mybatis,如何进行对象关系映射,里面主要是一些sql语句)
  5. 修改配置文件,添加映射文件的位置
  6. 调用mybatis提供的api访问数据库(主要是调用SqlSession类提供的方法)

jar包依赖

<dependencies>
		<!-- mybatis的jar包 -->
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.5.4</version>
		</dependency>
		<!-- mysql的jar包 -->
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.19</version>
		</dependency>
		<!-- junit单元测试 -->
		<!-- https://mvnrepository.com/artifact/junit/junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<properties resource="db.properties" />
	<typeAliases>
		<package name="entity"/>
	</typeAliases>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driver}" />
				<property name="url" value="${jdbc.url}" />
				<property name="username" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="entity/EmployeeMapper.xml" />
	</mappers>
</configuration>

db.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ems?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

数据库

//创建数据库
create database ems;
//创建表
CREATE TABLE t_emp (
  id int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  ename varchar(255) DEFAULT NULL COMMENT '雇员名称',
  salary decimal(10,2) DEFAULT NULL COMMENT '薪水',
  age int(11) DEFAULT NULL COMMENT '年龄',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8

实体类

package entity;

public class Employee {
	private int id;
	private String ename;
	private double salary;
	private int age;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getEname() {
		return ename;
	}
	public void setEname(String ename) {
		this.ename = ename;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String toString() {
		return "Employee [id=" + id + ", ename=" + ename + ", salary=" + salary + ", age=" + age + "]";
	}
	
}

映射文件

EmployeeMapper.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="test">
	<insert id="save" parameterType="Employee" useGeneratedKeys="true" keyProperty="id">
		insert into t_emp values(null,#{ename},#{salary},#{age})
	</insert>
	<delete id="delete" parameterType="int">
		delete from t_emp where id=#{id}
	</delete>
	<update id="update" parameterType="Employee">
		update t_emp set ename=#{ename},salary=#{salary},age=#{age} where id=#{id}
	</update>
	<select id="findById" parameterType="int" resultType="Employee">
		select * from t_emp where id=#{id}
	</select>
	<select id="findAll" resultType="Employee">
		select * from t_emp
	</select>
</mapper>

MyBatis配置文件SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<properties resource="db.properties" />
	<typeAliases>
		<package name="entity"/>
	</typeAliases>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driver}" />
				<property name="url" value="${jdbc.url}" />
				<property name="username" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="entity/EmployeeMapper.xml" />
	</mappers>
</configuration>

测试程序

package test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import entity.Employee;

public class TestCase {
	SqlSessionFactory sf;

	@Before
	public void before() throws IOException {
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		sf = new SqlSessionFactoryBuilder().build(inputStream);
	}

	@Test
	public void save() {
		SqlSession ss = sf.openSession();
		Employee e = new Employee();
		e.setEname("小红");
		e.setAge(16);
		e.setSalary(2000);
		ss.insert("test.save", e);
		System.out.println(e.getId());
		ss.commit();
		ss.close();
	}

	@Test
	public void delete() {
		SqlSession ss = sf.openSession();
		ss.delete("test.delete", 5);
		ss.commit();
		ss.close();
	}

	@Test
	public void update() {
		SqlSession ss = sf.openSession();
		Employee e = new Employee();
		e.setId(6);
		e.setAge(23);
		e.setEname("小红");
		e.setSalary(2000);
		ss.update("test.update", e);
		ss.commit();
		ss.close();
	}

	@Test
	public void findById() {
		SqlSession ss = sf.openSession();
		Employee e = ss.selectOne("test.findById", 6);
		System.out.println(e);
		ss.close();
	}

	@Test
	public void findAll() {
		SqlSession ss = sf.openSession();
		List<Employee> employees = ss.selectList("test.findAll");
		for (Employee employee : employees) {
			System.out.println(employee);
		}
		ss.close();
	}
}

工作原理

在这里插入图片描述

返回Map类型的结果

mybatis会将查询到的记录先存放到map对象里面(以字段名作为
key,以字段值作为value,一条记录对应一个map),再将map中存放的
数据添加到实体对象(默认以key作为属性名来赋值)。
注:
返回Map类型的结果,可以不用写实体类,但是取字段值时,
需要调用get方法,需要考虑字段名的差异(比如oracle数据库
会将字段名大写)。
还是返回实体对象取值方便。

映射文件EmployeeMapper.xml

添加如下代码

<select id="findById2" parameterType="int" resultType="map">
		select * from t_emp where id=#{id}
	</select>

测试程序

@Test
	public void findById2() {
		SqlSession ss = sf.openSession();
		Map map = ss.selectOne("test.findById2", 6);
		System.out.println(map);
		ss.close();
	}

测试结果
在这里插入图片描述

解决实体类的属性名与表的字段名不一致的情况

方式一 使用别名
SELECT name as ename…
方式二 使用resultMap元素

实体类修改

package entity;

public class Emp2 {
	private int empNo;
	private String name;
	private double salary;
	private int age;
	public int getEmpNo() {
		return empNo;
	}
	public void setEmpNo(int empNo) {
		this.empNo = empNo;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String toString() {
		return "Emp2 [empNo=" + empNo + ", name=" + name + ", salary=" + salary + ", age=" + age + "]";
	}
}

映射文件EmployeeMapper.xml修改

<resultMap type="Emp2" id="Emp2ResultMap">
		<id column="id" property="empNo"/>
		<result column="ename" property="name"/>
		<result column="salary" property="salary"/>
		<result column="age" property="age"/>
	</resultMap>
	<select id="findAll2" resultMap="Emp2ResultMap">
		select * from t_emp
	</select>

测试程序

SqlSessionFactory sf;

	@Before
	public void before() throws IOException {
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		sf = new SqlSessionFactoryBuilder().build(inputStream);
	}
@Test
	public void findAll2() {
		SqlSession ss = sf.openSession();
		List<Emp2> employees = ss.selectList("test.findAll2");
		for (Emp2 employee : employees) {
			System.out.println(employee);
		}
		ss.close();
	}

测试结果

在这里插入图片描述

Mapper映射器

Mapper映射器是什么

是一个符合映射文件要求的接口。
注:mybatis会生成一个符合该接口的实现类。

使用Mapper映射器

  1. 定义接口

方法名必须与sqlId一样
参数类型必须与parameterType一样
返回类型必须与resultType一样

2、映射文件中的namespace必须等于接口名(全限定名)
3、调用SqlSession提供的getMapper方法。

修改映射文件Emp2.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="dao.EmployeeDAO">
	<insert id="save" parameterType="Employee" useGeneratedKeys="true" keyProperty="id">
		insert into t_emp values(null,#{ename},#{salary},#{age})
	</insert>
	<delete id="delete" parameterType="int">
		delete from t_emp where id=#{id}
	</delete>
	<update id="update" parameterType="Employee">
		update t_emp set ename=#{ename},salary=#{salary},age=#{age} where id=#{id}
	</update>
	<select id="findById" parameterType="int" resultType="Employee">
		select * from t_emp where id=#{id}
	</select>
	<select id="findAll" resultType="Employee">
		select * from t_emp
	</select>
</mapper>

接口EmployeeDAO

package dao;

import java.util.List;

import entity.Employee;

public interface EmployeeDAO {
	public void save(Employee e);
	public void delete(int id);
	public void update(Employee e);
	public Employee findById(int id);
	public List<Employee>findAll();
}

mybatis配置文件中添加Emp2.xml的映射

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<properties resource="db.properties" />
	<typeAliases>
		<package name="entity"/>
	</typeAliases>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driver}" />
				<property name="url" value="${jdbc.url}" />
				<property name="username" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="entity/EmployeeMapper.xml" />
		<mapper resource="entity/Emp2.xml" />
	</mappers>
</configuration>

测试程序

package test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import dao.EmployeeDAO;
import entity.Employee;

public class TestCase2 {
	SqlSessionFactory sf;

	@Before
	public void before() throws IOException {
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		sf = new SqlSessionFactoryBuilder().build(inputStream);
	}

	@Test
	public void save() {
		SqlSession ss = sf.openSession();
		EmployeeDAO employeeDAO = ss.getMapper(EmployeeDAO.class);
		Employee e = new Employee();
		e.setEname("腊月红");
		e.setAge(24);
		e.setSalary(40000);
		employeeDAO.save(e);
		System.out.println(e.getId());
		ss.commit();
		ss.close();
	}

	@Test
	public void delete() {
		SqlSession ss = sf.openSession();
		EmployeeDAO employeeDAO = ss.getMapper(EmployeeDAO.class);
		employeeDAO.delete(7);
		ss.commit();
		ss.close();
	}

	@Test
	public void update() {
		SqlSession ss = sf.openSession();
		EmployeeDAO employeeDAO = ss.getMapper(EmployeeDAO.class);
		Employee e = new Employee();
		e.setId(8);
		e.setEname("呼呼");
		e.setAge(17);
		e.setSalary(4000);
		employeeDAO.update(e);
		ss.commit();
		ss.close();
	}

	@Test
	public void findById() {
		SqlSession ss = sf.openSession();
		EmployeeDAO employeeDAO = ss.getMapper(EmployeeDAO.class);
		Employee e = employeeDAO.findById(8);
		System.out.println(e);
		ss.close();
	}

	@Test
	public void findAll() {
		SqlSession ss = sf.openSession();
		EmployeeDAO employeeDAO = ss.getMapper(EmployeeDAO.class);
		List<Employee> employees = employeeDAO.findAll();
		for (Employee employee : employees) {
			System.out.println(employee);
		}
		ss.close();
	}
}

工程制图习题集张大庆课后习题答案解析 所以,我想向大家求助,希望能得到一些学习资料、学习方法和学习经验,帮助我更好地理解和掌握这门课程。在寻找学习资料的过程中,我发现了一款叫做资小料的APP,它里面有很多关于工程制图的学习资料,包括视频教程、习题解答和考试真题等。通过使用资小料,我逐渐掌握了工程制图的基本理论和方法,解决了很多学习中遇到的问题。在这里,我想推荐给和我一样在学习《工程制图习题集》这门课的同学们,希望大家也能从这款APP中受益,共同进步。上传者: 『Consentesdei』蒼迷穀。出版社: 清华大学出版社。 阅读详情

相关推荐

Llama模型结构拆解:为什么MLP模块要这样设计?从参数配置到计算流程全解析

本文深入解析了Llama模型MLP模块的设计精髓。通过拆解其三线性层结构、门控机制与SwiGLU激活函数,揭示了并行计算如何提升效率,并详细阐述了intermediate_size参数配置背后的经验权衡与计算考量,帮助读者透彻理解这一核心组件的设计逻辑与工程实现。

mac99的博客 529

【MyBatis】入门程序

详解编写mybatis入门程序的主要步骤,以及junit、logback和工具类 SqlSessionUtil 的封装

August_._的博客 1183

ROS学习笔记之——无人机PID调参过程记录

For cooperaive inquiries, please visit the website:guanweipeng.com

gwpscut的博客 6828

Mybatis入门

在前面我们学习MySQL数据库时,都是利用图形化客户端工具(如:idea、datagrip),来操作数据库的。在客户端工具中,编写增删改查的SQL语句,发给MySQL数据库管理系统,由数据库管理系统执行SQL语句并返回执行结果。增删改操作:返回受影响行数查询操作:返回结果集(查询的结果)我们做为后端程序开发人员,通常会使用Java程序来完成对数据库的操作。Java程序操作数据库,现在主流的方式是:Mybatis。什么是MyBatis?MyBatis是一款优秀的持久层框架,用于简化JDBC的开发。

qq_63763836的博客 1095

手把手教你用Cesium和RayMarching实现逼真体积云(附完整Shader代码)

本文详细介绍了如何利用Cesium和RayMarching技术实现逼真的体积云效果,包括环境准备、核心逻辑、云层建模和光照增强等关键步骤,并提供了完整的Shader代码。通过噪声函数选型、动态风场模拟和多重散射近似等技术,开发者可以在数字地球可视化项目中创建沉浸式天气效果,显著提升场景的真实感。

weixin_29230649的博客 415

手把手教你用键盘在Ubuntu上给Lerobot机械臂采集HIL-SERL训练数据(附完整配置文件)

本文详细介绍了在Ubuntu系统中使用键盘控制Lerobot机械臂进行HIL-SERL训练数据采集的完整流程。从环境准备、机械臂校准到键盘遥操系统配置和数据采集优化,提供了实战指南和常见问题解决方案,帮助读者高效获取高质量训练数据,推动具身智能和强化学习应用的发展。

weixin_30733003的博客 479

MyBatis快速入门第二讲——MyBatis的快速入门

MyBatis框架的架构MyBatis框架的架构如下图: 下面作简要概述: SqlMapConfig.xml,此文件作为mybatis的全局配置文件,配置了mybatis的运行环境等信息。mapper.xml文件即sql映射文件,文件中配置了操作数据库的sql语句,此文件需要在SqlMapConfig.xml中加载。 通过mybatis环境等配置信息构造SqlSessionFactory(即会

李阿昀的博客 1万+

32、AI责任认定:法律与社会视角的探讨

本文探讨了人工智能(AI)在法律与社会视角下的责任认定问题。从疏忽与责任标准、严格责任制度的适用性,到AI是否能够承担法律责任等角度展开分析,指出随着AI技术的发展,传统的责任概念需要重新审视。文章进一步将AI与法人进行类比,提出AI作为物理-社会系统的责任认定框架,并强调需要建立适应AI特点的法律体系以实现公平与安全的平衡。

star5的专栏 200

MyBatis实战:从入门到精通,一站式学习MyBatis的最佳选择

MyBatis实战:从入门到精通,一站式学习MyBatis的最佳选择 项目介绍 MyBatis实战是一个专注于MyBatis技术学习的开源项目,旨在通过丰富的实战示例代码,帮助开发者从零开始掌握MyBatis的核心概念与高级用法。项目中的示例代码主要来源于刘增辉老师所著的《MyBatis从入门到精通》一书,经过精心整理与实践,确保每一个示例都能帮助开发者深入理解MyBatis的各个方面。 项目技术...

gitblog_00834的博客 1112

C#使用OpenCvSharp+微信模型识别多个二维码

本文介绍了一个基于OpenCvSharp和微信开源二维码检测器的多二维码识别项目。该项目通过C# WinForm实现,主要功能包括:加载图片、识别图片中的多个二维码并显示识别结果。核心代码使用了OpenCvSharp.WeChatQRCode类,通过预训练的caffe模型(detect.prototxt/detect.caffemodel和sr.prototxt/sr.caffemodel)进行二维码检测和解码。识别结果包括每个二维码的编号、内容及位置信息。项目适用于批量二维码识别场景,部署简单,识别效果良

遇见--专栏 123

YOLOv11改进 | Neck篇 | 轻量化跨尺度跨通道融合颈部CCFM助力YOLOv11有效涨点

到此本文的正式分享内容就结束了,在这里给大家推荐我的YOLOv11改进有效涨点专栏,本专栏目前为新开的平均质量分98分,后期我会根据各种最新的前沿顶会进行论文复现,也会对一些老的改进机制进行补充,目前本专栏免费阅读(暂时,大家尽早关注不迷路~)如果大家觉得本文帮助到你了,订阅本专栏,关注后续更多的更新~YOLOv11有效涨点专栏——本专栏持续复习各种顶会内容——科研必备​ycb。

Snu77的博客 8082

【Mybatis】Mybatis入門

1-1什么是MyBatis a.MyBatis是对JDBC的封装 b.将SQL语句放在映射文件中(XML) c.自动将输入参数映射到SQL语句的动态参数中 d.自动将SQL语句执行的结果映射成Java对象 1-2MyBatis的应用 (0)准备工作,创建学生表,添加数据 CREATE TABLE tbl_student(id VARCHAR(32),NAME VARCHAR(32),age INT); INSERT INTO tbl_student VALUE("..

keeper42的博客 188

智能水下机器人设计: 基于MATLAB的水下机器人动力学建模和控制系统设计,包括水下环境感知、路径规划和任务执行等

智能水下机器人是指能够在水下自主完成各种任务的机器人,例如探测、勘察、救援等。它具有广阔的应用前景,可用于海洋环境监测、水下考古、海上作业等领域。基于MATLAB的水下机器人设计可以为科研人员和工程师提供强大的建模和仿真工具,帮助他们设计更智能、更高效的水下机器人。智能水下机器人是未来海洋科技发展的重要方向,它将为海洋科学研究、水下考古和海上作业等领域带来新的机遇。MATLAB是一种功能强大的数学和科学计算软件,它可以为智能水下机器人设计提供强大的工具和支持。

走向CTO的路上... 962

Mybatis入门及使用

MyBatis是一款优秀的持久层框架,用于简化JDBC的开发。MyBatis本是 Apache的一个开源项目iBatis,2010年这个项目由apache迁移到了google code,并且改名为MyBatis。2013年11月迁移到Github。在上面我们提到了两个词:一个是持久层,另一个是框架。持久层:指的是就是数据访问层(dao),是用来操作数据库的。框架:是一个半成品软件,是一套可重用的、通用的、软件基础代码模型。在框架的基础上进行软件开发更加高效、规范、通用、可拓展。

2202_75483664的博客 1971

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

mybatis入门

Mybatis入门 亿图作品思维图(本人作)

神韵 492

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

MyBatis详解(一):入门程序

一、对原生态jdbc程序中问题总结1.1、原始jdbc程序步骤:(1) 注册驱动JDBC类库向DriverManager注册数据库驱动·(2)建立连接(url、username、password)使用DriverManager提供的getConnection()方法连接到数据库(3)创建SQL语句,获取语句执行对象编写SQL语句,并建立SQL语句执行对象(4)执行语句执行SQL语句,并将结果集合返回到ResultSet中(5)处理结果(6)释放资源(注意关闭的顺序)

2501_90472645的博客 1848

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

mybatis的入门使用

mybatis generator的使用 准备工作: 可编辑xml文件的编辑器(懒人直接用myeclipse打开就行) mybatis generator core 包(mybatis-generator-core-1.3.2.jar) jdbc驱动包(mysql-connector-java-5.1.40-bin.jar) 一个空的src文件夹 结构如图(根目录D:/mybatis

qq499889810的博客 450

Mybatis 配置Mybatis 二、MyBatis的入门程序

6.编写主配置文件,在resources目录下创建SqlMapConfig.xml的配置文件(其实名称可以任意),导入对应的约束,编写主配置文件。编写UserMapper.xml的配置文件,导入约束文件。引入log4j的jar包,1.2.12版本(需要引入log4j.properties的配置文件)4.编写UserMapper的接口和方法(就是咱们以前的UserDao接口)3.编写User的实现类,属性尽量使用包装类型,具体的代码如下。引入MyBatis的3.4.5的版本的坐标。

best_virtuoso的博客 1029

MyBatis框架的入门

MyBatis是一个优秀的基于Java的持久层框架,内部对JDBC做了封装,使开发者只需要关注SQL语句,而不用关注JDBC的代码,使开发变得更加的简单。MyBatis通过XML或者注解的方式将要执行的各种Statement对象配置起来,通过Java对象和statement中SQL的动态参数进行映射,并最终执行SQL语句。执行SQL后,最终将结果已Java对象返回。采用了ORM的思想。

qq_63964907的博客 901

MyBatis-什么是MyBatis?以及MyBatis的快速入门。

MyBatis-什么是MyBatis?以及MyBatis的快速入门。

m0_63949203的博客 1072

MyBatis 入门

MyBatis基础

2301_80313139的博客 1395

跟老杜从零学MyBatis框架【二】MyBatis入门程序

注意2:CarMapper.xml文件的名字不是固定的。可以使用其它名字。注意3:CarMapper.xml文件的位置也是随意的。这里选择放在resources根下,相当于放到了类的根路径下。注意4:将CarMapper.xml文件路径配置到mybatis-config.xml:

2301_76637874的博客 189

【MyBatis】MyBatis 快速入门

MyBatis 是一款优秀的持久层框架,用于简化 JDBC 开发。最初,MyBatis 是 Apache 的开源项目 iBatis,2010 年该项目迁移到 Google Code,并改名为 MyBatis。

zzy_NIC的博客 669
上一篇: 拦截器、异常处理器、springjdbc
下一篇: Spring集成MyBatis
迷失的小鹿
博客等级 码龄8年 1万+粉丝 199原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值