学习笔记057——MyBatis介绍

MyBatis详解 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。 阅读详情


企业级框架 数据库管理有:Hibernate、MyBatis、Spring Data JPA、MyBatis Plus

MyBatis

MyBatis 是目前主流的 ORM 框架,Apache

ORM:Object Relationship Mapping 对象关系映射

把面向对象的编程语言和关系性数据库进行映射

把 Java 和 MySQL 进行映射

在这里插入图片描述

在这里插入图片描述

MyBatis 以前叫 iBatis

1、MyBatis 的优势

  • 极大简化 JDBC 代码的开发
  • 简单易上手、具有很强的灵活性
  • SQL 写到 XML 中,实现和 Java 代码的解耦合
  • 支持动态 SQL,可以根据具体业务灵活实现需求

2、MyBatis 的缺点

  • 相比于 Hibernate,开发者需要完成更多的工作,定义 SQL,完成结果集和实体类的匹配。
  • 要求开发人员具备一定的 SQL 编写能力。
  • 数据库移植性较差,因为 SQL 依赖于底层数据库的,如果要进行数据库迁移,部分 SQL 需要重新编写。

3、MyBatis 的使用

Maven:管理 jar 的工具

Maven 提供了一个远程仓库,Java 生态中所有框架的 jar 包依赖都会上传到远程仓库,

开发者需要哪个 jar 只需要通过简单的配置从远程仓库下载 jar 到本地即可使用。

导入 jar 的顺序:

1、pom.xml 配置你需要的 jar

2、会在本地仓库进行查找,如果本地仓库存在,则直接导入

3、如果本地仓库没有这个 jar,则需要联网去远程仓库下载

首先需要在本地配置 Maven 环境

1、下载 Maven 文件

2、配置环境变量

在这里插入图片描述

在这里插入图片描述

Maven 换源 更换远程仓库数据源

更换为国内的阿里云镜像仓库,下载速度会很快

4、使用 Maven 搭建 MyBatis 项目

在这里插入图片描述

在这里插入图片描述

pom:project object model 工程对象模型

jar 包管理全部通过修改 pom.xml 来实现

1、pom.xml 添加依赖

<dependencies>
    <!-- MyBatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>

    <!-- MySQL -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.25</version>
    </dependency>
</dependencies>

2、创建实体类

package com.htl.entity;

import lombok.Data;

@Data
public class User {
    private Integer id;
    private String name;
    private Integer money;
}

3、配置数据源,config.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>

    <!-- 数据源 -->
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test2"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

</configuration>

4、调用 API 完成操作

  • 使用原生接口

第一步、创建 Mapper 文件 UserMapper.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.htl.mapper.UserMapper">

    <select id="get" parameterType="int" resultType="com.htl.entity.User">
        select * from user where id = #{id}
    </select>

</mapper>

第二步、config.xml 注册 UserMapper.xml

<!-- 注册UserMapper.xml -->
<mappers>
    <mapper resource="com/htl/mapper/UserMapper.xml"></mapper>
</mappers>

第三步、调用原生接口执行 SQL 获取结果

package com.htl.test;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class Test {
    public static void main(String[] args) {
        //加载MyBatis配置文件
        InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
        //构建SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(inputStream);
        //获取SqlSession
        SqlSession sqlSession = factory.openSession();
        String statement = "com.htl.mapper.UserMapper.get";
        Object o = sqlSession.selectOne(statement, 1);
        System.out.println(o);
    }
}

注意:

1、Maven 默认 JDK 是 1.5,所以需要手动进行升级

<plugins>
    <!-- 设置jdk版本 -->
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
            <encoding>utf-8</encoding>
        </configuration>
    </plugin>
</plugins>

2、默认无法读取 src 路径下的 XML 文件,需要手动进行修改

<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
    </resource>
</resources>
  • Mapper 代理实现自定义接口

5、使用 MyBatis 的注意事项

