欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot和Maven 整合Mybatis项目

程序员文章站 2022-03-02 15:29:12
...

Mybatis 原理和流程

运行原理:

        1. 创建会话工厂SqlSessionFactory,跟进配置文件创建。

        2. SqlSessionFactory创建SqlSession。

        3. SqlSession操作数据库(发出sql增、删、改、查)

        4. Mybatis在内部整合Sql语句(拼接等),输入参数、输出类型,

        5. 最后关闭SqlSession。

Spring与Mybatis整合后,上面的SqlSessionFactory和SqlSession都直接在Spring的bean中配置。

1. 添加依赖,spring boot统一进行了版本管理,并整合了日志的依赖等。

    在添加dbcp时,需要最新版本,否则会报错,亲测。spring boot没有整合dbcp, springboot用的自己的配置文件application.properties

    错误为:java.lang.IllegalAccessError: org.apache.commons.dbcp.DelegatingPreparedStatement.isClosed()Z

    能查询到结果,但不能返回数据。只需更新dbcp版本就可以。


打开pom.xml,在Dependencies标签查看的依赖:

Spring Boot和Maven 整合Mybatis项目

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.plin</groupId>
	<artifactId>springMvcMybatis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springMvcMybatis</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.1.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		
		<dependency>  
            <groupId>junit</groupId>  
            <artifactId>junit</artifactId>  
            <version>4.11</version>  
            <!-- 表示开发的时候引入,发布的时候不会加载此包 -->  
            <scope>test</scope>  
        </dependency>  
		
		 <!-- 导入Mysql数据库链接jar包 -->  
        <dependency>  
            <groupId>mysql</groupId>  
            <artifactId>mysql-connector-java</artifactId>  
        </dependency> 
        
		<dependency>  
         	<groupId>commons-dbcp</groupId>
    		<artifactId>commons-dbcp</artifactId>
    		<version>1.4</version>
        </dependency>  
        
		<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
		<dependency>
		    <groupId>org.apache.commons</groupId>
		    <artifactId>commons-pool2</artifactId>
		    <version>2.4.2</version>
		</dependency>
       
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

2. 项目结构

Spring Boot和Maven 整合Mybatis项目

3. 配置文件, 

        spring配置mybatis就是两个,加载sqlSession 和Mapper映射的。

        mybatis的配置的也是两个:SqlMapConfig.xml和XXXmapper.xml,mapper.xml会有很多,会根据业务来添加,主要配置sql语句和操作数据库接口(类似Dao)。

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123456

log4j.properties

# Global logging configuration

log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

SqlMapConfig.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>
	<!-- 别名定义 -->
	<typeAliases>
	<!-- 批量别名定义 
		指定包名,mybatis自动扫描包中的po类,自动定义别名,别名就是类名(首字母大写或小写都可以)
		-->
		<package name="com.plin.ssm.po"/>		
	</typeAliases>		
	<!-- 加载 映射文件
	和spring整合后,使用mapper扫描器,这里不需要配置了
	遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录 中
	 -->
	<mappers>
	    <package name="com.plin.ssm.mapper"/>
	</mappers>
</configuration>

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
	
    <!-- 加载配置文件 -->
	<context:property-placeholder location="classpath:db.properties" />
	
	<!-- 数据源,使用dbcp -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="maxActive" value="10" />
		<property name="maxIdle" value="5" />
	</bean>
	
	<!-- sqlSessinFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 加载mybatis的配置文件 -->
		<property name="configLocation" value="mybatis/SqlMapConfig.xml" />
		<!-- 数据源 -->
		<property name="dataSource" ref="dataSource" />
	</bean>
	
	<!-- mapper配置 
	MapperFactoryBean:根据mapper接口生成代理对象
	-->
	<!-- 	mapperInterface指定mapper接口 -->      
        <!-- <bean id="itemsMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		<property name="mapperInterface" value="com.plin.ssm.mapper.ItemsMapper"/>
		<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
	</bean> -->
		<!-- 指定扫描的包名 
		如果扫描多个包,每个包中间使用半角逗号分隔
		-->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">    
		<property name="basePackage" value="com.plin.ssm.mapper"/>
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>		
	</bean>    
