Spring integration MybatisPlus, as well as some of the problems encountered

I. Introduction

1. This is simply the integration of Spring and MybatisPlus, and made the most simple test
2. To integrate Spring and MybatisPlus, first of all to familiar with the Spring Framework
3. Use maven project build tools

Second, step

1. Create project is omitted, show how simple directory structure. . .
Here Insert Picture Description
2. First add dependencies in the pom file

<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>
		</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>
		<!-- mysql驱动 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.6</version>
		</dependency>
		<!-- spring相关 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.2.4.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>4.2.4.RELEASE</version>
		</dependency>
	</dependencies>

3. learned mybatis should know, mybatis there is a global configuration file, but does not require integration with Spring inside after adding content, but we generally have reservations. Build a resource directory in mybatis-config.xmlthe xml file

<?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>

Under 4.resource Spring catalog to build a core file applicationContext.xmlthis xml file.

<?xml version="1.0" encoding="UTF-8"?>
<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" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
       xmlns="http://www.springframework.org/schema/beans" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
       xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd">
    <!--引入properties配置文件-->
    <context:property-placeholder location="classpath:db.properties" />
    <!--配置数据源,使用C3p0连接池-->
    <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"/>
    <!--整合Mybatis-->
    <!--Spring一启动就会创建sqlSessionFactory对象-->
    <!-- 
    	mybatis提供的:org.mybatis.spring.SqlSessionFactoryBean
    	mybatisPlus 提供的:com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean  -->
    <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!--配置mybatis的全局配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    </bean>

Build a directory under 5.resource db.proertiesthe properties file

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_mybatis_plus?characterEncoding=utf-8
jdbc.username=root
jdbc.password=自己数据的密码

6. In order to facilitate testing us, add a log file. build a resource directory under log4j.xmlthis xml file

<?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>

7. As to the test, we must prepare the database tables and entity classes
(1) a database table, use the mysql database, create a new database and tables and add a few data.

CREATE DATABASE db_mybatis_plus;
USE db_mybatis_plus;
CREATE TABLE tbl_employee(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
last_name VARCHAR(50), email VARCHAR(50),
gender INT(1), age INT
);
INSERT INTO tbl_employee(last_name,email,gender,age) VALUES('Tom','[email protected]',1,22); 
INSERT INTO tbl_employee(last_name,email,gender,age) VALUES('Jerry','[email protected]',0,25); 
INSERT INTO tbl_employee(last_name,email,gender,age) VALUES('rose','[email protected]',1,30); 
INSERT INTO tbl_employee(last_name,email,gender,age) VALUES('jack','[email protected]',0,35);

(2) Java entity classes, fields of the database table.

	private Integer id;

	private String lastName;

	private String email;
	
	private Integer gender;

	private Integer age;
	//无参构造
	//有参构造
	//getter和setter方法
	//toString 方法
	//太占地了,我就省略l,但是你不要省略,特别的setter和getter方法。
	

(3) create a mapper interfaces, inheritance MybatisPlus mention provided BaseMapper interfaces, generic entity class object
EmployeeMapper

public interface EmployeeMapper extends BaseMapper<Employee>{

}

Do not worry, come Photo
Here Insert Picture Description

Third, the test

1. First test the database connection is not successful

//获取Spring容器
private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
	private EmployeeMapper employeeMapper = ioc.getBean("employeeMapper",EmployeeMapper.class);

Write a test method

@Test
	public void testMp() throws SQLException {
		DataSource dataSource = ioc.getBean("dataSource",DataSource.class);
		System.out.println(dataSource);
		Connection connection = dataSource.getConnection();
		System.out.println(connection);
		connection.close();

	}

To Zhang map, no error, no problem with the configuration Probably a
Here Insert Picture Description
log effect
Here Insert Picture Description
2. insert a test insertion method to use, of course, so most probably will complain directly to the test
Here Insert Picture Description
3. error message

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: Could not set property 'id' of 'class com.atguigu.mp.beans.Employee' with value '1237661424084324353' Cause: java.lang.IllegalArgumentException: argument type mismatch

4. Solution, add annotations on the id property of an entity type, is a self-declared primary key growth strategy

@TableId(type = IdType.AUTO)

Here Insert Picture Description
5. Run will once again throw an exception

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mp.employee' doesn't exist

Solution, in which the entity classes annotated class name, entity class declaration corresponds to a database table (they are inconsistent with the entity class and table names, if this has not throw an exception)

@TableName(value = "tbl_employee")

The two exceptions, of course, there's an easier solution, not to mention here the
Here Insert Picture Description
6. On the run, this will be successful, it returns a value of 1, and print out the SQL statement
Here Insert Picture Descriptionyou're done

Writing is not easy, if helpful to you, please give a little praise, your thumbs for me great support and encouragement, thank you! ! !

Published 10 original articles · won praise 4 · Views 435

Guess you like

Origin blog.csdn.net/qq_44719527/article/details/104798849