资讯详情

SSM框架

SSM框架

MyBatis

MyBatis简介

  1. 一款
  2. MyBatis 几乎所有的避免 JDBC 代码和手动设置参数以及获取结果集的过程
  3. MyBatis 使用简单 XML 或注释配置和映射原始信息 Java 的 实体类 【Plain Old Java Objects,普通的 Java对象映射成数据库中的记录。
  4. 可以通过Maven仓库获得MyBatis

  1. 持久化是程序数据的持久性的机制。
  2. 也就是说,将数据(如内存中的对象)存储在可永久存储的存储设备中(如磁盘)。持久性的主要应用程序是将内存中的对象存储在数据库或磁盘文件中XML中等数据文件。

  1. 完成持久工作的代码块 . ----> 【DAO (Data Access Object) 数据访问对象
  2. 持久实现的过程大多是通过各种方式实现的来完成

  1. Mybatis帮助程序猿使用数据数据库中 , 和从数据库中数据
  2. 传统的jdbc操作 , 重复代码块很多 .比如 : 数据取出时的包装 , 数据库的建立连接等等… , 可以通过框架
  3. MyBatis 半自动化
  4. MyBatis的优点

一个MyBatis程序

  1. 创造一个普通的maven项目

  2. 导入依赖

     <dependencies>         <!--mysql驱动-->         <dependency>             <groupId>mysql</groupId>             <artifactId>mysql-connector-java</artifactId>             <version>5.1.14</version>         </dependency>          <!--mybatis-->         <dependency>             <groupId>org.mybatis</groupId>             <artifactId>mybatis</artifactId>             <version>3.5.6</version>         </dependency> 
  3. 编写MyBatis 核心配置文件

    mybatis-config.xml在resources文件中

    <?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="development">
           <environment id="development">
               <transactionManager type="JDBC"/>
               <dataSource type="POOLED">
                   <property name="driver" value="com.mysql.jdbc.Driver"/>
                   <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
                   <property name="username" value="root"/>
                   <property name="password" value="123456"/>
               </dataSource>
           </environment>
       </environments>
    <!--每一个Mpper,XML都需要Mybatis核心配置文件中注册-->
        <mappers>
        <!--<mapper resource="com/tqw_zg/dao/UserMapper.xml"/>-->
            <!--<mapper class="com.tqw_zg.dao.UserMapper"/>-->
            <package name="com.tqw_zg.dao"/>
        </mappers>
     </configuration>
    
    
  4. 编写MyBatis工具类

    //sqlSessionFactory --> sqlSession
    public class MybatisUtils { 
              
    
        static SqlSessionFactory sqlSessionFactory = null;
    
        static { 
              
            try { 
              
                //使用Mybatis第一步 :获取sqlSessionFactory对象
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) { 
              
                e.printStackTrace();
            }
        }
    
        //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例.
        // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
        public static SqlSession getSqlSession(){ 
              
            return sqlSessionFactory.openSession();
        }
    }
    
    
  5. dao接口

    public interface UserDao { 
              
        //获取全部用户
        List<User> getUserList();
    
        //模糊查询一个用户
        List<User> getUserLike(String str);
    
        //根据ID查询用户
        User getUserById(int id);
    
        //添加一个用户
        int addUser(User user);
    
        int addUser2(Map<String,Object> map);
    
        //修改用户
        int updateUser(User user);
    
        //删除一个用户
        int deleteUser(int id);
    
    }
    
  6. 接口实现类

    UserMapper.xml在dao文件下

    <?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">
    <!--namespace=绑定一个对应的Dao/Mapper接口-->
    <mapper namespace="com.tqw_zg.dao.UserDao">
        <select id="getUserList" resultType="com.tqw_zg.pojo.User">
          select * from mybatis.user
         </select>
    
        <select id="getUserById" resultType="com.tqw_zg.pojo.User" parameterType="int">
          select * from mybatis.user where id=#{ 
              id}
         </select>
    
        <insert id="addUser" parameterType="com.tqw_zg.pojo.User">
          insert into mybatis.user (id, name, pwd) values (#{ 
              id}, #{ 
              name}, #{ 
              pwd})
         </insert>
    
    
        <update id="updateUser" parameterType="com.tqw_zg.pojo.User">
            update mybatis.user set name=#{ 
              name},pwd=#{ 
              pwd} where id=#{ 
              id}
        </update>
    
        <delete id="deleteUser" parameterType="int">
            delete from mybatis.user where id=#{ 
              id}
        </delete>
    
    </mapper>
    
  7. 配置类还可以这样写

    db.properties

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
    username=root
    password=123456
    

    mybatis-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>
        <properties resource="db.properties"/>
        <!--可以给实体类起别名-->
        <!--<typeAliases>-->
            <!--<typeAlias type="com.tqw_zg.pojo.User" alias="User"/>-->
        <!--</typeAliases>-->
        <typeAliases>
            <package name="com.tqw_zg.pojo"/>
        </typeAliases>
    
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="${driver}"/>
                    <property name="url" value="${url}"/>
                    <property name="username" value="${username}"/>
                    <property name="password" value="${password}"/>
                </dataSource>
            </environment>
        </environments>
        <!--每一个Mpper,XML都需要Mybatis核心配置文件中注册-->
        <mappers>
            <!--<mapper resource="com/tqw_zg/dao/UserMapper.xml"/>-->
            <!--<mapper class="com.tqw_zg.dao.UserMapper"/>-->
            <package name="com.tqw_zg.dao"/>
        </mappers>
    </configuration>
    
  8. 测试

    @Test
        public void test(){ 
              
    
            //1.获取SqlSession对象
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            //2.执行SQL
            // 方式一:getMapper
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            List<User> userList = userDao.getUserList();
            for (User user : userList) { 
              
                System.out.println(user);
            }
    
            //关闭sqlSession
            sqlSession.close();
        }
    
    

    注意:增删改一定要提交事务

    sqlSession.commit();

  9. 万能Map

    假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应该考虑使用Map!

    UserMapper接口
    //用万能Map插入用户
    public void addUser2(Map<String,Object> map);
    
    UserMapper.xml
    <!--对象中的属性可以直接取出来 传递map的key-->
    <insert id="addUser2" parameterType="map">
        insert into user (id,name,pwd) values (#{ 
              userid},#{ 
              username},#{ 
              userpassword})
    </insert>
    
    测试
        @Test
        public void test3(){ 
              
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("userid",4);
            map.put("username","王虎");
            map.put("userpassword",789);
            mapper.addUser2(map);
            //提交事务
            sqlSession.commit();
            //关闭资源
            sqlSession.close();
        }
    
    
  10. 模糊查询