</beans>

4. java代码

Items.java

package com.plin.ssm.po;

import java.util.Date;

public class Items {
    private Integer items_id;

    private String items_name;

    private Float items_price;

    private String items_pic;

    private Date items_createtime;

    private String items_detail;

	public Integer getItems_id() {
		return items_id;
	}

	public void setItems_id(Integer items_id) {
		this.items_id = items_id;
	}

	public String getItems_name() {
		return items_name;
	}

	public void setItems_name(String items_name) {
		this.items_name = items_name;
	}

	public Float getItems_price() {
		return items_price;
	}

	public void setItems_price(Float items_price) {
		this.items_price = items_price;
	}

	public String getItems_pic() {
		return items_pic;
	}

	public void setItems_pic(String items_pic) {
		this.items_pic = items_pic;
	}

	public Date getItems_createtime() {
		return items_createtime;
	}

	public void setItems_createtime(Date items_createtime) {
		this.items_createtime = items_createtime;
	}

	public String getItems_detail() {
		return items_detail;
	}

	public void setItems_detail(String items_detail) {
		this.items_detail = items_detail;
	}

	@Override
	public String toString() {
		return "Items [items_id=" + items_id + ", items_name=" + items_name
				+ ", items_price=" + items_price + ", items_pic=" + items_pic
				+ ", items_createtime=" + items_createtime + ", items_detail="
				+ items_detail + "]";
	}
      
}

ItemsMapper.java

package com.plin.ssm.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.plin.ssm.po.Items;

public interface ItemsMapper {

    int deleteByPrimaryKey(Integer items_id);

    int insert(Items record);

    int insertSelective(Items record);

    Items selectByPrimaryKey(int items_id);

    int updateByPrimaryKeySelective(Items record);

    int updateByPrimaryKeyWithBLOBs(Items record);

    int updateByPrimaryKey(Items record);
}
ItemsMapper.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">

<!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离 
注意:使用mapper代理方法开发,namespace有特殊重要的作用,namespace等于mapper接口地址
-->
<mapper namespace="com.plin.ssm.mapper.ItemsMapper">
	<select id="selectByPrimaryKey" parameterType="int" resultType="items">
		SELECT * FROM items WHERE items_id=#{value}
	</select>
		
	<insert id="insert" parameterType="Items">
		<!-- selectKey将主键返回,需要再返回 -->
		<selectKey keyProperty="items_id" order="AFTER" resultType="java.lang.Integer">
			select LAST_INSERT_ID()
		</selectKey>
		INSERT INTO `mybatis`.`items` (`items_name`, `items_price`, `items_detail`, `items_createtime`) 
		VALUES (#{items_name}, #{items_price}, #{items_detail}, #{items_createtime});
	</insert>	
</mapper>

5. 测试

测试代码

package com.plin.ssm.mapper;

import java.util.Date;

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

import com.plin.ssm.po.Items;

public class ItemsMapperTest {
	private ApplicationContext applicationContext;
	
	
	@Before
	public void setUp() throws Exception {
		
	}


	@Test
	public void testSelectByPrimaryKey() {
		applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
		ItemsMapper itemsMapper = (ItemsMapper) applicationContext.getBean("itemsMapper");
		Items items = itemsMapper.selectByPrimaryKey(1);
		System.out.println(items);
	}
	
	
	@Test
	public void testInsert() {
		applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
		ItemsMapper itemsMapper = (ItemsMapper) applicationContext.getBean("itemsMapper");
		Items items = new Items();
		items.setItems_name("苹果");
		items.setItems_price(34F);
		items.setItems_detail("真甜");
		items.setItems_createtime(new Date());
		int lastInsertedId= itemsMapper.insert(items);
		System.out.println(lastInsertedId);
	}	
}

6. 测试结果

testSelectByPrimaryKey测试结果:

Spring Boot和Maven 整合Mybatis项目

testInsert测试结果:

Spring Boot和Maven 整合Mybatis项目