MyBatis学习笔记第二天、MyBatis入门、自定义MyBatis的实现

Mybatis基础入门学习笔记(一) 这里写自定义目录标题一.Mybatis快速入门1.1 框架介绍1.2 ORM介绍1.3 原始jdbc操作(查询数据)1.4 原始jdbc操作的分析1.5 Mybatis的快速入门1.6.1 环境搭建1.6.2编写测试代码1.7 知识小结二. MyBatis的相关api2.1 Resources2.2 构建器SqlSessionFactoryBuilder2.3 工厂对象SqlSessionFactory2.4 SqlSession会话对象三.MyBatis 映射配置文件3.1 映射配置文件介绍3.2 查 阅读详情

1 回顾自定义的MyBatis、流程再分析

在这里插入图片描述

2 MyBatis的CRUD(基于代理dao的方式)

2.1 回顾MyBatis的环境搭建-实现一个查询所有的功能

我们来新建一个Module命名为day02_01mybatisCRUD。我们可以把昨天的Module里的log4j的配置文件直接拷贝道我们新建的Module里。因为我们不需要是新的jar所以我们可以按照昨天的pom.xml来修改我们新建的Module的pom.xml。

<?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-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.itheima</groupId>
    <artifactId>day02_01mybatis_CRUD</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--打包方式-->
    <packaging>jar</packaging>
    <!--依赖包-->
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

然后我们创建一个实体类User.java

public class User implements Serializable {
    private Integer id;
    private String username;
    private String address;
    private String sex;
    private Date birthday;
    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 getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    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;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", address='" + address + '\'' +
                ", sex='" + sex + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}

下面来创建MyBatis的主配置文件SqlMapperConfig.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">
<!--上面是mybatis的主配置文件的约束-->
<configuration>
    <!--配置环境-->
    <environments default="mysql">
        <!--配置mysql的环境-->
        <environment id="mysql">
            <!--配置事务-->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--配置映射文件的位置-->
    <mappers>
        <mapper resource="com/itheima/dao/IUserDao.xml"></mapper>
    </mappers>
</configuration>

然后我们在创建Dao接口,IUserDao.java

/**
 * 用户的持久层接口
 */
public interface IUserDao {
    /**
     * 查询所有用户的操作
     */
    List<User> findAll();
}

然后再根据MyBatis的主配置文件中的 mapper 来创建IUserDao的M映射配置文件IUserDao.xml。这里我们在resources里创建包的时候,要想一次把这个包的路径全部创建出来,需要填入 com/itheima/dao 这里也创建包,然后在这个包中创建IUserDao.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的接口-->
<mapper namespace="com.itheima.dao.IUserDao">
    <!--配置查询所有 resultType 表示传递的参数类型-->
    <select id="findAll" resultType="com.itheima.domain.User">
        select * from user;
    </select>
</mapper>

下面来创建一个测试类 MybatisTest.java 测试我们写的代码。

/**
 * 测试MyBatis的CRUD操作
 */
public class MybatisTest {
    /**
     * 查询所有的测试
     */
    @Test
    public void testFindAll() throws Exception{
     	//1.读取配置文件,生成字节输入流
        InputStream  in = Resources.getResourceAsStream("SqlMapperConfig.xml");
        //2.获取SqlSessionFactor对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory = builder.build(in);
        //3.获取SqlSession对象
        SqlSession session = sessionFactory.openSession();
        //4.获取Dao的代理对象
        IUserDao dao = session.getMapper(IUserDao.class);
        //5.查询所有方法
        List<User> users = dao.findAll();
        for (User user : users) {
            System.out.println(user);
        }
    }
}

我们执行以下测试类中的测试方法控制台输出如下,可以看出程序正常执行啦。
在这里插入图片描述

2.2 MyBatis的CRUD和MyBatis中的参数(参数的各种类型)深入及结果(结果集的封装)的深入