Java代码执行的时候,传递通配符% %

List userList = mapper.getUserLike("%李%");

在sql拼接中使用通配符

select * from user where name like “%”#{value}"%"

  1. 配置解析

    MyBatis默认的事务管理器就是JDBC ,连接池:POOLED

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kQ2cnN3g-1633929723333)(C:\Users\zg\AppData\Roaming\Typora\typora-user-images\1633577279151.png)]

  2. 解决属性名和字段名不一致的问题

    1. 起别名

      pwd as password

    2. 结果映射集

      <resultMap id="UserMap" type="com.tqw_zg.pojo.User">
          <!--column数据库中的字段,property实体类中的属性-->
          <result column="id" property="id"></result>
          <result column="name" property="name"></result>
          <result column="pwd" property="password"></result>
      </resultMap>
      
      <select id="getUserList" resultMap="UserMap">
          select * from USER where id=${ 
                  id}
      </select>
      
  3. 分页

    使用Limit分页

    SELECT * from user limit startIndex,pageSize 
    SELECT * from user limit 3; [0,n]
    

    代码实现

    接口
    //分页
    List<User> getUserByLimit(Map<String,Integer> map);
    
    Mapper.xml
    <!--分页查询-->
    <select id="getUserByLimit" parameterType="map" resultMap="UserMap">
        select * from user limit #{ 
              startIndex},#{ 
              pageSize}
    </select>
    
    测试
    
        @Test
        public void getUserByLimit(){ 
              
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            HashMap<String, Integer> map = new HashMap<String, Integer>();
            map.put("startIndex",1);
            map.put("pageSize",2);
            List<User> list = mapper.getUserByLimit(map);
            for (User user : list) { 
              
                System.out.println(user);
            }
        }
    
    
  4. 使用注解开发

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-P3nsr8qh-1633929723336)(C:\Users\zg\AppData\Roaming\Typora\typora-user-images\1633577710334.png)]

    注解在接口上实现

    @Select("select * from user")
    List<User> getUsers();
    

    需要在核心配置文件中绑定接口

    <mappers>
      <mapper class="com.kuang.dao.UserMapper"/>
    </mappers>
    

    本质:反射机制实现

    底层:动态代理

    方法存在多个参数,所有的参数前面必须加上@Param(“id”)注解

    基本类型的参数或者String类型,需要加上@Param()

    #{}可以很大程度防止sql注入

    ${}不可以防止sql注入

  5. 多对一

    多个学生关联一个老师

     <!--按照结果进行查询-->
        <select id="getStudent2" resultMap="StudentTeacher2">
            select s.id sid , s.name sname, t.name tname
            from student s,teacher t
            where s.tid=t.id
        </select>
        <!--结果封装,将查询出来的列封装到对象属性中-->
        <resultMap id="StudentTeacher2" type="student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <association property="teacher" javaType="teacher">
                <result property="name" column="tname"></result>
            </association>
        </resultMap>
    
  6. 一对多

    一个老师管理多个学生

    <!--按结果嵌套查询-->
    <select id="getTeacher" resultMap="StudentTeacher">
        SELECT s.id sid, s.name sname,t.name tname,t.id tid FROM student s, teacher t
        WHERE s.tid = t.id AND tid = #{ 
              tid}
    </select>
    <resultMap id="StudentTeacher" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <!--复杂的属性,我们需要单独处理 对象:association 集合:collection
        javaType=""指定属性的类型!
        集合中的泛型信息,我们使用ofType获取
        -->
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>
    
  7. 动态SQL

  8. 缓存

