目 录CONTENT

文章目录

集成mybatis-plus

ByteNews
2020-01-15 / 0 评论 / 1 点赞 / 30,388 阅读 / 8,097 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-01-15,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

02_集成MP


创建测试表

/*
Navicat MySQL Data Transfer

Source Server         : tom
Source Server Version : 50525
Source Host           : localhost:3306
Source Database       : mp-test

Target Server Type    : MYSQL
Target Server Version : 50525
File Encoding         : 65001

Date: 2019-06-08 14:36:59
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for tbl_employee
-- ----------------------------
DROP TABLE IF EXISTS `tbl_employee`;
CREATE TABLE `tbl_employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `last_name` varchar(50) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `gender` char(1) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tbl_employee
-- ----------------------------
INSERT INTO `tbl_employee` VALUES ('1', 'Tom', 'tom@tomxwd.top', '1', '22');
INSERT INTO `tbl_employee` VALUES ('2', 'Jerry', 'jerry@tomxwd.top', '0', '25');
INSERT INTO `tbl_employee` VALUES ('3', 'Black', 'black@tomxwd.top', '1', '30');
INSERT INTO `tbl_employee` VALUES ('4', 'White', 'white@tomxwd.top', '0', '35');

创建javaBean

public class Employee {

	private Integer id;
	private String lastName;
	private String email;
	private Integer gender;
	private Integer age;
	@Override
	public String toString() {
		return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + ", age="
				+ age + "]";
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public Integer getGender() {
		return gender;
	}
	public void setGender(Integer gender) {
		this.gender = gender;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}

}

需要注意的是,在定义javabean的时候,成员变量使用的类型:建议使用包装类型,因为基本类型由默认值。

  • int ==> 0
  • boolean ==> false

如果有默认值,那么就不会有null值出现。


依赖配置

  1. 在pom.xml文件中加入对MP、Spring、连接池、Junit、Mysql驱动等依赖。
<dependencies>
  <!-- MP -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>2.3</version>
</dependency>
<!-- Junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.9</version>
    <scope>test</scope>
</dependency>
<!-- mysql -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.37</version>
</dependency>
<!-- log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<!-- c3p0连接池 -->
<dependency>
    <groupId>com.mchange</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.5.2</version>
</dependency>
  <!-- spring相关 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.10.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>4.3.10.RELEASE</version>
</dependency>
</dependencies>

可以发现没有加入Mybatis以及Mybatis-Spring桥梁包的信息,因为Mybatis-Plus插件会自动维护。
2. 搭建Mybatis以及Spring相关的环境


首先创建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>
</configuration>

由于要迁移到spring中,所以mybatis的配置文件这里是为空的。
3. log4j.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
	<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
		<param name="Encoding" value="UTF-8" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L)\n"/>
		</layout>
	</appender>
	<logger name="java.sql">
		<level value="debug" />
	</logger>
	<logger name="org.apache.ibatis">
		<level value="info" />
	</logger>

	<root>
		<level value="debug"/>
		<appender-ref ref="STDOUT"/>
	</root>
</log4j:configuration>
  1. db.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mp-test
jdbc.username=root
jdbc.password=root
  1. spring配置文件(applicationContext.xml)
<?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:tx="http://www.springframework.org/schema/tx"
    xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
    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-4.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://mybatis.org/schema/mybatis-spring
        http://mybatis.org/schema/mybatis-spring-1.2.xsd"
        >
    <!-- 数据源 -->
    <context:property-placeholder location="classpath:db.properties"/>
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    	<property name="driverClass" value="${jdbc.driver}"></property>
    	<property name="jdbcUrl" value="${jdbc.url}"></property>
    	<property name="user" value="${jdbc.username}"></property>
    	<property name="password" value="${jdbc.password}"></property>
    </bean>
    <!-- 事务管理器 -->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    	<property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 基于注解的事务管理 -->
    <tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
    <!-- 配置SqlSessionFactoryBean -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
    	<!-- 数据源 -->
    	<property name="dataSource" ref="dataSource"></property>
    	<property name="configLocation" value="classpath:mybatis-config.xml"></property>
    	<!-- 别名处理 -->
    	<property name="typeAliasesPackage" value="top.tomxwd.mp.beans"></property>
    </bean>
    <!-- 配置mybatis 扫描mapper接口的路径 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    	<property name="basePackage" value="top.tomxwd.mp.mapper"></property>
    </bean>
</beans>

测试

public class TestMP {

	private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");

	@Test
	public void testDataSource() throws SQLException {
		DataSource ds = ioc.getBean("dataSource",DataSource.class);
		System.out.println(ds);
		Connection conn = ds.getConnection();
		System.out.println(conn);
	}

}

测试是否能够拿到DataSource,如果能够get到Connection,则说明成功。


集成MP

Mybatis-Plus的集成非常简单,对于Spring,我们仅仅需要把Mybatis自带的MybatisSqlSessionFactoryBean替换为MP自带的即可。

<!-- 配置MybatisSqlSessionFactoryBean -->
<bean id="sqlSessionFactoryBean" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
  <!-- 数据源 -->
  <property name="dataSource" ref="dataSource"></property>
  <property name="configLocation" value="classpath:mybatis-config.xml"></property>
  <!-- 别名处理 -->
  <property name="typeAliasesPackage" value="top.tomxwd.mp.beans"></property>
</bean>
1

评论区