Java架构师升级之路之MyBatis精讲以及Spring整合MyBatis(实用篇)

574 篇文章 4 订阅

Mybatis各个模块:
在这里插入图片描述
Mapper映射的配置文件注意之一: 自增主键
在这里插入图片描述
NameSpace:1>相当于包的作用;2>定义接口方法和xml中id一致

一级缓存(session级别的会话,默认开启的)、二级缓存

在这里插入图片描述
1.减少数据库的压力,一次会话结束后,第二次请求会命中缓存。

2.查询脏数据的问题,我们使用的原因是优点大于缺点。

在这里插入图片描述
更新策略:update/delete

二级缓存默认是关闭的,不建议使用,一般用redis替代
基于nameSpace的,或者是mapper.xml文件的

在这里插入图片描述
在这里插入图片描述
证明二级缓存的存在:
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
1>出现脏数据,2>失效问题
在这里插入图片描述
更新的时候blog1时候全部删掉其他内容

MyBatis 实用操作

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
联合查询:

a)嵌套查询;

在这里插入图片描述

在这里插入图片描述
嵌套查询 1:N

懒加载:用到的时候就给我加载业务,不用的时候不需要给我加载。
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
与1:1比较 在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

b)嵌套结果;
对结果嵌套:也就是对查询的结果做映射。 join
1:1 情况下
在这里插入图片描述
在这里插入图片描述

N+1问题:比如当需要Blog信息的时候 ,只做select * from blog where id=1查询;当需要评论信息时候,它会做N次查询。
在这里插入图片描述
在这里插入图片描述

MyBatis关于懒加载与N+1问题。

Spring整合MyBatis demo

13-spring-mybatis-druid:整合spring和mybatis,使用阿里公司的druid数据库的连接池

spring整合mybatis的主要思路: 把mybatis的对象交给spring统一创建和管理。
哪些对象交给spring:
1.数据源DataSource,表示数据库的连接,访问数据库的。
2.SqlSessionFactory, 使用它创建SqlSession对象
3.Dao对象。 由spring使用mybatis的动态代理技术,创建Dao接口的实现类对象。


步骤:
1.新建mysql的数据库springdb, 新建表student(id,name,age)
2.新建java project
3.导入jar:
  1)spring的核心:spring-core.jar,spring-beans.jar,spring-context.jar,spring-expression.jar
  2)spring的aop:spring-aop.jar(支持环绕通知,使用事务处理)
  3)spring访问数据库的相关jar:spring-jdbc.jar,spring-tx.jar
     spring整合mybatis事务是自动提交的方式。
  4)mybatis的核心:mybatis-3.4.5.jar
  5)mybatis和spring的整合包: mybatis-spring-1.3.1.jar ,
         整合包的作用:能够在spring框架中创建mybatis的对象。 整合包来自mybatis的官网。
  6)数据库的驱动:mysql的驱动
  7)数据库的连接池: druid.1.1.9.jar
  8)其他:日志, 单元测试。 
4.定义实体类:Student
5.定义Dao接口和sql映射文件
6.定义MyBatis的主配置文件
7.定义Service接口和实现类,在实现类中应该有一个Dao的属性
8.定义spring的配置文件:重点
  1)声明数据源DataSource, 访问数据库
  2)声明SqlSessionFactoryBean, 创建SqlSessionFactory对象
  3)声明MyBatis的扫描器对象,创建Dao接口的实现类对象。
  4)声明Service对象,把Dao对象注入给Service的属性
9.定义测试类, 访问数据库

 

在这里插入图片描述

package com.bjpowernode.beans;

public class Student {

	//定义属性, 属性名和列名一样
	private Integer id;
	private String name;
	private Integer age;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	
	
}

package com.bjpowernode.service;

import java.util.List;

import com.bjpowernode.beans.Student;

public interface StudentService {

	int addStudent(Student student);
	List<Student> queryStudents();
}

package com.bjpowernode.service;

import java.util.List;