Spring

  1. Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器(框架)

    Spring 框架是一个分层架构,由 7 个定义良好的模块组成。Spring 模块构建在核心容器之上,核心容器定义了创建、配置和管理 bean 的方式 .

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-O613GwcJ-1633929723337)(C:\Users\zg\AppData\Roaming\Typora\typora-user-images\1633592851141.png)]

    组成 Spring 框架的每个模块(或组件)都可以单独存在,或者与其他一个或多个模块联合实现。每个模块的功能如下:

    • :核心容器提供 Spring 框架的基本功能。核心容器的主要组件是 BeanFactory,它是工厂模式的实现。BeanFactory 使用控制反转(IOC) 模式将应用程序的配置和依赖性规范与实际的应用程序代码分开。
    • :Spring 上下文是一个配置文件,向 Spring 框架提供上下文信息。Spring 上下文包括企业服务,例如 JNDI、EJB、电子邮件、国际化、校验和调度功能。
    • :通过配置管理特性,Spring AOP 模块直接将面向切面的编程功能 , 集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理任何支持 AOP的对象。Spring AOP 模块为基于 Spring 的应用程序中的对象提供了事务管理服务。通过使用 Spring AOP,不用依赖组件,就可以将声明性事务管理集成到应用程序中。
    • :JDBC DAO 抽象层提供了有意义的异常层次结构,可用该结构来管理异常处理和不同数据库供应商抛出的错误消息。异常层次结构简化了错误处理,并且极大地降低了需要编写的异常代码数量(例如打开和关闭连接)。Spring DAO 的面向 JDBC 的异常遵从通用的 DAO 异常层次结构。
    • :Spring 框架插入了若干个 ORM 框架,从而提供了 ORM 的对象关系工具,其中包括 JDO、Hibernate 和 iBatis SQL Map。所有这些都遵从 Spring 的通用事务和 DAO 异常层次结构。
    • :Web 上下文模块建立在应用程序上下文模块之上,为基于 Web 的应用程序提供了上下文。所以,Spring 框架支持与 Jakarta Struts 的集成。Web 模块还简化了处理多部分请求以及将请求参数绑定到域对象的工作。
    • :MVC 框架是一个全功能的构建 Web 应用程序的 MVC 实现。通过策略接口,MVC 框架变成为高度可配置的,MVC 容纳了大量视图技术,其中包括 JSP、Velocity、Tiles、iText 和 POI。
  2. IOC本质

,也有人认为DI只是IoC的另一种说法。没有IoC的程序中 , 我们使用面向对象编程 , 对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0Kjl6f3I-1633929723338)(file:///C:/Users/zg/AppData/Local/Temp/msohtmlclip1/01/clip_image002.png)]

,使用多种方式完美的实现了IoC,可以使用XML配置,也可以使用注解,新版本的Spring也可以零配置实现IoC。

Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从Ioc容器中取出需要的对象。

采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

​ [外链图片转存失败,源站可能有防盗

标签: fmd68m连接器160v155j安规电容器5tj5zk连接器1v69连接器ygm219微风速变送器精轧螺纹钢连接器ygm28mm

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台