mybatis架构
1. 导包
2. 写 mybatis-config.xml 配置
3. 编写工具类
4. 编写实体类
5. 写mapper接口
6. 写mapper.xml
7. 测试
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
这个xml配置直接从官方文档里面拷贝。mybatis官网。入门里面就有
<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED"><!-- 下面就是连接数据库了-->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--每一个mapper.xml都需要在mybatis核心配置文件中注册!-->
<mappers>
<mapper resource="fang/mapper/UserMapper.xml"/>
<!-- 这里需要指定你自己的UserMapper.xml路径,这里还没写,这么放会有一个maven资源导出问题。末尾有贴解决方法。
也可以放在resources目录里面-->
</mappers>
</configuration>
mybatis-config.xml
写完需要有个工具类去读取配置。写一个工具类,里面主要的就是这三行代码。这个工具类是方便我们每次使用的时候直接调用
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
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;
/**
* MyBatis工具类
* @author Bernie_xin
* @create 2020/7/31 20:25
**/
public class MybatisUtils {
private static String resource = null;
private static InputStream inputStream = null;
private static SqlSessionFactory sqlSessionFactory = null;
static{
try {
resource = "mybatis-config.xml";
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
实体类需要跟数据库的实体类字段对应,这个就不展示了。但是记得遵守JavaBean
的写法,有get/set,全参、无参以及toString
mapper接口把全部需要的方法都定义上去。如
public interface UserMapper {
User queryUserById(int id);
List<User> selectUser();
int add(User user);
int update(User user);
int delete(int id);
List<User> queryUserByName(String name);//这个实现模糊查询
}
mapper.xml
就和我们以前写的dao的实现类一个作用,但是用mapper.xml
会更方便,SQL的定制化程度会更高!
<?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">
<mapper namespace="fang.mapper.UserMapper">
<select id="queryUserById" resultType="fang.pojo.User">
select * from users where id = #{id}
</select>
<select id="queryUserByName" resultType="fang.pojo.User" parameterType="String">
select * from users where name like "%"#{name}"%"
</select>
<select id="selectUser" resultType="fang.pojo.User">
select * from users
</select>
<insert id="add" parameterType="fang.pojo.User">
insert into users (id, name , password) values (#{id}, #{name}, #{password})
</insert>
<update id="update" parameterType="fang.pojo.User">
update users set name=#{name}, password=#{password} where id=#{id}
</update>
<delete id="delete" parameterType="int">
delete from users where id=#{id}
</delete>
</mapper>
mapper.xml
需要注意的是:
1、 namespace
要绑定你的mapper接口的路径,否则会报错。
2、 标签要对应sql,查询对应select
标签,修改对应update
…
3、 id对应mapper接口
的方法名字
4、 parameterType
是参数类型,如果是类,要写全路径,否则报找不到错
5、 resultType
是返回结果类型,如果是类,也要写全路径
6、 sql的限定条件如上所述加载
7、模糊查询为防止sql注入,可如第二句一样,把sql写死,既条件前后加通配符
测试相对容易,使用我们导入的junit
进行测试
建议在maven的test里面建与源代码一样路径的类,在类名加test
,方法名字对应相应的方法,如我自己的习惯:
@Test
public void testSelectUser(){//这是测试selectUser
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.selectUser();
for (User user:users){
System.out.println(user.toString());
}
sqlSession.close();
}
测试方法里面,第一二句和最后一句都是固定写法。中间是查询打印,如果能在控制台打印出你数据库的东西,那测试就成功了!
最后呢,就上面提到的一个错误。报错Could not find resource fang/mapper/UserMapper.xml
,明明你已经写了,路径也没错,但就是没有。报错信息如下。
java.lang.ExceptionInInitializerError
at fang.mapper.UserMapperTest.test(UserMapperTest.java:18)
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:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: org.apache.ibatis.exceptions.PersistenceException:
### Error building SqlSession.
### The error may exist in fang/mapper/UserMapper.xml
### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource fang/mapper/UserMapper.xml
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:80)
at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:64)
at fang.utils.MybatisUtils.<clinit>(MybatisUtils.java:26)
... 26 more
Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource fang/mapper/UserMapper.xml
at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:122)
at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:99)
at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:78)
... 28 more
Caused by: java.io.IOException: Could not find resource fang/mapper/UserMapper.xml
at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:114)
at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:100)
at org.apache.ibatis.builder.xml.XMLConfigBuilder.mapperElement(XMLConfigBuilder.java:374)
at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:120)
... 30 more
这个其实是maven的过滤问题,不是在resources下的配置,导出默认是关闭的,我们需要手动开启。
在pom.xml
插入如下代码。
<!--在Build里面配置resource,防止导入资源失败-->
<!--<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>-->
学习记录到这结束!喜欢请点个赞。