1、Mapper.xml(SQL语句所在的文件) 必须要在 config.xml(全局环境配置)中进行注册,才可以使用,否则会抛出异常。

在这里插入图片描述

2、statement 值必须是 Mapper 接口的命名空间+方法id

在这里插入图片描述

3、需要修改 pom.xml ,让 src 路径下的 XML 可以被读取

<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
    </resource>
</resources>

在这里插入图片描述

Maven 工程中默认只能读取 resources 路径下的 XML,src 路径下的 XML 无法读取,所以会报错,所以需要手动进行设置。

6、自定义接口

推荐使用,解决原生接口所带来的问题

Free MyBatis 很实用的 MyBatis 插件

1、自定义接口

package com.htl.mapper;

import com.htl.entity.User;

import java.util.List;

public interface UserMapper {
    public User findById(Integer id);
    public List<User> findAll();
    public int save(User user);
    public int deleteById(Integer id);
    public int update(User user);
}

2、接口对应的 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.htl.mapper.UserMapper">

    <insert id="save" parameterType="com.htl.entity.User">
        insert into user(name,money) values(#{name},#{money})
    </insert>

    <update id="update" parameterType="com.htl.entity.User">
        update user set name = #{name},money = #{money} where id = #{id}
    </update>

    <delete id="deleteById" parameterType="java.lang.Integer">
        delete from user where id = #{id}
    </delete>

    <select id="findById" parameterType="java.lang.Integer" resultType="com.htl.entity.User">
        select * from user where id = #{id}
    </select>

    <select id="findAll" resultType="com.htl.entity.User">
        select * from user
    </select>

</mapper>

XML 的命名空间为接口的全类名

每一个 statement 的 id 对应接口的方法名,参数和返回值类型也需要匹配

3、config.xml 中注册 Mapper.xml

<mappers>
    <mapper resource="com/htl/mapper/UserMapper.xml"></mapper>
</mappers>

4、调用 API

System.out.println(mapper.findById(1));

List<User> all = mapper.findAll();
for (User user : all) {
    System.out.println(user);
}

User user = new User();
user.setUserName("小王");
user.setUserMoney(600);
int save = mapper.save(user);
System.out.println(save);
//增删改需要提交事务,查询不需要
sqlSession.commit();

User user = mapper.findById(1);
user.setUserName("小黄");
user.setUserMoney(2000);
int update = mapper.update(user);
System.out.println(update);
sqlSession.commit();

System.out.println(mapper.deleteById(4));
sqlSession.commit();

7、MyBatis 底层实现

功能:

  • 自定义接口
  • XML 中定义接口方法对应的 SQL 语句
  • 根据 XML,通过 JDK 动态代理(反射)完成自定义接口的具体实现
  • 自动解析结果集,映射成 XML 中配置的 JavaBean

技术:

  • XML 解析
  • Mapper 代理机制通过 JDK 动态代理,掌握反射

8、parameterType

设置参数数据类型,支持基本数据类型、包装类、String、多个参数、Java 对象

1、基本数据类型

public User findById(int id);
<select id="findById" parameterType="int" resultMap="userMap">
    select * from user where id = #{id}
</select>

#{id} 可以任意替换,因为只有一个参数,所以无论映射名是什么都可以完成映射

2、包装类

public User findById(Integer id);
<select id="findById" parameterType="java.lang.Integer" resultMap="userMap">
    select * from user where id = #{abc}
</select>

3、String

public User findByName(String name);
<select id="findByName" parameterType="java.lang.String" resultMap="userMap">
    select * from user where name = #{abc}
</select>

4、多个参数

多个参数的情况下,无法通过映射名来进行映射,而应该采用下标进行映射

arg0、arg1、param1、param2

public User findByIdAndName(Integer id,String name);
<select id="findByIdAndName" resultMap="userMap">
    select * from user where id = #{param1} and name = #{param2}
</select>

5、Java 对象

参数列表中的映射名就是实体类的属性名

public User findByUser(User user);
<select id="findByUser" parameterType="com.htl.entity.User" resultMap="userMap">
    select * from user where name = #{userName} and money = #{userMoney}
</select>

9、resultType

1、基本数据类型

public int count();
<select id="count" resultType="int">
    select count(id) from user
</select>

2、包装类

public Integer count();
<select id="count" resultType="java.lang.Integer">
    select count(id) from user
</select>

3、String

public String findNameById(Integer id);
<select id="findNameById" parameterType="java.lang.Integer" resultType="java.lang.String">
    select name from user where id = #{id}
</select>

4、Java 对象

public User findById(Integer id);
<select id="findById" parameterType="java.lang.Integer" resultMap="userMap">
    select * from user where id = #{abc}
</select>

10、多表关联查询

1、一对多

在这里插入图片描述

如果查询出来的结果是 null

1、数据确实不存在

2、数据存在,但是字段无法和实体类属性名进行映射

在这里插入图片描述

在这里插入图片描述

package com.htl.entity;

import lombok.Data;

@Data
public class Student {
    private Integer id;
    private String name;
    private Class aClass;
}
package com.htl.entity;

import lombok.Data;

@Data
public class Class {
    private Integer id;
    private String name;
}
package com.htl.mapper;

import com.htl.entity.Student;

public interface StudentMapper {
    public Student findById(Integer id);
}
<?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.htl.mapper.StudentMapper">

    <resultMap id="studentMap" type="com.htl.entity.Student">
        <id column="sid" property="id"></id>
        <result column="sname" property="name"></result>
        <association property="aClass" javaType="com.htl.entity.Class">
            <id column="cid" property="id"></id>
            <result column="cname" property="name"></result>
        </association>
    </resultMap>

    <select id="findById" resultMap="studentMap">
        select s.id sid,s.name sname,c.id cid,c.name cname
        from student s,class c where s.cid = c.id and s.id = #{id}
    </select>

</mapper>

TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 2

查询出来的结果集和实体类无法映射,接口方法返回值要求是一个对象,但是查出来多条结果。

package com.htl.entity;

import lombok.Data;

import java.util.List;

@Data
public class Class {
    private Integer id;
    private String name;
    private List<Student> students;
}
package com.htl.mapper;

import com.htl.entity.Class;

public interface ClassMapper {
    public Class findById(Integer id);
}

2、多对多关系

package com.htl.m2mentity;

import lombok.Data;

import java.util.List;

@Data
public class Course {
    private Integer id;
    private String name;
    private List<User> users;
}
package com.htl.m2mentity;

import lombok.Data;

import java.util.List;

@Data
public class User {
    private Integer id;
    private String name;
    private List<Course> courses;
}
package com.htl.mapper;

import com.htl.m2mentity.Course;

public interface CourseMapper {
    public Course findById(Integer id);
}
<?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.htl.mapper.CourseMapper">

    <resultMap id="courseMap" type="com.htl.m2mentity.Course">
        <id column="cid" property="id"></id>
        <result column="cname" property="name"></result>
        <collection property="users" ofType="com.htl.m2mentity.User">
            <id column="uid" property="id"></id>
            <result column="uname" property="name"></result>
        </collection>
    </resultMap>

    <select id="findById" parameterType="java.lang.Integer" resultMap="courseMap">
        select u.id uid,u.name uname,
        c.id cid,c.name cname from user u,course c,user_course uc
        where u.id = uc.uid and c.id = uc.cid and c.id = #{id}
    </select>

</mapper>

11、MyBatis 延迟加载

将某些加载(查询数据库)进行滞后操作,尽量减少 SQL 的执行,从而达到提高速度的目的,是对数据库操作的一种优化。

延迟加载(按需加载、懒加载)只存在于级联查询中,单表查询没有延迟加载的功能。

查询学生–>班级

MyBatis 打印 SQL

<settings>
    <!-- 打印SQL -->
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

同样的结果,但是 SQL 语句不同,尽量选择效率最高的 SQL 去执行。

1、多表关联查询的 SQL 拆分成两个 SQL 。

单独 SQL 查询 student

单独 SQL 查询 class

1、select * from student where id = 1;

在这里插入图片描述

查询出 student 的相关信息,再去查询级联的 class 信息

2、select * from class where id = 1

第 2 条 SQL 的条件就是第 1 条 SQL 的结果中的 cid

在这里插入图片描述

开启延迟加载之前,查询 name 需要执行两条 SQL

在这里插入图片描述

2、config.xml 配置文件中开启延迟加载。

开启延迟加载,如果只需要获取 student 的信息,那么只执行第一条 SQL,足够了。

<!-- 延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>

在这里插入图片描述

如果要获取级联的 class 信息,则第一条 SQL 不够用,此时再去执行第二条 SQL,这就是按需加载。

在这里插入图片描述

总结

MyBatis 框架的延迟加载,是实际开发中使用频录较高的功能,正确的使用延迟加载,可以有效减少 Java 程序和数据库的交互次数,从而提升整个系统的运行效率,延迟加载适用于多表关联查询的业务场景。

12、MyBatis 缓存

MyBatis 延迟加载,解决的是多表关联查询情况下的效率问题,但是对于单表查询,延迟加载没有作用,MyBatis 提供了缓存机制来解决单表查询情况下的效率问题。

使用缓存也是通过减少 Java 程序和数据库交互次数来提高查询效率,第一次查询出某个对象之后,MyBatis 会自动将它存入缓存,当下一次查询该对象的时候,可以直接从缓存中获取,不必再次访问数据库。

在这里插入图片描述

如果执行删除、修改操作,MyBatis 会自动清楚缓存,从而保证数据的时效性。

MyBatis 有两种缓存:一级缓存和二级缓存,作用域不同

12.1、一级缓存

MyBatis 自带一级缓存,并且无法关闭,一直存在,一级缓存的数据存储在 SqlSession,它的作用域是同一个 SqlSession,当使用同一个 SqlSession 执行查询的时候,第一次的结果会自动存入 SqlSession 缓存,第二次查询可以直接获取。

如果是两个不同的 SqlSession,则一级缓存不会生效。

在这里插入图片描述

package com.htl.test;

import com.htl.entity.Class;
import com.htl.entity.Student;
import com.htl.entity.User;
import com.htl.mapper.*;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

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

public class Test {
    public static void main(String[] args) {
        //加载MyBatis配置文件
        InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
        //构建SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(inputStream);
        //获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //通过sqlSession获取代理对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        Student student = mapper.selectById(1);
        System.out.println(student);
        //获取新的sqlSession
        sqlSession = factory.openSession();
        mapper = sqlSession.getMapper(StudentMapper.class);
        Student student1 = mapper.selectById(1);
        System.out.println(student1);
    }
}

在这里插入图片描述

12.2、二级缓存

一级缓存不需要进行任何配置,可以直接使用。

当一级缓存失效的时候,可以开启二级缓存,同样实现数据共享的功能,二级缓存是比一级缓存作用域更大的缓存机制,它是 Mapper 级别的,只要是同一个 Mapper,无论使用多少个 SqlSession 来创建,数据都是共享的,多个 SqlSession 可以共用二级缓存。

MyBatis 二级缓存默认是关闭的,需要使用的时候可以通过手动设置来开启。

1、config.xml 配置文件中开启二级缓存。

<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>

2、Mapper.xml 中配置二级缓存

<cache></cache>

3、实体类实现 Serializable 接口

package com.htl.entity;

import lombok.Data;

import java.io.Serializable;

@Data
public class Student implements Serializable {
    private Integer id;
    private String name;
    private Class aClass;
}

4、测试

package com.htl.test;

import com.htl.entity.Class;
import com.htl.entity.Student;
import com.htl.entity.User;
import com.htl.mapper.*;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

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

public class Test {
    public static void main(String[] args) {
        //加载MyBatis配置文件
        InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
        //构建SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(inputStream);
        //获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //通过sqlSession获取代理对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        Student student = mapper.selectById(1);
        System.out.println(student);
        sqlSession.close();
        //获取新的sqlSession
        sqlSession = factory.openSession();
        mapper = sqlSession.getMapper(StudentMapper.class);
        Student student1 = mapper.selectById(1);
        System.out.println(student1);
    }
}

要使用二级缓存,第一次使用的 SqlSession必须关闭,否则二级缓存无法开启。

SqlSession 在没有提交的情况下,不会将数据同步到二级缓存中,所以会导致第二次查询仍然要执行 SQL,所以一般执行完毕之后需要关闭 SqlSession,关闭的同时会自动提交。

12.3、总结

MyBatis 框架的缓存分为两种:一级缓存和二级缓存,一级缓存是 SqlSession 级别的,二级缓存是 Mapper 级别的,使用的时候需要注意两种缓存的区别,作用域不同,一级缓存是默认开启且无法关闭的,二级缓存需要手动开启。

缓存机制和延迟加载功能类似,都是通过减少 Java 程序和数据库的交互次数来提高系统的运行速度,缓存机制更多针对于单表查询,延迟加载更多针对多表关联查询。

缓存机制使用的前提是两次查询直接没有修改、删除的操作,如果有修改、删除的操作,那么缓存就会自动清空,从而保证数据的时效性。

13、MyBatis 动态 SQL

  • id 和 username 查询
  • username 和 password 查询
  • password 和 age 查询
<?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.mapper.UserMapper">

    <select id="findByUser1" resultType="com.domain.User">
        select * from user where id = #{id} and username = #{username}
    </select>

    <select id="findByUser2" resultType="com.domain.User">
        select * from user where password = #{password} and username = #{username}
    </select>

    <select id="findByUser3" resultType="com.domain.User">
        select * from user where password = #{password} and age = #{age}
    </select>

</mapper>

代码复用性很差,可以使用动态 SQL 来解决这个问题。

判断条件是否成立,如果成立则追加 if 标签中的内容,如果不成立,则不追加内容

自动判断 where 后面是否直接跟 and,如果是则删除 and,如果不是则保留 and

<select id="findByUser" resultType="com.domain.User">
    select * from user
    <where>
        <if test="id != null">
            id = #{id}
        </if>
        <if test="username != null">
            and username = #{username}
        </if>
        <if test="password != null">
            and password = #{password}
        </if>
        <if test="age != null">
            and age = #{age}
        </if>
    </where>
</select>

作用和 if 标签一致

<select id="findByUser" resultType="com.domain.User">
    select * from user
    <where>
        <choose>
            <when test="id != null">
                id = #{id}
            </when>
            <when test="username != null">
                and username = #{username}
            </when>
            <when test="password != null">
                and password = #{password}
            </when>
            <when test="age != null">
                and age = #{age}
            </when>
         </choose>
    </where>
</select>

prefix 中的值,如果和 prefixOverrides 中的值直接拼接,则自动删除 prefixOverrides 中的值。

<select id="findByUser" resultType="com.domain.User">
    select * from user
    <trim prefix="where" prefixOverrides="and">
        <if test="id != null">
            id = #{id}
        </if>
        <if test="username != null">
            and username = #{username}
        </if>
        <if test="password != null">
            and password = #{password}
        </if>
        <if test="age != null">
            and age = #{age}
        </if>
     </trim>
</select>

用于 update 操作,会自动根据参数选择生成 SQL 语句

<update id="update">
    update user
    <set>
        <if test="username != null">
            username = #{username},
        </if>
        <if test="password != null">
            password = #{password},
        </if>
        <if test="age != null">
            age = #{age}
        </if>
    </set>
    where id = #{id}
</update>

可以迭代生成一系列的值,这个标签主要用于 SQL 的 in 语句。

<select id="findByUser" parameterType="com.domain.User" resultType="com.domain.User">
    select * from user
    <where>
        <foreach collection="ids" item="id" open="id in (" close=")" separator=",">
               #{id}
        </foreach>
    </where>
</select>
浅谈 Mybatis 框架 MyBatis是一款优秀的持久层框架,它支持自定义SQL、存储过程(多条SQL语句的集合)以及高级映射。MyBatis 去除了几乎所有的JDBC代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的XML或注解来配置和映射原始类型、接口和Java POJO (Plain Old Java Objects,普通老式Java对象)为数据库中的记录。存储过程:高级映射:程序中的类对应数据库中的表,程序中的类里的属性对应数据库的表中的字段。 阅读详情

相关推荐

mybatis详解(全)

mybatis详解

Ferao的博客 15万+

mybatis学习文档

mybatis-9.28 环境: JDK1.8 mysql 8.0.16 maven3.6.1 IDEA 回顾: JDBC mysql jave基础 Maven junit 1.简介 1.1 什么是mybatis ​ mybatis是支持普通SQL查询、存储过程和高级映射的优秀持久层框架。 MyBatis 是一款优秀的持久层框架 支持自定义 SQL、存储过程以及高级映射 MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作 MyBatis 可

weixin_47356044的博客 3314

mybatis-入门

本文介绍了MyBatis的基本使用方式,包含两种构建SqlSessionFactory的方法:XML配置和Java代码实现。通过Maven依赖引入MyBatis最新版本(3.5.14),详细讲解了配置数据库连接、创建实体类、Mapper接口及XML映射文件的全过程。文章还演示了SqlSession的直接调用方式,解释了命名空间的作用,并展示了注解式SQL的写法。最后强调了SqlSessionFactoryBuilder、SqlSessionFactory和SqlSession的生命周期管理要点,推荐使用tr

cosseen的专栏 926

什么是MyBatis

MyBatis是什么?为什么要用MyBatis?一文搞定!!!

雷东宸的博客 3万+

Postman账号

Postman账号一、为什么要注册一个Postm账号二、如何注册Postman账号三、登录账号四、切换账号五、找回账号密码 一、为什么要注册一个Postm账号 注册Postman账号是免费的。当注册并登录一个Postman账号后,用户可以获得一下权限。 (1)同步和备份历史、集合、环境和预置头。 (2)可以轻松处理来自不同机器的多个Postman实例‘ (3)创建集合链接发送给其他开发人员。 当然,不注册也可以使用Postman。 二、如何注册Postman账号 (1)下载、安装Postman应用程序。 (

精益求精,永无止境,永远在路上! 6787

Visual Studio Community与Visual Studio Community与VS Code有啥区别

Visual Studio Code提供了基本的代码编辑、调试和版本控制功能,以及丰富的插件和扩展库。Visual Studio Community和Visual Studio Code在功能上有很大的差异,Visual Studio Community提供了比Visual Studio Code更多的功能,包括代码重构、智能提示、图形化设计等。他的优势在于它的轻量级和灵活性。此外,Visual Studio Code还具有丰富的扩展和插件生态系统,用户可以通过安装插件来扩展其功能,从而满足自己的需求。

m0_56551554的博客 2849

SSM整合之Mybatis笔记(MyBatis的缓存)(P053—P057)

SSM整合之Mybatis笔记(MyBatis的缓存)(P053—P057)

m0_59281987的博客 156

解决‘GLIBC_2.28 not found‘错误:手把手教你升级glibc到最新版(附中文乱码修复)

本文提供了一份详尽的Linux系统glibc升级实战指南,旨在解决常见的'GLIBC_2.28 not found'错误。文章不仅涵盖从风险评估、环境准备到编译安装的完整流程,还特别加入了精简本地化数据以修复中文乱码的实用技巧,帮助管理员和开发者在安全可控的前提下完成系统核心库的升级。

a1b2c3d的博客 1359

JAVA毕业设计——springboot057洗衣店订单管理系统

首页、个人中心、顾客管理店家管理、店铺信息管理、衣服类型管理洗衣信息管理、订单信息管理、订单进度管理交流区、系统管理首页、个人中心店铺信息管理、洗衣信息管理订单信息管理、订单进度管理首页、个人中心店铺信息管理、衣服类型管理洗衣信息管理、订单信息管理、订单进度管理注册,登录首页、店铺信息、交流区、系统公告、个人中心、后台管理、在线客服基础环境 :IDEA/eclipse, JDK 1.8,Mysql5.7及以上,Maven。

2401_87477518的博客 312

保姆级教程:用Kvaser DB Editor从零创建你的第一个DBC文件(附CAN信号属性详解)

本文提供了一份详细的Kvaser DB Editor教程,指导用户从零开始创建DBC文件,并深入解析CAN信号属性的关键设置。通过步骤清晰的安装指南、信号属性配置详解和实用技巧,帮助工程师和学生快速掌握CAN总线通信的核心工具,提升工作效率。

weixin_27076351的博客 265

C#上位机开发揭秘:从新手到大神的蜕变之路,代码实例全解析!

上位机通常是与硬件设备(如嵌入式系统、PLC、传感器等)进行通信的计算机程序。它的作用是通过某种通信协议(如串口、TCP/IP 等)向设备发送命令,并接收设备的反馈数据。上位机需要有一个图形用户界面(GUI)来展示数据或控制硬件设备。通过本篇教程,我们介绍了 C# 上位机开发的基本步骤,从串口通信的实现,到图形用户界面的构建,再到进阶功能的实现。作为上位机开发的新手,掌握这些基础知识是非常重要的。而随着经验的积累,你可以逐步尝试更复杂的功能,比如多线程处理、数据分析与存储等。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 4842

mybatis 使用in 查询时报错_使用mybatis的resultMap进行复杂查询 057

拿到表的第一时间要学会分析陌生表的数据模型:1、学习单表记录了什么东西(去学习理解需求)2、学习单表重要字段的意义(优先学习不能为空的字段)3、学习表与表之间的关系(一对一、一对多、多对多)通过表的外键分析表之间的关系注意:分析表与表之间的关系时是要建立在具体 的业务意义基础之上用户表user:记录了购买商品的用户订单表orders:记录了用户所创建的订单信息订单明细表orderdetail:记录...

weixin_28882363的博客 140

【Zephyr电源与功耗专题】13_PMU电源驱动介绍

本文介绍的PMU芯片包含2路DCDC和6路LDO,在Zephyr实时操作系统下实现了完整的电源管理解决方案。

zero的博客 846

mybatis 查询_使用mybatis的resultMap进行复杂查询 057

拿到表的第一时间要学会分析陌生表的数据模型:1、学习单表记录了什么东西(去学习理解需求)2、学习单表重要字段的意义(优先学习不能为空的字段)3、学习表与表之间的关系(一对一、一对多、多对多)通过表的外键分析表之间的关系注意:分析表与表之间的关系时是要建立在具体 的业务意义基础之上用户表user:记录了购买商品的用户订单表orders:记录了用户所创建的订单信息订单明细表orderdetail:记录...

weixin_39936792的博客 123

Untiy之如何实现AI+MR (Pico4u 相机推流MR画面给Server做实时AI图像识别)

本文介绍了基于Pico4U企业版开发AI+MR应用的实现方案。文章详细说明了硬件准备步骤,包括购买企业版设备、申请相机权限和注册管理平台。重点讲解了Unity开发中获取摄像头画面的两种技术方案:通过Overlay直接渲染到Android Surface,或使用API获取图像数据转换为Texture。提供了完整的代码示例和权限配置说明,并揭示了底层通过JNI调用Android原生API的技术原理。该方案适用于带电操作等实习场景,可提升安全性和学习趣味性。

TxNet 1360

支付域——账户系统设计

本文详细介绍了支付域中的账户系统设计,包括账户的定义、核心特征、常见类型以及在支付系统中的作用。账户是支付平台为用户、商户等主体建立的资金记录单元,具有资金归属、余额管理、交易流水、资金安全等核心特征。常见账户类型包括用户账户、商户账户、平台账户、保证金账户等。此外,还探讨了账户与银行账户的区别、账户的结构设计、如何设计账户类型以及账户系统设计等内容。

庄小焱 1207

Java学习总结--057MyBatis下的CRUD操作(增删改查)

Mapper接口本质就是原来的Dao接口,只是为了方便我们的书写。一个mapper接口对应一个mapper映射文件。 将UserMapper更名为UserDao,说明本质 修改对应的mapper映射文件的namespace属性,对应上接口。 1.编写接口 import com.kuang.pojo.User; import java.util.List; public interface Us...

web116629的博客 219

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

苍穹外卖学习笔记(跳过微信支付)

项目中使用到的技术框架和中间件前端我们就不自己写代码了 直接打开nginx.exe运行,打开端口访问前端页面Git学习笔记打开Gitee,点击加号创建远程仓库点击push,输入远程仓库url,输入账号密码,成功push记得在命令行中打开mysql连接: 在navicat打开sql文件,运行创建数据库内容 navicat运行sql文件nginx反向代理:就是将前端发送的动态请求由nginx转发到后端服务器使用md5加密算法将明文123456加密: 4. 导入接口文档 使用Apifox-导入-选择YApi-将j

m0_68356693的博客 772

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

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

Spring Boot 整合 tk.mybatis

概述 tk.mybatis 是在 MyBatis 框架的基础上提供了很多工具,让开发更加高效 引入依赖 在 pom.xml 文件中引入 mapper-spring-boot-starter 依赖,该依赖会自动引入 MyBaits 相关依赖 tk.mybatis mapper-spring-boot-starter 2.0.2 # 配置 application.yml 配...

好记性不如烂笔头 335

springboot和mybatis的整合—黑马上课学习笔记

springboot和mybatis整合笔记,仅供学习

qq_59746711的博客 514

Spring Boot 整合 MyBatis

1.Spring Boot 整合 Druid 概述 Druid 是阿里巴巴开源平台上的一个项目,整个项目由数据库连接池、插件框架和 SQL 解析器组成。该项目主要是为了扩展 JDBC 的一些限制,可以让程序员实现一些特殊的需求,比如向密钥服务请求凭证、统计 SQL 信息、SQL 性能收集、SQL 注入检查、SQL 翻译等,程序员可以通过定制来实现自己需要的功能。 Druid 是目前最好的数据...

步北宸的博客 811

CMS 6.MyBatis配置

1.在spring-mvc中配置数据库文件 2. 3. 4.

peanutのblog 234

springboot057洗衣店订单管理系统

结尾名片获取源码开发语言:Java框架:SpringBoot持久化框架:Mybatis-plusJDK版本:JDK1.8服务器:tomcat7\8\9数据库:mysql 5.7以上数据库工具:Navicat11以上开发软件:eclipse/myeclipse/idea浏览器:谷歌浏览器\Edge功能描述随着信息互联网信息的飞速发展,无纸化作业变成了一种趋势,针对这个问题开发一个专门适应洗衣店业务新的交流形式的网站。本文介绍了洗衣店订单管理系统的开发全过程。

Steve1122的博客 412

Springboot毕设项目宏盛仓库管理系统057p8(java+VUE+Mybatis+Maven+Mysql)

Jdk1.8 + Tomcat8.5 + Mysql + HBuilderX(Webstorm也行)+ Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)。若包含,则为maven项目,否则为非maven项目。Springboot + mybatis + Maven + Vue 等等组成,B/S模式 + Maven管理等等。Springboot毕设项目宏盛仓库管理系统057p8(java+VUE+Mybatis+Maven+Mysql)其他版本理论上也可以。

蒋道理吧 223
上一篇: 学习笔记056——Docker日志的清理问题
下一篇: 学习笔记058——Java中的【线程】
须晴日.
博客等级 码龄5年 595粉丝 103原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址