我们在上面创建的Module的基础上来实心MyBatis的CRUD操作和对参数的设置和结果集的封装进行配置。首先修改IUserService.java

/**
 * 用户的持久层接口
 */
public interface IUserDao {
    /**
     * 查询所有用户的操作
     */
    List<User> findAll();

    /**
     * 保存用户
     */
    void saveUser(User user);

    /**
     * 更新用户
     */
    void updateUser(User user);

    /**
     * 根据id删除用户
     */
    void deleteUser(Integer userId);

    /**
     * 根据id查询用户
     */
    User findById(Integer userId);

    /**
     * 根据名称模糊查询用户信息
     */
    List<User> findByName(String username);
    /**
     * 查询总的用户数
     */
    int findTotal();

    /**
     * 根据QueryVo中的条件查询用户
     */
    List<User> findUserByVo(QueryVo vo);
}

创建一个查询条件类 QueryVo.java

public class QueryVo {
    private User user;
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
}

然后就是修改我们的MyBatis的映射配置文件IUserDao.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的接口-->
<mapper namespace="com.itheima.dao.IUserDao">
    <!--配置查询结果的列名和实体类的属性名的对应关系 property是实体类中的属性名,column是数据库中的列名-->
    <resultMap id="userMap" type="com.itheima.domain.User">
        <!--主键字段的对应 property 表示实体类中的属性名字,column表示数据库表的列名-->
        <id property="id" column="id"></id>
        <!--非主键字段的对应-->
        <result property="username" column="username"></result>
        <result property="address" column="address"></result>
        <result property="sex" column="sex"></result>
        <result property="birthday" column="birthday"></result>
    </resultMap>

    <!--配置查询所有,id表示方法名, resultType表示返回的结果集封装到哪里-->
    <!--当实体类中的属性名和数据库中的列名不一致时,可以在sql语句中起别名,也可以使用resultMap进行映射-->
    <!--<select id="findAll" resultType="com.itheima.domain.User">-->
    <select id="findAll" resultMap="userMap">
        <!--select id as userId,username as userName,address as userAddress,sex as userSex,birthday as userBirthday from user-->
        select * from user;
    </select>
    <!--保存用户 parameterType表示方法的参数类型-->
    <insert id="saveUser" parameterType="com.itheima.domain.User">
        <!--配置插入操作后,获取插入数据的id
        keyProperty id的属性名称对应实体类里的属性名,
        keyColumn id的列名对应表
        order 表示在insert前执行还是插入后执行
        -->
        <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
            select last_insert_id();
        </selectKey>
        insert into user(username,address,sex,birthday) values(#{username},#{address},#{sex},#{birthday});
    </insert>
    <!--更新用户-->
    <update id="updateUser" parameterType="com.itheima.domain.User">
        update user set username =#{username}, address =#{address}, sex=#{sex},birthday =#{birthday} where id=#{id};
    </update>
    <!--删除用户 当方法只有一个参数时,并且是基本类型或基本类的包装类时,{uid}就是一个占位符,写什么都行-->
    <delete id="deleteUser" parameterType="Integer">
        delete from user where id=#{uid};
    </delete>
    <!--根据id查询一个用户-->
    <select id="findById" parameterType="Integer" resultType="com.itheima.domain.User">
        select * from user where id=#{uid};
    </select>
    <!-- 根据名称模糊查询 -->
    <select id="findByName" parameterType="String" resultType="com.itheima.domain.User">
        <!--这种方式,要在调用方法的时候加%
            这
            在实际执行的时候是 select * from user where username like ?;使用了占位符
            使用的是 PrepatedStatement的参数占位符,建议使用这个
        -->
        select * from user where username like #{uname};
        <!--下面这种方式,在调用方法的时候不用加%,但是这个站位符必须写出value,因为这个在源码中写死了
            这种方法不常用,在实际执行的时候是 select * from user where username like '%小%'; 拼接的字符串
            这个是用 Statement对象的字符串拼接的SQL,不建议使用,易SQL注入
        -->
        <!--select * from user where username like '%${value}%';-->
    </select>

    <!--获取用户的总计数条数-->
    <select id="findTotal" resultType="int">
        select count(*) from user;
    </select>

    <!--根据QueryVo的条件查询用户-->
    <select id="findUserByVo" parameterType="com.itheima.domain.QueryVo" resultType="com.itheima.domain.User">
        select * from user where username like #{user.username}; <!--QueryVo对象中有一个属性为 user-->
    </select>
</mapper>

在这个配置文件中我们展示了MyBatis的CRUD操作的映射配置和参数的传递配置和结果集的封装处理。
下面在来修改一下测试类MybatisTest.java

/**
 * 测试MyBatis的CRUD操作
 */
public class MybatisTest {
    private InputStream in = null;
    private SqlSession session = null;
    private IUserDao dao = null;
    /**
     * 初始化Mybatis
     */
    @Before //用于在测试方法之前执行
    public void init() throws Exception {
        //1.读取配置文件,生成字节输入流
        in = Resources.getResourceAsStream("SqlMapperConfig.xml");
        //2.获取SqlSessionFactor对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory = builder.build(in);
        //3.获取SqlSession对象
        session = sessionFactory.openSession();
        //4.获取Dao的代理对象
        dao = session.getMapper(IUserDao.class);
    }
    /**
     * 释放资源
     *
     * @throws Exception
     */
    @After //用于在测试方法之后执行
    public void destroy() throws Exception {
        //提交事务
        session.commit();
        //和上面一句一样
        // session.commit(true);
        if (in != null)
            in.close();
        if (session != null)
            session.close();
    }
    /**
     * 查询所有的测试
     */
    @Test
    public void testFindAll() {
        //5.查询所有方法
        List<User> users = dao.findAll();
        for (User user : users) {
            System.out.println(user);
        }
    }
    /**
     * 保存用户测试
     */
    @Test
    public void testSaveUser() {
        User user = new User();
        user.setUsername("mybatis last insertUser");
        user.setAddress("天津");
        user.setSex("女");
        user.setBirthday(new Date());
        System.out.println("保存操作之前:" + user);
        //5.执行保存方法
        dao.saveUser(user);
        System.out.println("保存操作之后:" + user);
    }
    /**
     * 更新用户测试
     */
    @Test
    public void testUpdateUser() {
        User user = new User();
        user.setId(5);
        user.setUsername("mybatis update user");
        user.setAddress("上海");
        user.setSex("女");
        user.setBirthday(new Date());
        //5.执行更新用户方法
        dao.updateUser(user);
    }
    /**
     * 删除用户测试
     */
    @Test
    public void testDeleteUser() {
        //5.执行删除用户方法
        dao.deleteUser(5);
    }
    /**
     * 根据id查询用户测试
     */
    @Test
    public void testFindById() {
        //5.执行根据id查询用户有方法
        User user = dao.findById(2);
        System.out.println(user);
    }
    /**
     * 根据username模糊查询
     */
    @Test
    public void testFindByName() {
        // 执行根据username模糊查询方法
        // List<User> users = dao.findByName("%小%");
        List<User> users = dao.findByName("小");
        for (User user : users) {
            System.out.println(user);
        }
    }
    /**
     * 查询用户的总数
     */
    @Test
    public void testFindTotal() {
        //执行查询用户的总数方法
        int total = dao.findTotal();
        System.out.println("总人数:" + total);
    }
    /**
     * 测试使用QueryVo作为查询条件的模糊查询
     */
    @Test
    public void testFindByVo() {
        //执行根据username模糊查询方法
        QueryVo queryVo = new QueryVo();
        User user = new User();
        user.setUsername("%小%");
        queryVo.setUser(user);
        List<User> users = dao.findUserByVo(queryVo);
        for (User u : users) {
            System.out.println(u);
        }
    }
}

整个Module的结构如下
在这里插入图片描述

3 MyBatis中基于传统Dao的方式(编写Dao的实现类,了解就行)

5 MyBatis中的配置(主配置文件:SqlMapConfig.xml)

5.1 properties标签

5.2 typeAliases标签

5.3 mappers标签

mybatis自定义标签.zip 介绍了mybatis自定义标签,添加自定义标签的实现代码,通过实例代码展示给大家 立即下载

相关推荐

笔记本电脑更换主板后出现2203:System configuration is invalid,以及2201、2202系统错误的解决

主板更换后刷新S/N

晓夏IT笔记 3516

mapper的名字空间出错,坑我几个小时

&lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"&gt;&lt;mapper namespace="com.vv.dao.U

jintingbo的专栏 2716

Kriging代理模型理论相关推导

代理模型,Kriging,加点准则

森屹的博客 1万+

Mybatis的mapper标签 namespace方法说明

Mybatis的mapper标签 namespace方法说明有三种全路径:第一种:namespace绑定实体类的全路径:第二种:namespace绑定dao层接口的全路径:第三种:namespace绑定mapper接口的sql.xml文件。 有三种全路径: namespace绑定实体类的全路径; namespace绑定dao层接口的全路径; namespace绑定mapper接口的sql.xml文件。 第一种:namespace绑定实体类的全路径: 当namespace绑定的是实体类的全路径时,其实现数据持

m0_38088420的博客 2348

ARM和FPGA之间的通信(硬件原理图篇)

设计该开发板的初衷是为了学习,但也希望今后能扩展其功能,看到大家都在diy示波器,自己也非常冲动的想DIY一把,于是呼选了arm+fpga的方案,fpga主要用来实现数据的高速采样,而ARM则提供数据的显示,以及一些人机交互的功能。那么该方案中最重要的地方就是ARM和FPGA之间的通信如何实现了。在网上查了很多的资料,有说将FPGA作为ARM的一个外设,可以通过DMA的方式来直接访问;也有说把FP

屌yy的博客 5万+

解决在封装自定义IP时加入ila,或者其他ip核时出错的情况

在查阅很多资料后,明白了这个应该是软件bug,但是最终还是解决了问题 我们只需要删除

weixin_42553916的博客 3604

Mybatis学习

Mybatis 一、简介 1.1、什么是Mybatis Mybatis是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。Mybatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。Mybatis可以使用简单的XML或注解来配置和映射原生信息,将接口和Java的POJOs(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。 <!-- https://mvnrepository.com/artifact/org.mybatis/mybati

Reckless_hrl的博客 2314

GMSL转eDP芯片MAX9686X(ADI)

MAX96860/MAX96862/MAX96864解串器可以把单路或双路GMSL转换成eDP V1.4a,支持820MHzPCLK的无压缩的24bpp(每个像素的位数)视频,或660MHz的30bpp视频。芯片的GMSL支持NRZ编码的6Gbps/187Mbps的GMSL2,PAM4编码的12Gbps/187Mbps的GMSL3。同时支持单线(COAX模式)双向全双工传输控制数据和video数据。支持DSC压缩的芯片,最大支持像素时钟1080MHz@24bpp或者864MHz@30bpp,传输方式包括同轴

qflook的博客 2835

MyBatis--03自定义MyBatis的实现

以下操作在下面案例的基础上修改。 在原案例基础上修改 修改的地方有: (1)删除mybatis依赖 <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> (2)新增dom4j和jaxen依赖 <!--

Ur_Eyes_的博客 456

Transformer实战(32)——Transformer模型压缩

在本节中,我们学习了如何在硬件资源受限的情况下减轻运行大模型的负担。我们介绍了如何通过蒸馏、剪枝和量化从训练好的模型中提取高效模型。预训练轻量级的通用语言模型(如 DistilBERT) 可以在各种任务上进行微调,并表现出与非蒸馏模型相当的性能。随着数据量的不断增加,我们希望模型能够更快地运行,在这方面,高效 Transformer 起着至关重要的作用。

盼小辉丶的博客 2539

PowerPMAC配置EtherCAT设备

本文详细介绍了在PowerPMAC IDE环境下配置EtherCAT伺服电机的完整流程。主要内容包括:准备工作(连接硬件和获取ESI文件)、通过ESI管理器加载配置文件、网络扫描识别从站设备、变量映射(定义输入输出位置参数)、激活EtherCAT通讯(验证状态字和实际位置)以及相关参数说明。文章还概述了主站配置的8个方面和从站配置的7个选项,重点说明了PDO映射和变量分配机制,为伺服电机的EtherCAT通信配置提供了系统指导。

mahuliang321的博客 964

MyBatis学习笔记第一天、MyBatis入门、自定义MyBatis的实现

MyBatis学习第一天1. MyBatis的概述2. MyBatis的环境搭建环境搭建的注意事项:3. MyBatis入门MyBatis快速入门mybatis基于注解的入门案例4. 自定义MyBatis的实现对测试类方法的分析功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML 图

Code_Boy_Code的博客 452

Vue3 - 强力解决前端下载二进制流pdf文件、下载成功后打开空白问题解决,或者获取PDF文件流,将blob对象转换成下载链接打开后一片空白(无论是否使用pdf插件下载,还是原生方法下载都完美解决)

vue3前端下载二进制流pdf文件,下载成功,打开空白问题解决,js下载PDF文件流,打开空白问题,VUE3 h5中的文件流下载和指定的url下载总结(解决下载后的pdf打开空白情况)pdfjs打开文件流空白,解决pdf文件流,预览全是空白页,pdf文件流,下载正常,但是预览全是空白页,前端JS获取PDF文件流,将blob对象转换成下载链接打开后一篇空白的问题,前端文件流下载后文件空白,前端下载文件流PDF文件显示空白 或 无法打开,在线预览PDF文件打不开白屏怎么办,前端axios请求二进制数据流转换生成

🏆 前端领域优质创作者 4615

Mybatis学习笔记 - 01

Mybatis 的学习笔记第一篇,包括以下内容 Mybatis 的概述 Mybatis 的环境搭建 Mybatis 入门案例 自定义 Mybatis 框架(可以了解底层执行细节)

鱼开饭的博客 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")

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

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

MyBatis 快速入门学习笔记

ORM(Object Relational Mapping,对象关系映射)是一种将数据库中的表结构映射到程序中的对象的技术。ORM 框架通过元数据(通常以 XML 或注解形式)描述对象与数据库表之间的映射关系。常见的 ORM 框架包括 MyBatis、Hibernate 和 JOOQ。MyBatis 是一款优秀的持久层框架,支持自定义 SQL、存储过程以及高级映射。它简化了 JDBC 的使用,免去了繁琐的参数设置和结果集处理。

2301_78498098的博客 1681

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

MyBatis学习笔记(一)MyBatis介绍、入门案例以及自定义实现MyBatis

一、MyBatis介绍、入门案例以及自定义实现MyBatis 1、什么是框架? 它是我们软件开发中的一套解决方案,不同的框架解决的是不同的问题。 使用框架的好处: 框架封装了很多的细节,使开发者可以使用极简的方式实现功能。大大提高开发效率。 2、三层架构 表现层:是用于展示数据的 业务层:是处理业务需求(Spring不属于任何一个层) 持久层:是和数据库交互的 3、持久层技术解决方案 JDB...

sc的博客 251

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

MyBatis学习笔记——04MyBatis入门程序

MyBatis学习笔记——04MyBatis入门程序 要想学好mybatis必须掌握好其入门程序掌握好它的增,删,改,查 代码里注释解释巨细无比不懂请留言 1.首先我们来了解一下mybatis的入门程序的架构 1.两个jar包 mybaits核心包 mysql驱动包 2.config目录 **sqlmap:用来保存mapper文件 如User.xml(userdb映射文件) <?xm...

qq_40163148的博客 326

MyBatis之TypeHandler的自定义实现

在 MyBatis 中,类型处理器(TypeHandler)扮演着 JavaType 与 JdbcType 之间转换的桥梁角色。它们用于在执行 SQL 语句时,将 Java 对象的值设置到 PreparedStatement 中,或者从 ResultSet 或 CallableStatement 中取出值。MyBatis的TypeHandler机制具有很高的扩展性。我们可以通过实现TypeHandler接口或继承BaseTypeHandler类来创建自定义的TypeHandler实现。

daydayup 2459

MyBatis-学习笔记02【02.Mybatis入门案例】

MyBatis-学习笔记02【02.Mybatis入门案例】

upward 726

【MyBatis】自定义MyBatis的实现

文章目录一、整体分析二、具体实现1.准备工作Step 1 自定义Resource类§ SqlMapConfig.xml主配置文件§ Resource类Step 2 自定义SqlSessionFactoryBuilder类§ SqlSessionFactoryBuilder工厂类§ XMLConfigBuilder配置解析类§ Configuration数据库连接配置类§ Mapper映射配置类Step 3 自定义SqlSessionFactory类§ SqlSessionFactory类Step 4 自定.

懂得一千零一种,赋予你失败的方法! 672

Mybatis自定义插件实现分表

自定义mybatis分表组件功能: 1、带分片参数的增删改 2、查询和支持pageHelper分页查询(带不带分片参数都支持) 3、可以结合tkMapper和pageHelper无缝使用

abc2675811870的博客 1752

Mybatis学习笔记

mybatis学习笔记

triticale的博客 775

mybatis入门案例自定义实现

mybatis入门案例自定义实现 一、需要实现的类和接口 public static void main(String[] args) throws Exception{ //1.读取配置文件 InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml"); //2.创建SqlSessionFactory...

weixin_42364196的博客 201

Mybatis学习笔记——Mybatis入门

文章目录Mybatis入门1.为什么要使用mybatis?2.ORM3.mybatis简介4.mybatis框架5.mybatis入门程序5.1搭建环境5.2 配置log4j5.3 配置SqlMapConfig.xml5.4 创建bean对象5.5 配置映射文件5.6 加载映射文件5.7 编写代码6.完成CRUD操作6.1 映射文件6.2 编码7.总结原生Dao的开发的缺陷8.Mapper代理方法8.1 mapper代理开发规范8.2mapper代理开发入门8.2.1 映射文件8.2.2 mapper接..

Yiky的博客 1001

JavaWeb——MyBatis框架之执行过程原理与解析(通过自定义MyBatis查询所有操作的实现来观察整个过程)

1 MyBatis执行过程分析 通过上一博文,我们了解了MyBatis的入门,知道了怎么搭建环境及最基本的使用,那么,本次我们结合上一博文的案例实战,进行更深入的分析MyBatis的执行过程,MyBatis使用代理dao方式进行增删改查时做了哪些事呢?其实就是两件: 1)创建代理对象; 2)在代理对象中调用selectList。 1.1MyBatis执行查询所有的过程分析 1.2 MyBatis创建代理对象的分析 2 自定义MyBatis 在入门实战案例基础上修改,删除掉pom....

数字世界 万物互联 2215

Mybatis(快速入门及简单自定义Mybatis框架)

1. Mybatis框架快速入门 在 pom.xml 文件中添加 Mybatis3.4.5 的坐标,如下: <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </

限定私语的博客 2148
上一篇: 高性能MySql学习笔记第一章
下一篇: CountDownLatch详解
Code_Boy_Code
博客等级 码龄9年 650粉丝 28原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值