1、建库建表
CREATE DATABASE `mybatis-example`;USE `mybatis-example`;CREATE TABLE `t_emp`(emp_id INT AUTO_INCREMENT,emp_name CHAR(100),emp_salary DOUBLE(10,5),PRIMARY KEY(emp_id)
);INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("tom",200.33);
INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("jerry",666.66);
INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("andy",777.77);
2、pom.xml
<dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId></dependency><!-- MySQL驱动 mybatis底层依赖jdbc驱动实现,本次不需要导入连接池,mybatis自带! --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!--junit5测试--><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies>
3、Employee.java(pojo)
package com.atguigu.mybatis.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {private Integer empId;private String empName;private Double empSalary;
}
4、EmpMapper.java
package com.atguigu.mybatis.mapper;
import com.atguigu.mybatis.pojo.Employee;
import org.apache.ibatis.annotations.Param;public interface EmpMapper {void addEmp(Employee employee);void addEmp2(@Param("ename") String ename, @Param("esalary") Double esalary);}
5、mybatis-config.xml(mybatis的总配置文件)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!-- environments表示配置Mybatis的开发环境,可以配置多个环境,在众多具体环境中,使用default属性指定实际运行时使用的环境。default属性的取值是environment标签的id属性的值。 --><environments default="development"><!-- environment表示配置Mybatis的一个具体的环境 --><environment id="development"><!-- Mybatis的内置的事务管理器 --><transactionManager type="JDBC"/><!-- 配置数据源 --><dataSource type="POOLED"><!-- 建立数据库连接的具体信息 --><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/mybatis-example"/><property name="username" value="root"/><property name="password" value="123456"/></dataSource></environment></environments><mappers><!-- Mapper注册:指定Mybatis映射文件的具体位置 --><!-- mapper标签:配置一个具体的Mapper映射文件 --><!-- resource属性:指定Mapper映射文件的实际存储位置,这里需要使用一个以类路径根目录为基准的相对路径 --><!-- 对Maven工程的目录结构来说,resources目录下的内容会直接放入类路径,所以这里我们可以以resources目录为基准 --><mapper resource="mapper/EmpMapper.xml"/></mappers></configuration>
6、EmpMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace等于mapper接口类的全限定名,这样实现对应 -->
<mapper namespace="com.atguigu.mybatis.mapper.EmpMapper"><!--演示数据类型--><!--单个实体类型作为输入参数--><insert id="addEmp"><!--此处的empName和empSalary不能随便写,必须是参数中的属性名称-->insert into t_emp values(0,#{empName},#{empSalary})<!--Preparing: insert into t_emp values(0,?,?)--></insert><!--零散的参数--><insert id="addEmp2">insert into t_emp values(0,#{ename},#{esalary})<!--insert into t_emp values(0,#{arg0},#{arg1})--><!--insert into t_emp values(0,#{param1},#{param2})--></insert>
</mapper>
7、MybatisTest3.java
package com.atguigu.mybatis;
import com.atguigu.mybatis.mapper.EmpMapper;
import com.atguigu.mybatis.pojo.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
public class MybatisTest3 {SqlSessionFactory sqlSessionFactory;SqlSession sqlSession;EmpMapper empMapper;@BeforeEachpublic void setup() throws IOException {// 获取资源流,读取"mybatis-config.xml"文件InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");// 使用资源流创建SqlSessionFactorysqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);// 使用SqlSessionFactory打开一个SessionsqlSession = sqlSessionFactory.openSession();// 使用Session获取EmpMapper的Mapper对象empMapper = sqlSession.getMapper(EmpMapper.class);}// 在每个测试用例之后执行的清理方法@AfterEachpublic void teardown() {sqlSession.commit(); // 提交事务sqlSession.close(); // 关闭SqlSession}@Testpublic void addEmpTest() {Employee employee = new Employee(0, "鸠摩智", 8080.0);empMapper.addEmp(employee);}@Testpublic void addEmpTest2() {empMapper.addEmp2("张无忌",999.9);}
}
D:\Java\jdk-17\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\lib\idea_rt.jar=57332:D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\bin" -Dfile.encoding=UTF-8 -classpath "D:\develop\maven\repository\org\junit\platform\junit-platform-launcher\1.3.1\junit-platform-launcher-1.3.1.jar;D:\develop\maven\repository\org\apiguardian\apiguardian-api\1.0.0\apiguardian-api-1.0.0.jar;D:\develop\maven\repository\org\junit\platform\junit-platform-engine\1.3.1\junit-platform-engine-1.3.1.jar;D:\develop\maven\repository\org\junit\platform\junit-platform-commons\1.3.1\junit-platform-commons-1.3.1.jar;D:\develop\maven\repository\org\opentest4j\opentest4j\1.1.1\opentest4j-1.1.1.jar;D:\develop\maven\repository\org\junit\jupiter\junit-jupiter-engine\5.3.1\junit-jupiter-engine-5.3.1.jar;D:\develop\maven\repository\org\junit\jupiter\junit-jupiter-api\5.3.1\junit-jupiter-api-5.3.1.jar;D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\lib\idea_rt.jar;D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\plugins\junit\lib\junit5-rt.jar;D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\plugins\junit\lib\junit-rt.jar;F:\IdeaProjects\workspace\pro-ssm\pro18-mybatis-begin\target\test-classes;F:\IdeaProjects\workspace\pro-ssm\pro18-mybatis-begin\target\classes;F:\my_java\maven_repository\org\mybatis\mybatis\3.5.11\mybatis-3.5.11.jar;F:\my_java\maven_repository\mysql\mysql-connector-java\8.0.25\mysql-connector-java-8.0.25.jar;F:\my_java\maven_repository\com\google\protobuf\protobuf-java\3.11.4\protobuf-java-3.11.4.jar;F:\my_java\maven_repository\org\junit\jupiter\junit-jupiter-api\5.3.1\junit-jupiter-api-5.3.1.jar;F:\my_java\maven_repository\org\apiguardian\apiguardian-api\1.0.0\apiguardian-api-1.0.0.jar;F:\my_java\maven_repository\org\opentest4j\opentest4j\1.1.1\opentest4j-1.1.1.jar;F:\my_java\maven_repository\org\junit\platform\junit-platform-commons\1.3.1\junit-platform-commons-1.3.1.jar;F:\my_java\maven_repository\org\projectlombok\lombok\1.18.20\lombok-1.18.20.jar;F:\my_java\maven_repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;F:\my_java\maven_repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;F:\my_java\maven_repository\org\slf4j\slf4j-api\1.7.25\slf4j-api-1.7.25.jar" com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit5 com.atguigu.mybatis.MybatisTest3,addEmpTest2
11:39:57,274 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml]
11:39:57,274 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]
11:39:57,274 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback.xml] at [file:/F:/IdeaProjects/workspace/pro-ssm/pro18-mybatis-begin/target/classes/logback.xml]
11:39:57,360 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
11:39:57,363 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [STDOUT]
11:39:57,369 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
11:39:57,393 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to DEBUG
11:39:57,394 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDOUT] to Logger[ROOT]
11:39:57,395 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [com.atguigu.mybatis] to DEBUG
11:39:57,395 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
11:39:57,396 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@62230c58 - Registering current configuration as safe fallback point
[11:39:57.401] [DEBUG] [main] [org.apache.ibatis.logging.LogFactory] [Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.]
[11:39:57.415] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [PooledDataSource forcefully closed/removed all connections.]
[11:39:57.415] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [PooledDataSource forcefully closed/removed all connections.]
[11:39:57.415] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [PooledDataSource forcefully closed/removed all connections.]
[11:39:57.415] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [PooledDataSource forcefully closed/removed all connections.]
[11:39:57.483] [DEBUG] [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction] [Opening JDBC Connection]
[11:39:58.035] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [Created connection 694069884.]
[11:39:58.035] [DEBUG] [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction] [Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@295eaa7c]]
[11:39:58.040] [DEBUG] [main] [com.atguigu.mybatis.mapper.EmpMapper.addEmp2] [==> Preparing: insert into t_emp values(0,?,?)]
[11:39:58.099] [DEBUG] [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction] [Committing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@295eaa7c]]
[11:39:58.100] [DEBUG] [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction] [Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@295eaa7c]]
[11:39:58.101] [DEBUG] [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction] [Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@295eaa7c]]
[11:39:58.101] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [Returned connection 694069884 to pool.]org.apache.ibatis.exceptions.PersistenceException:
### Error updating database. Cause: org.apache.ibatis.binding.BindingException: Parameter 'ename' not found. Available parameters are [arg1, arg0, param1, param2]
### The error may exist in mapper/EmpMapper.xml
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: insert into t_emp values(0,?,?)
### Cause: org.apache.ibatis.binding.BindingException: Parameter 'ename' not found. Available parameters are [arg1, arg0, param1, param2]at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:196)at org.apache.ibatis.session.defaults.DefaultSqlSession.insert(DefaultSqlSession.java:181)at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:62)at org.apache.ibatis.binding.MapperProxy$PlainMethodInvoker.invoke(MapperProxy.java:145)at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:86)at jdk.proxy2/jdk.proxy2.$Proxy10.addEmp2(Unknown Source)at com.atguigu.mybatis.MybatisTest3.addEmpTest2(MybatisTest3.java:45)at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.base/java.lang.reflect.Method.invoke(Method.java:568)at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:515)at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:171)at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:167)at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:114)at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:59)at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:105)at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:95)at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:71)at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:110)at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:95)at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:71)at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:110)at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:95)at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:71)at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:232)at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55)
Caused by: org.apache.ibatis.binding.BindingException: Parameter 'ename' not found. Available parameters are [arg1, arg0, param1, param2]at org.apache.ibatis.binding.MapperMethod$ParamMap.get(MapperMethod.java:212)at org.apache.ibatis.reflection.wrapper.MapWrapper.get(MapWrapper.java:45)at org.apache.ibatis.reflection.MetaObject.getValue(MetaObject.java:122)at org.apache.ibatis.scripting.defaults.DefaultParameterHandler.setParameters(DefaultParameterHandler.java:79)at org.apache.ibatis.executor.statement.PreparedStatementHandler.parameterize(PreparedStatementHandler.java:94)at org.apache.ibatis.executor.statement.RoutingStatementHandler.parameterize(RoutingStatementHandler.java:64)at org.apache.ibatis.executor.SimpleExecutor.prepareStatement(SimpleExecutor.java:88)at org.apache.ibatis.executor.SimpleExecutor.doUpdate(SimpleExecutor.java:49)at org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:117)at org.apache.ibatis.executor.CachingExecutor.update(CachingExecutor.java:76)at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:194)... 47 moreProcess finished with exit code -1