环境准备
数据库准备
USE mybatis;
# 创建一个名称为tb_worker的表
CREATE TABLE tb_worker(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(32),
age INT,
sex VARCHAR(8),
worker_id INT UNIQUE
);
# 插入2条数据
INSERT INTO tb_worker(name,age,sex,worker_id)VALUES('张三',32,'女',1001);
INSERT INTO tb_worker(name,age,sex,worker_id)VALUES('李四',29,'男',1002);
INSERT INTO tb_worker(name,age,sex,worker_id)VALUES('王五',26,'男',1003);
Idea基础环境
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.biem</groupId>
<artifactId>mybatis6</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.18</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
com.biem.pojo.Worker.java
package com.biem.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Data
//@Data : 注在类上,提供类的get、set、equals、hashCode、canEqual、toString方法
@NoArgsConstructor
@AllArgsConstructor
public class Worker {
private Integer id;
private String name;
private Integer age;
private String sex;
private Integer workerId;
}
com.biem.mapper.WorkerMapper.java
package com.biem.mapper;
public interface WorkerMapper {
}
com.biem.util.MyBatisUtil.java
package com.biem.util;
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 java.io.IOException;
import java.io.InputStream;
public class MyBatisUtil {
//利用static(静态)属于类不属于对象,且全局唯一
private static SqlSessionFactory sqlSessionFactory = null;
private static final Class<Object> Resources = ;
//利用静态块在初始化类时实例化sqlSessionFactory
static {
InputStream is= null;
try {
is = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
}
/**
* openSession 创建一个新的SqlSession对象
* @return SqlSession对象
*/
public static SqlSession openSession(boolean autoCommit){
return sqlSessionFactory.openSession(autoCommit);
}
public static SqlSession openSession(){
return sqlSessionFactory.openSession();
}
/**
* 释放一个有效的SqlSession对象
* @param session 准备释放SqlSession对象
*/
public static void closeSession(SqlSession session){
if(session != null){
session.close();
}
}
}
package com.biem.test;
public class WorkerTest {
}
db.properties
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
mysql.username=root
mysql.password=123
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>
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>
<!--引入properties文件-->
<properties resource="db.properties"></properties>
<!--将下划线映射为驼峰-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!--设置类型别名-->
<typeAliases>
<package name="com.biem.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
</environments>
<!-- 引入映射文件 -->
<mappers>
<package name="com.biem.mapper"/>
</mappers>
</configuration>
常用注解
Select注解
com.biem.mapper.WorkerMapper.java下添加
@Select("select * from tb_worker where id=#{id}")
public Worker findWorkerById(Integer id);
com.biem.test.WorkerTest.java下添加
@Test
public void findWorkerById(){
SqlSession session = MyBatisUtil.openSession();
WorkerMapper mapper = session.getMapper(WorkerMapper.class);
System.out.println("mapper.findWorkerById(1) = " + mapper.findWorkerById(1));
session.close();
}
输出结果
Insert注解
com.biem.mapper.WorkerMapper.java下添加
@Insert("insert into tb_worker(name, age, sex, worker_id) values(#{name}, #{age}, #{sex}, #{workerId})")
public int insertWorker(Worker worker);
com.biem.test.WorkerTest.java下添加
@Test
public void inserWorker(){
SqlSession session = MyBatisUtil.openSession();
WorkerMapper mapper = session.getMapper(WorkerMapper.class);
Worker worker = new Worker();
worker.setName("王强");
worker.setAge(36);
worker.setSex("女");
worker.setWorkerId(1004);
int result = mapper.insertWorker(worker);
session.commit();
session.close();
}
输出结果
Update注解
com.biem.mapper.WorkerMapper.java下添加
@Update("update tb_worker set name=#{name},age=#{age} where id = #{id}")
public int updateWorker(Worker worker);
com.biem.test.WorkerTest.java下添加
@Test
public void updateWorker(){
SqlSession session = MyBatisUtil.openSession();
WorkerMapper mapper = session.getMapper(WorkerMapper.class);
Worker worker = new Worker();
worker.setId(4);
worker.setName("王冰");
worker.setAge(36);
int result = mapper.updateWorker(worker);
if(result>0){
System.out.println("更新了"+result+"条数据");
} else {
System.out.println("更新失败");
}
session.commit();
session.close();
}
输出结果
Delete注解
com.biem.mapper.WorkerMapper.java下添加
@Delete("delete from tb_worker where id=#{id}")
public int deleteWorkerById(Integer id);
com.biem.test.WorkerTest.java下添加
@Test
public void deleteWorkerById(){
SqlSession session = MyBatisUtil.openSession();
WorkerMapper mapper = session.getMapper(WorkerMapper.class);
int result = mapper.deleteWorkerById(4);
if(result>0){
System.out.println("删除了"+result+"条数据");
} else {
System.out.println("删除失败");
}
session.close();
}
测试结果
Param注解
com.biem.mapper.WorkerMapper.java下添加
//mybatis不能识别多个参数,所以多个参数会抛出,
//Cause: org.apache.ibatis.binding.BindingException: Parameter 'id' not found. Available parameters are [arg1, arg0, param1, param2]
@Select("select * from tb_worker where id=#{id} and name=#{name}")
public Worker findWorkerByIdAndName1(Integer id, String name);
@Select("select * from tb_worker where id=#{param1} and name=#{param2}")
public Worker findWorkerByIdAndName2(@Param("param1") Integer id, @Param("param2") String name);
@Select("select * from tb_worker where id=#{arg1} and name=#{arg0}")
public Worker findWorkerByIdAndName3(@Param("arg1") Integer id, @Param("arg0") String name);
@Test
public void findWorkerByIdAndName1(){
SqlSession session = MyBatisUtil.openSession();
WorkerMapper mapper = session.getMapper(WorkerMapper.class);
System.out.println("mapper.findWorkerByIdAndName1(1,\"张三\") = " + mapper.findWorkerByIdAndName1(1, "张三"));
session.close();
}
@Test
public void findWorkerByIdAndName2(){
SqlSession session = MyBatisUtil.openSession();
WorkerMapper mapper = session.getMapper(WorkerMapper.class);
System.out.println("mapper.findWorkerByIdAndName2(1,\"张三\") = " + mapper.findWorkerByIdAndName2(1, "张三"));
session.close();
}
@Test
public void findWorkerByIdAndName3(){
SqlSession session = MyBatisUtil.openSession();
WorkerMapper mapper = session.getMapper(WorkerMapper.class);
System.out.println("mapper.findWorkerByIdAndName3(1,\"张三\") = " + mapper.findWorkerByIdAndName3(1, "张三"));
session.close();
}
输出结果
"C:\Program Files\Java\jdk1.8.0_202\bin\java.exe" -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:D:\ssm\idea\IntelliJ IDEA Community Edition 2022.3.2\lib\idea_rt.jar=5199:D:\ssm\idea\IntelliJ IDEA Community Edition 2022.3.2\bin" -Dfile.encoding=UTF-8 -classpath "D:\ssm\idea\IntelliJ IDEA Community Edition 2022.3.2\lib\idea_rt.jar;D:\ssm\idea\IntelliJ IDEA Community Edition 2022.3.2\plugins\junit\lib\junit5-rt.jar;D:\ssm\idea\IntelliJ IDEA Community Edition 2022.3.2\plugins\junit\lib\junit-rt.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_202\jre\lib\rt.jar;D:\ssm\IdeaProjects\mybatis-3.5.6\annotaion\target\test-classes;D:\ssm\IdeaProjects\mybatis-3.5.6\annotaion\target\classes;D:\repository\org\mybatis\mybatis\3.4.6\mybatis-3.4.6.jar;D:\repository\junit\junit\4.12\junit-4.12.jar;D:\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;D:\repository\mysql\mysql-connector-java\8.0.18\mysql-connector-java-8.0.18.jar;D:\repository\com\google\protobuf\protobuf-java\3.6.1\protobuf-java-3.6.1.jar;D:\repository\log4j\log4j\1.2.12\log4j-1.2.12.jar;D:\repository\org\projectlombok\lombok\1.18.18\lombok-1.18.18.jar" com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 com.biem.test.WorkerTest,findWorkerByIdAndName1
org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.apache.ibatis.binding.BindingException: Parameter 'id' not found. Available parameters are [arg1, arg0, param1, param2]
### Cause: org.apache.ibatis.binding.BindingException: Parameter 'id' 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.selectList(DefaultSqlSession.java:150)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:77)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:83)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)
at com.sun.proxy.$Proxy9.findWorkerByIdAndName1(Unknown Source)
at com.biem.test.WorkerTest.findWorkerByIdAndName1(WorkerTest.java:64)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
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:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: org.apache.ibatis.binding.BindingException: Parameter 'id' not found. Available parameters are [arg1, arg0, param1, param2]
at org.apache.ibatis.binding.MapperMethod$ParamMap.get(MapperMethod.java:204)
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.executor.BaseExecutor.createCacheKey(BaseExecutor.java:219)
at org.apache.ibatis.executor.CachingExecutor.createCacheKey(CachingExecutor.java:146)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:82)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148)
... 30 more
Process finished with exit code -1
findWorkerByIdAndName2结果
findWorkerByIdAndName3结果