个人主页:BoBooY的CSDN博客_Java领域博主
前言:本篇文章总结了Mybatis的入门知识(上),希望能通过 文字+代码+截图 的方式帮助大家快速掌握
Mybatis入门知识(下):https://blog.csdn.net/qq_58233406/article/details/127112954
环境说明:
学习前需要掌握:
持久化是将程序数据在持久状态和瞬时状态间转换的机制。
为什么需要持久化服务呢?那是由于内存本身的缺陷引起的
什么是持久层?
Mybatis就是帮助程序猿将数据存入数据库中 , 和从数据库中取数据 .
传统的jdbc操作 , 有很多重复代码块 .比如 : 数据取出时的封装 , 数据库的建立连接等等… , 通过框架可以减少重复代码,提高开发效率 .
MyBatis 是一个半自动化的ORM框架 (Object Relationship Mapping) -->对象关系映射
所有的事情,不用Mybatis依旧可以做到,只是用了它,所有实现会更加简单!技术没有高低之分,只有使用这个技术的人有高低之别
MyBatis的优点
最重要的一点,使用的人多!公司需要!
思路流程:搭建环境–>导入Mybatis—>编写代码—>测试
CREATE DATABASE `Mybatis`;
use `Mybatis`;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(20) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`pwd` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE = InnoDB CHARACTER SET = utf8;
INSERT INTO `user` VALUES (1, '赵惟', 'zhaowei');
INSERT INTO `user` VALUES (2, '彭浩', 'penghao');
INSERT INTO `user` VALUES (3, '郝文虎', 'haowenhu');
注意更改Maven版本为3.6.1,不要使用IDEA自带的版本
mybatis、mysql、junit
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
dependencies>
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.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
mappers>
configuration>
package com.bby.utils;
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 MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//获取SqlSession
public static SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
package com.bby.pojo;
public class User {
private int id;
private String name;
private String pwd;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
package com.bby.Dao;
import com.bby.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> selectUser();
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bby.Dao.UserMapper">
<select id="selectUser" resultType="com.bby.pojo.User">
select * from User
select>
mapper>
<mappers>
<mapper resource="com/bby/Dao/UserMapper.xml"/>
mappers>
package com.bby.Dao;
import com.bby.pojo.User;
import com.bby.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
@Test
public void test() {
SqlSession sqlSession = MybatisUtils.getSession();
//方式一(推荐)
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.selectUser();
//方式二
List<User> users1 = sqlSession.selectList("com.bby.Dao.UserMapper.selectUser");
for(User user : users) {
System.out.println(user);
}
}
}
mybatis核心配置文件的mapper 中的资源路径必须使用 " / "
Maven没有在build中配置resource,导致资源读取不到,因为正常情况下,xml配置文件应该放在resources目录下,而Maven约定大于配置,所以可能读取不到
java.lang.ExceptionInInitializerError
at com.bby.Dao.UserMapperTest.test(UserMapperTest.java:13)
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.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:221)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: org.apache.ibatis.exceptions.PersistenceException:
### Error building SqlSession.
### The error may exist in com/bby/Dao/UserMapper.xml
### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/bby/Dao/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 com.bby.utils.MybatisUtils.(MybatisUtils.java:22)
... 23 more
Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/bby/Dao/UserMapper.xml
at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:121)
at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:98)
at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:78)
... 25 more
Caused by: java.io.IOException: Could not find resource com/bby/Dao/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:372)
at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:119)
... 27 more
进程已结束,退出代码为 -1
解决方式:
在父工程和子工程中都配置一下pom.xml文件:
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
java.lang.NullPointerException
insert、update、select、delete标签不要乱用,应该一一对应
添加selectUserById()方法
//根据id查询用户
User selectUserById(int id);
添加映射接口的查询语句
<select id="selectUserById" parameterType="int" resultType="com.bby.pojo.User">
select * from User where id = #{id}
select>
//测试通过id查询用户
@Test
public void test2() {
SqlSession sqlSession = MybatisUtils.getSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectUserById(1);
System.out.println(user);
}
//添加用户
int insertUser(User user);
<insert id="insertUser" parameterType="com.bby.pojo.User">
insert into user(`id`,`name`,`pwd`) values(#{id},#{name},#{pwd})
</insert>
//测试添加用户
@Test
public void test3() {
SqlSession sqlSession = MybatisUtils.getSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User(4,"张三","zhangsan");
int result = mapper.insertUser(user);
//提交事务
sqlSession.commit();
if(result > 0) {
System.out.println("添加成功");
} else {
System.out.println("添加失败");
}
//关闭资源
sqlSession.close();
}
//修改用户信息
int updateUser(User user);
<update id="updateUser" parameterType="com.bby.pojo.User">
update user set `name`=#{name},`pwd`=#{pwd} where `id`=#{id}
update>
//测试修改用户信息
@Test
public void test4() {
SqlSession sqlSession = MybatisUtils.getSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectUserById(4);
user.setPwd("123");
int result = mapper.updateUser(user);
//提交事务
sqlSession.commit();
if(result > 0) {
System.out.println("修改成功");
} else {
System.out.println("修改失败");
}
//关闭资源
sqlSession.close();
}
//删除用户
int deleteUser(int id);
<delete id="deleteUser" parameterType="int">
delete from user where `id`=#{id}
delete>
//测试删除用户
@Test
public void test5(){
SqlSession sqlSession = MybatisUtils.getSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int result = mapper.deleteUser(5);
//提交事务
sqlSession.commit();
if(result > 0) {
System.out.println("删除成功");
} else {
System.out.println("删除失败");
}
//释放资源
sqlSession.close();
}
mybatis-config.xml 系统核心配置文件
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。
能配置的内容如下:
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
我们可以阅读 mybatis-config.xml 上面的dtd的头文件!【演示】
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="..." value="..."/>
transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
dataSource>
environment>
environments>
配置MyBatis的多套运行环境,将SQL映射到多个不同的数据库上,必须指定其中一个为默认运行
环境(通过default指定)
子元素节点:environment
具体的一套环境,通过设置id进行区别,id保证唯一!
子元素节点:transactionManager - [ 事务管理器 ]
<transactionManager type="[ JDBC | MANAGED ]"/>
这两种事务管理器类型都不需要设置任何属性。
子元素节点:数据源(dataSource)
dataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。
数据源是必须配置的。
有三种内建的数据源类型
type="[UNPOOLED|POOLED|JNDI]")
数据库这些属性都是可外部配置且可动态替换的,既可以在典型的 Java 属性文件中配置,亦可通过properties 元素的子元素来传递。
第一步:在资源目录下新建一个db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8
username=root
password=1234
第二步:将文件导入properties 配置文件
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="db.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/bby/Dao/UserMapper.xml"/>
mappers>
configuration>
可以直接引入外部文件或者在核心配置文件中映入,如下:
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="pwd" value="11111"/>
properties>
可以在其中增加一些属性配置
如果两个文件有同一字段,优先使用外部配置文件的!
类型别名是为 Java 类型设置一个短的名字
它只和 XML 配置有关,存在的意义仅在于用来减少类完全限定名的冗余。
<typeAliases>
<typeAlias type="com.kuang.pojo.User" alias="User"/>
typeAliases>
也可以制定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:
扫描实体类的包,它的默认别名就为这个类的类名,首字母不区分大小写,例如:User / user
<typeAliases>
<package name="com.kuang.pojo"/>
typeAliases>
提示:在实体类比较少的时候,使用第一种方式
如果实体类特别多,建议使用第二种方式
第一种方式可以DIY别名,第二种则不行,如果非要改,需要在实体类上增加注解
import org.apache.ibatis.type.Alias;
@Alias("use")//记住这种方式需要两步,第一步在typeAliases中配置扫描包名,第二步在实体类上面使用注解
public class User {}
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25"/>
<setting name="defaultFetchSize" value="100"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
settings>
具体看官方文档:https://mybatis.org/mybatis-3/zh/configuration.html#settings
MapperRegistry:注册绑定我们的Mapper文件
<mappers>
<mapper resource="org/mybatis/builder/PostMapper.xml"/>
mappers>
<mappers>
<mapper url="file:///var/mappers/AuthorMapper.xml"/>
mappers>
这种方式是使用映射器接口实现类的完全限定类名
<mappers>
<mapper class="org.mybatis.builder.AuthorMapper"/>
mappers>
注意点:
这种方式可以将包内的映射器接口实现全部注册为映射器
<mappers>
<package name="org.mybatis.builder"/>
mappers>
注意点:
不同作用域和生命周期类是至关重要的,因为错误的使用会导致非常严重的并发问题。
以下是Mybatis的执行过程:
这里面的每一个Mapper,就代表一个具体的业务!
要解决的问题:属性名和字段名不一致
环境:新建一个项目,将之前的项目拷贝过来
1、查看之前的数据库的字段名
2、Java中的实体类设计
public class User {
private int id; //id
private String name; //姓名
private String password; //密码和数据库不一样!
//构造
//set/get
//toString()
}
3、接口
//根据id查询用户
User selectUserById(int id);
4、mapper映射文件
<select id="selectUserById" resultType="user">
select * from user where id = #{id}
select>
5、测试
@Test
public void testSelectUserById() {
SqlSession session = MybatisUtils.getSession(); //获取SqlSession连接
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.selectUserById(1);
System.out.println(user);
session.close();
}
结果:
分析:
select * from user where id = #{id} 可以看做
select id,name,pwd from user where id = #{id}
mybatis会根据这些查询的列名(会将列名转化为小写,数据库不区分大小写) , 去对应的实体类中查找相应列名的set方法设值 , 由于找不到setPwd() , 所以password返回null ; 【自动映射】
<select id="selectUserById" resultType="User">
select id , name , pwd as password from user where id = #{id}
select>
<resultMap id="UserMap" type="User">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
resultMap>
<select id="selectUserById" resultMap="UserMap">
select id , name , pwd from user where id = #{id}
select>
Mybatis入门知识(下):https://blog.csdn.net/qq_58233406/article/details/127112954
尾声:创作不易,如果本文的内容对您有帮助,还望客官可以三连支持一下博主,+✏️+⭐️是我创作的巨大动力!