Spring 整合 Mybatis && 回顾 Mybatis

回顾mybatis
  • 添加依赖
      <!-- mybatis的依赖 maven真香 依赖真牛-->
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>
    <!--mysql的驱动依赖-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.19</version>
    </dependency>
<!--    日志记录-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-nop</artifactId>
      <version>1.7.2</version>
    </dependency>
    <!--   添加分页依赖 -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.10</version>
    </dependency>
  <build>
<!--  防止生成target文件时有文件丢失-->
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <!--包括目录下的.properties .xml 文件都会被扫描-->
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
  </build>
  • 在 resource文件中配置mybatis.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 环境标签 在里面可以配置多个environment (表示一个数据库的连接信息 id为自定义的环境标识 唯一值)-->
<!--    <properties resource="jdbc.properties"/>-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
<!--    声明别名-->
    <typeAliases>
<!--  1 第一种语法个格式 type ="java类型的全限定行名称 alias自定义别名 用别名对全类名进行替换 更加简洁 但是需要进行缺点 每个类需要进行单独定义
     2第二种方式: name包名 mybatis 会把包中的所有类名作为别名 不用区分大小写 -->
<!--        <typeAlias type="org.example.Student" alias="stu"/>-->
<!--        <package name="org.example.Student"/>-->
    </typeAliases>
<!-- 添加分页插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>
    <environments default="development">
<!--        //这里的mysql是代表默认加载的环境id,可以配置多个环境来切换--><!--配置mysql的环境-->
        <environment id="development">
<!--            //id表示对一个环境的唯一标识-->
            <!--配置事务的类型 type为事务管理类型 jdbc为 使用connection对象 由mybatis自己完成事务的处理
             manager 把事务的容器交给容器实现 -->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置数据源(连接池) 连接数据库 pooled mybatis会在内存中创建pooledDataSources 类管理多个连接对象
            使用的的是连接池-->
            <dataSource type="POOLED">
                <!--配置连接数据库的四个基本信息-->
<!--       driver :驱动的内容 -->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<!--         连接数据库的url       -->
                <property name="url" value="jdbc:mysql://localhost:3306/sys?useSSL=false&amp;serverTimezone=UTC"/>
<!--           连接数据库的账号     -->
                <property name="username" value="root"/>
<!--            连接数据库的密码    -->
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
<!-- mapper文件 指定其它mapper文件的位置直到其它文件中的sql语句
   可以使用mapper中的resource属性指定这个路径时从target/classes路径开始的
   使用注意: resource=mapper文件的路径使用/进行分割的 一个mapper对应 resource一个路径-->
    <mappers>
<!--   resource要求时dao的全限定性名称 每次添加一个mapper文件都要在xml文件中做一下声明 -->
        <mapper resource="dao/UserDao.xml"/>
        <mapper resource="dao/AdminDao.xml"/>
     <!-- 将包名添加进去 或者将xml文件添加进去-->
<!--        <package name="dao"/>-->
    </mappers>
</configuration>
  • 编写接口
    在这里插入图片描述
  • mapper文件
<?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.AdminDao">
    <select id="findAdmin" resultType="model.admin">
        select * from admin where account=#{account} and password=#{password}
    </select>
</mapper>
抽取工具类
/* 工具类创建 SqlSession对象*/
public class MyBatisUtil {
    //
    private static SqlSessionFactory factory = null;
    static{
        String config ="mybatis.xml";
        try {
            //将xml文件进行加载
            InputStream inputStream = Resources.getResourceAsStream(config);
            factory=new SqlSessionFactoryBuilder().build(inputStream);
        } catch(Exception e){
            e.printStackTrace();
        }
    }
    //创建方法得到sql session对象
    public static  SqlSession getSqlSession(){
        SqlSession session=null;
        if (factory!=null){
            session=factory.openSession();
        }
        return  session;
    }
}

简单讲解 SqlSessionFactory和 SqlSession的作用

SqlSessionFactory的作用?

SqlSessionFactory简单的理解就是创建SqlSession实例的工厂。所有的MyBatis应用都是以SqlSessionFactory实例为中心,SqlSessionFactory的实例可以通过SqlSessionFactoryBuilder对象来获取。有了它以后,顾名思义,就可以通过SqlSession提供的openSession()方法来获取SqlSession实例

SqlSession 作用

在这里插入图片描述