import com.bjpowernode.beans.Student;
import com.bjpowernode.dao.StudentDao;

public class StudentServiceImpl implements StudentService {

	//引用类型
	private StudentDao stuDao;
	
	//IoC的设值注入
	public void setStuDao(StudentDao stuDao) {
		this.stuDao = stuDao;
	}
	
	@Override
	public int addStudent(Student student) {
		int rows  = stuDao.insertStudent(student);
		return rows;
	}

	@Override
	public List<Student> queryStudents() {
		List<Student> students = stuDao.selectStudents();
		return students;
	}

}

package com.bjpowernode.dao;

import java.util.List;

import com.bjpowernode.beans.Student;

public interface StudentDao {
	
	int insertStudent(Student student);
	List<Student> selectStudents();

}

<?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.bjpowernode.dao.StudentDao">
    <insert id="insertStudent">
    	insert into student(name,age) values(#{name},#{age})
    </insert>
    
    <select id="selectStudents" resultType="Student">
    	select id,name,age from student order by id desc
    </select>
</mapper>
<?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>

	<!-- 配置别名 -->
	<typeAliases>
		<package name="com.bjpowernode.beans"/>
	</typeAliases>
	
	<!-- 配置sql映射文件 -->
	<mappers>
		<package name="com.bjpowernode.dao"/>
	</mappers>
	
</configuration>
jdbc.url=jdbc:mysql://localhost:3306/springdb
jdbc.username=root
jdbc.password=root
<?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:context="http://www.springframework.org/schema/context"
    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/context 
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd">
        
    <!-- 指定属性配置文件的位置 
         location:指定属性配置文件的位置,使用classpath:表示类路径
    -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
        
    <!-- 声明数据源DataSource, 使用druid -->
    <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
       init-method="init" destroy-method="close" >
        <!-- 
                      使用属性配置文件中的数据, 语法格式: ${key}
         -->
    	<property name="url" value="${jdbc.url}" />
    	<property name="username" value="${jdbc.username}" />
    	<property name="password" value="${jdbc.password}" />
    </bean>
    
    <!-- 声明SqlSessionFactoryBean ,创建SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    	<!-- 指定数据源DataSource -->
    	<property name="dataSource" ref="myDataSource" />
    	<!-- 指定mybatis的主配置文件 
    	     Resource类型,赋值使用value ,spring会读取文件,转为Resource类型
    	     classpath:指定到类路径中找配置文件  
    	-->
    	<property name="configLocation" value="classpath:mybatis.xml" />
    </bean>
    
    <!-- 声明mybatis的扫描器对象,创建Dao接口的实现类对象 -->
    <!-- 
        1.通过属性sqlSessionFactoryBeanName,能获取到SqlSessionFactory
        2.通过SqlSessionFactory.openSession(),得到SqlSession对象
        for(接口:com.bjpowernode.dao所有接口){
                         接口的实现类对象  = 使用sqlSession.getMapper(接口.class);
                         把创建好的对象放入到spring的容器中,springMap.put(接口的首字母小写,接口的实现类对象)
        }
    
     -->
    <bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    	<!-- 指定SqlSessionFactory对象 -->
    	<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    	<!-- 指定Dao接口的包名 -->
    	<property name="basePackage" value="com.bjpowernode.dao" />
    </bean>
    
    <!-- 声明Service对象 -->
    <bean id="studentService" class="com.bjpowernode.service.StudentServiceImpl">
    	<property name="stuDao" ref="studentDao"/>
    </bean>
</beans>
package com.bjpowernode.test;

import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.bjpowernode.beans.Student;
import com.bjpowernode.service.StudentService;

public class MyTest {
	
	private StudentService service;
	//定义junit的初始化方法
	@Before
	public void myinit(){
		String config="applicationContext.xml";
		ApplicationContext ctx  = new ClassPathXmlApplicationContext(config);
		service  = (StudentService) ctx.getBean("studentService");
		
	}

	//测试添加功能
	@Test
	public void testAddStudent(){
		
		Student student = new Student();
		student.setAge(20);
		student.setName("周丽");
		int rows  = service.addStudent(student);
		System.out.println("添加的结果:"+rows);
	}
	
	@Test
	public void testQueryStudents(){
		List<Student> students = service.queryStudents();
		for(Student stu : students){
			System.out.println(stu);
		}
	}
	
	@Test
	public void testGetObjects(){
		String config="applicationContext.xml";
		ApplicationContext ctx  = new ClassPathXmlApplicationContext(config);
		String names [] = ctx.getBeanDefinitionNames();
		for(String name: names){
			System.out.println(name);
		}
	}
}

DBCP连接池

14-spring-mybatis-dbcp:整合spring和mybatis,使用dbcp数据库的连接池

spring整合mybatis的主要思路: 把mybatis的对象交给spring统一创建和管理。
哪些对象交给spring:
1.数据源DataSource,表示数据库的连接,访问数据库的。
2.SqlSessionFactory, 使用它创建SqlSession对象
3.Dao对象。 由spring使用mybatis的动态代理技术,创建Dao接口的实现类对象。


步骤:
1.新建mysql的数据库springdb, 新建表student(id,name,age)
2.新建java project
3.导入jar:
  1)spring的核心:spring-core.jar,spring-beans.jar,spring-context.jar,spring-expression.jar
  2)spring的aop:spring-aop.jar(支持环绕通知,使用事务处理)
  3)spring访问数据库的相关jar:spring-jdbc.jar,spring-tx.jar
     spring整合mybatis事务是自动提交的方式。
  4)mybatis的核心:mybatis-3.4.5.jar
  5)mybatis和spring的整合包: mybatis-spring-1.3.1.jar ,
         整合包的作用:能够在spring框架中创建mybatis的对象。 整合包来自mybatis的官网。
  6)数据库的驱动:mysql的驱动
  7)数据库的连接池: dbcp.jar, pool.jar
  8)其他:日志, 单元测试。 
