【Mybatis】使用Mybatis实现插入数据到数据库
1.数据库表
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 DEFAULT CHARSET=utf8;
INSERT INTO `user`(`id`,`name`,`pwd`) VALUES (1,'张三','123456'),(2,'李四','abcdef');
2.新建maven工程
工程名Mybatis3,子模块mybatisdemo01
3.添加依赖
添加到子模块的pom.xml文件中
<dependencies>
<!-- Mybatis核心 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.3</version>
</dependency>
<!--单元测试-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.3.1</version>
</dependency>
</dependencies>
<!--静态资源过滤-->
<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>false</filtering>
</resource>
</resources>
</build>
3.创建Mybatis核心配置文件
主要用于配置连接数据库的环境以及Mybatis的全局配置信息,mybatis-config.xml,存放在src/main/resources目录下
<?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.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--引入映射文件-->
<mappers>
<mapper resource="com/pxk/mapper/userMapper.xml"/>
</mappers>
</configuration>
4.实体类
public class User {
private int id;
private String name;
private String pwd;
//get,set方法,有参无参构造,toString方法
}
5.Mapper接口
相当于DAO,仅为接口,不需要实现类
public interface UserMapper {
int insertUser(User user);
}
6.创建Mybatis映射文件
就是用来写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="com.pxk.mapper.UserMapper">
<insert id="insertUser" parameterType="com.pxk.pojo.User">
insert into user(id, name, pwd)
values (#{id}, #{name}, #{pwd})
</insert>
</mapper>
mybatis的核心配置文件中添加映射文件的路径
<!--引入映射文件-->
<mappers>
<mapper resource="mappers/userMapper.xml"/>
</mappers>
7.测试
import com.pxk.mapper.UserMapper;
import com.pxk.pojo.User;
import com.pxk.utils.MybatisUtils;
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.Test;
import java.io.IOException;
import java.io.InputStream;
public class TestUser {
@Test
public void test1() throws IOException {
//1.以字节输入流方式读取核心配置文件
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//2.创建sqlSessionFactoryBuilder对象,这个对象用来创建工厂
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//3.创建工厂,用来生产sqlSession
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//4.获取sqlSession,sqlSession表示Java程序和数据库之间的会话
SqlSession sqlSession = sqlSessionFactory.openSession();
//5.获取UserMapper接口对象,这个方法底层用代理模式返回了接口实现类的对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//6.执行SQL语句
int result = userMapper.insertUser(new User(100, "叶霆宇", "yty"));
//7.提交事务,核心配置文件中的事物方式为JDBC,因此需要手动提交
sqlSession.commit();
//8.关闭会话
sqlSession.close();
System.out.println("影响行数:"+result);
}
}
sqlSession默认不提交事务,自动提交事务可设置为
sqlSessionFactory.openSession(true);
8.总结
(1)注意事项
- 映射文件中的namespace要和mapper接口的全类名一致
- 映射文件中SQL语句的id要和mapper接口中的方法名一致
(2)工程文件
(3)分析图,mybatis是面向接口编程
9.添加Log4j日志
这一步只是优化
(1)添加依赖
<!-- log4j日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
(2)log4j日志配置文件名称为log4j.xml,存放在src/main/resources目录下
<?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>
(3)日志级别
FATAL(致命)>ERROR(错误)>WARN(警告)>INFO(信息)>DEBUG(调试)
从左到右打印的内容越来越详细,日志级别越低记录信息越多