JDBC代码 对比理解
public class DBToolKitText {
	/*  */
	private static final String driver="oracle.jdbc.driver.OracleDriver";
	private static final String urlstr="jdbc:oracl:thin:@localhost:1521:orcl";
	private static final String username="scott";
	private static final String userPassW="Gguo123456";
	private static  Connection connnection = null;
	private static  PreparedStatement preparedStatement = null;
	private static  ResultSet resultSet = null;
	/* 使用静态代码块的好处是每次加载 类的时候都会执行 
	 因为加载驱动和 建立连接 和获得连接对象是一个必须要经过的步骤 */
	static {                                                                   //静态代码块 用于 加载驱动 Driver 接口 的实现类OracleDriver
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			System.out.println("加载驱动错误");
			System.out.println(e.getMessage());                               //getMessage()返回错误信息
		}
	}
	public static Connection getConnection() {                                //建立于数据库的连接操作 Connection接口 
		try {
			connnection = DriverManager.getConnection(urlstr,username,userPassW);
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		}
		return connnection;                                                   //将连接后的connection对象返回
	}
	public static  int executeUpdate(String sql, Object[] params) {           //执行insert、update或delete返回SQL语句行数执行create able语句
		int affectedLine = 0;
		try {
			connnection = getConnection();
			/* statement对象可以执行失sql语句 */
			preparedStatement = connnection.prepareStatement(sql);           //执行预编译的SQL语句是Statement的子接口
			for (int i = 0; i < params.length; i++) {
				preparedStatement.setObject(i + 1, params[i]);               //将指定参数设置为给定的params[],遍历参数
			}                                                                //第一个是指你SQL语句中的第几个参数,第二个是要设置的值
			affectedLine = preparedStatement.executeUpdate();               
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		} finally {
			closeAll();                                                     //将closeAll()放在fianlly中保证了一定能将执行,回收
		}
		return affectedLine;                                                //将返回的SQL执行语句返回
	}
	public static ResultSet executeQueryRS(String sql) {                    //保存JDBC执行查询时返回的结果集该结果集封装在一个逻辑表格中
		try {
			connnection = getConnection();    
			preparedStatement = connnection.prepareStatement(sql);
			/*resultset为 */
			resultSet = preparedStatement.executeQuery();                  //用于执行查询语句,返回ResultSet结果集对象
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		}
		return resultSet;                                                 
	}                                                                     //有参数形式
	public static ResultSet executeQueryRS(String sql, Object[] params) {  
		try {
			connnection = getConnection();
			preparedStatement = connnection.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				preparedStatement.setObject(i + 1, params[i]);
			}
			resultSet = preparedStatement.executeQuery();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		}
		return resultSet;
	}
	public static  List<Object> excuteQuery(String sql,Object[] params) {   //返回ResultSet的结果集放到List中
		ResultSet rs = executeQueryRS(sql, params);                           
		ResultSetMetaData rsmd = null;
		int columnCount = 0;
		try {
			/*检索此Resultset对象的列的数目、类型和属性。*/
			rsmd = rs.getMetaData();                                       //DatabaseMetaData接口获取元数据的方法。
			columnCount = rsmd.getColumnCount();                           //返回(报表样式)列表视图对象中的列数。
		} catch (SQLException e1) {
			System.out.println(e1.getMessage());
		}
		List<Object> list = new ArrayList<Object>();                       //泛型集合 
		try {
			while (rs.next()) {
				Map<String, Object> map = new HashMap<String, Object>();   // Map接口的实现类 提供所有映射操作
				for (int i = 1; i <= columnCount; i++) {
					/*通俗讲就是将*/
					map.put(rsmd.getColumnLabel(i), rs.getObject(i));       //将指定的值于此映射中的指定键关联
				}
				list.add(map);
			}
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		} finally {
			closeAll();
		}

		return list;
	}
	private static  void closeAll() {                                      //将所有数据回收关闭不多说

		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				System.out.println(e.getMessage());
			}
		}
		if (preparedStatement != null) {
			try {
				preparedStatement.close();
			} catch (SQLException e) {
				System.out.println(e.getMessage());
			}
		}
		if (connnection != null) {
			try {
				connnection.close();
			} catch (SQLException e) {
				System.out.println(e.getMessage());
			}
		}
	}
/*	public static List<Object> excuteQuery(String sql) {
		// TODO Auto-generated method stub
		return list;
	}
*/	
}

在这里插入图片描述

Spring对Mybatis的整合
  • 首先在Pom文件中引入支持Spring整和的依赖
<!--        mybatis-spring-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>
<!--        spring依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.12</version>
        </dependency>
<!--    spring-jdbc    -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.19.RELEASE</version>
        </dependency>
        <!--    添加上aop依赖-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>

在这里插入图片描述

Spring的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--    DataSource :使用Spring的数据源提供的mybatis的配置 这里使用的是
Spring提供的JDBC org.springframework.jdbc.datasource-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/sys?useSSL=false&amp;serverTimezone=UTC"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>
<!--    SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
<!--       绑定mybatis的配置文件-->
<!--        <property name="configLocation" value="classpath:mybatis.xml"/>-->
        <property name="mapperLocations" value="classpath:dao/*.xml"/>
    </bean>
<!--    SqlSession -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--     只能使用构造器注入 因为没有set方法 -->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
</beans>

在这里插入图片描述

    public List<User> findAll() {
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        return mapper.findAll();
    }

测试类

         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao = context.getBean("userDaoImpl", UserDao.class);
方式二:
public class UserDaoImpl  extends SqlSessionDaoSupport implements UserDao{
    @Override
    public List<User> findAll() {
        return getSqlSession().getMapper(UserDao.class).findAll();
    }
}
  • 我们来看一下SqlSessionDaoSupport 的源码
    在这里插入图片描述

配置操作

    <bean id="userDaoImpl" class="dao.UserDaoImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值