4.定义实体类:Student
5.定义Dao接口和sql映射文件
6.定义MyBatis的主配置文件
7.定义Service接口和实现类,在实现类中应该有一个Dao的属性
8.定义spring的配置文件:重点
  1)声明数据源DataSource, 访问数据库
  2)声明SqlSessionFactoryBean, 创建SqlSessionFactory对象
  3)声明MyBatis的扫描器对象,创建Dao接口的实现类对象。
  4)声明Service对象,把Dao对象注入给Service的属性
9.定义测试类, 访问数据库

  
  

  


jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springdb
jdbc.username=root
jdbc.password=root
<?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:context="http://www.springframework.org/schema/context"
    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/context 
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd">
        
    <!-- 指定属性配置文件的位置 
         location:指定属性配置文件的位置,使用classpath:表示类路径
    -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    
    <!-- 声明dbcp数据库的连接池 -->
    <bean id="myDataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <!-- 配置4个属性,访问数据库 -->
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
    	<property name="username" value="${jdbc.username}" />
    	<property name="password" value="${jdbc.password}" />
    </bean>
    
    <!-- 声明SqlSessionFactoryBean ,创建SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    	<!-- 指定数据源DataSource -->
    	<property name="dataSource" ref="myDataSource" />
    	<!-- 指定mybatis的主配置文件 
    	     Resource类型,赋值使用value ,spring会读取文件,转为Resource类型
    	     classpath:指定到类路径中找配置文件  
    	-->
    	<property name="configLocation" value="classpath:mybatis.xml" />
    </bean>
    
    <!-- 声明mybatis的扫描器对象,创建Dao接口的实现类对象 -->
    <!-- 
        1.通过属性sqlSessionFactoryBeanName,能获取到SqlSessionFactory
        2.通过SqlSessionFactory.openSession(),得到SqlSession对象
        for(接口:com.bjpowernode.dao所有接口){
                         接口的实现类对象  = 使用sqlSession.getMapper(接口.class);
                         把创建好的对象放入到spring的容器中,springMap.put(接口的首字母小写,接口的实现类对象)
        }
    
     -->
    <bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    	<!-- 指定SqlSessionFactory对象 -->
    	<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    	<!-- 指定Dao接口的包名 -->
    	<property name="basePackage" value="com.bjpowernode.dao" />
    </bean>
    
    <!-- 声明Service对象 -->
    <bean id="studentService" class="com.bjpowernode.service.StudentServiceImpl">
    	<property name="stuDao" ref="studentDao"/>
    </bean>
</beans>

在web应用中,使用spring

16-spring-web2:在web应用中,使用spring。spring管理Service,Dao对象

web项目中使用spring的问题:
1.容器对象创建多次了, 应该是创建一次 (在应用启动的时候创建一次)
2.容器对象需要在多个Servlet中使用,需要把容器对象放入到全局作用域ServletContext

解决问题使用监听器(自定义),框架提供了ContextLoaderLister监听器
==============================================================
private WebApplicationContext context;
public interface WebApplicationContext extends ApplicationContext
public interface ConfigurableWebApplicationContext extends WebApplicationContext

把创建好的spring容器对象,放入到ServletContext中

servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

key :  WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
       
this.context: 是WebApplicationContext

步骤:
1.新建 web应用
   加入jar:spring-web.jar
2.拷贝14-spring-mybatis-dbcp项目中的lib, src项目的源码和配置文件
3.新建jsp,定义form,有参数name,age
4.新建Servlet,接收请求参数, 在Servlet中创建Spring的容器, 获取Service对象,调用Service的业务方法。
5.新建显示处理结果的jsp
6.修改web.xml:
  1)注册Servlet
  2)注册监听器
  

在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>15-spring-web</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
  	<servlet-name>RegServlet</servlet-name>
  	<servlet-class>com.bjpowernode.action.RegisterServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>RegServlet</servlet-name>
  	<url-pattern>/regservlet</url-pattern>
  </servlet-mapping>
  
  
  <!-- 注册监听器:1.创建spring的容器对象;2.把创建好的容器对象放入到ServletContext中 -->
  
  <!-- 
               监听器启动的时候,找/WEB-INF/applicationContext.xml , 
               这个文件是在监听器中创建spring容器时,默认加载的配置文件路径和名称。
   -->
   
  <!-- 使用自动的配置文件路径和名称 -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:spring.xml</param-value>
  </context-param>
  <listener>
    <!-- spring-web.jar -->
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
  index.jsp <br>
  <form action="regservlet" method="post">
  	姓名:<input type="text" name="name" /><br>
  	年龄:<input type="text" name="age" /><br>
  	<input type="submit" value="注册">   
  </form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  result.jsp:注册成功!!!
</body>
</html>

Servlet 类

package com.bjpowernode.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.bjpowernode.beans.Student;
import com.bjpowernode.service.StudentService;


public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
  
    public RegisterServlet() {
        super();
       
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取请求参数 name ,age
		String strName = request.getParameter("name");
		String strAge = request.getParameter("age");
		
		//创建spring容器对象
		String configLocation="applicationContext.xml";
		//ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocation);
		//从ServletContext中获取容器对象
		
		//String key = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
		//WebApplicationContext ctx  = (WebApplicationContext) this.getServletContext().getAttribute(key);
		
		//框架提供一方法,获取容器对象
		WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
		System.out.println("容器对象:"+ctx);
		
		//从容器中获取对象
		StudentService service = (StudentService) ctx.getBean("studentService");
		
		//调用Service的方法
		Student student = new Student();
		student.setAge(Integer.parseInt(strAge));
		student.setName(strName);
		service.addStudent(student);
		
		//指定显示处理结果的页面
		request.getRequestDispatcher("/result.jsp").forward(request, response);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		doGet(request, response);
	}

}

1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。、可私 6信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 、可私信6博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 、可私信6博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值