IDE:idea 2021.2
构建工具:maven 3.6.3
MySQL版本:MySQL 8
MyBatis版本:MyBatis 3.5.10
MySQL不同版本的注意事项
1、驱动类driver-class-name
MySQL 5版本使用jdbc5驱动,驱动类使用:com.mysql.jdbc.Driver
MySQL 8版本使用jdbc8驱动,驱动类使用:com.mysql.cj.jdbc.Driver
2、连接地址url
MySQL 5版本的url:
jdbc:mysql://localhost:3306/ssm
MySQL 8版本的url:
jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
否则运行测试用例报告如下错误:
java.sql.SQLException: The server time zone value ‘Öйú±ê׼ʱ¼ä’ is unrecognized or
represents more
Maven 下载官网
解压文件并配置环境变量
变量名:
MAVEN_HOME
变量值:
D:\maven\apache-maven-3.8.6
path配置路径:
%MAVEN_HOME%\bin
cmd测试:
配置Maven仓库
apache-maven-3.8.6------>conf------>settings.xml
修改:
配置Maven远程仓库(setting.xml)
默认国外仓库,更改位国内阿里云仓库
修改:
代码:
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>
IDEA配置:
创建maven项目报错:
java.lang.RuntimeException: org.codehaus.plexus.component.repository.exception.ComponentLookupException: com.google.inject.ProvisionException: Unable to provision, see the following errors:
1) Error injecting constructor, java.lang.NoSuchMethodError: org.apache.maven.model.validation.DefaultModelValidator: method 'void <init>()' not found
at org.jetbrains.idea.maven.server.embedder.CustomModelValidator.<init>(Unknown Source)
while locating org.jetbrains.idea.maven.server.embedder.CustomModelValidator
at ClassRealm[maven.ext, parent: ClassRealm[plexus.core, parent: null]] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
while locating org.apache.maven.model.validation.ModelValidator annotated with @com.google.inject.name.Named(value="ide")
1 error
role: org.apache.maven.model.validation.ModelValidator
roleHint: ide
解决办法:更换低版本Maven
<dependencies>
<!-- Mybatis核心 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
</dependencies>
新建数据库SSM。新建表t_user
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`username` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`password` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`age` int(0) NULL DEFAULT NULL,
`gender` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`email` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES (1, NULL, NULL, NULL, '', NULL);
SET FOREIGN_KEY_CHECKS = 1;
User类:
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
private String gender;
private String email;
public User() {
}
public User(Integer id, String username, String password, Integer age, String gender, String email) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
this.gender = gender;
this.email = email;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
", email='" + email + '\'' +
'}';
}
}
习惯上命名为mybatis-config.xml,这个文件名仅仅只是建议,并非强制要求。将来整合Spring之后,这个配置文件可以省略,所以大家操作时可以直接复制、粘贴。
核心配置文件主要用于配置连接数据库的环境以及MyBatis的全局配置信息
核心配置文件存放的位置是src/main/resources目录下
mybatis-3.5.10.pdf------->getting started
<?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="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
src/main/resources目录下---->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>
<!--配置连接数据库的环境-->
<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/ssm?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 引入MyBatis的映射文件-->
<mappers>
<mapper resource=""/>
</mappers>
</configuration>
MyBatis中的mapper接口相当于以前的dao。但是区别在于,mapper仅仅是接口,我们不需要提供实现类。
public interface UserMapper {
/**
* 添加用户信息
*/
int insertUser();
}
相关概念:ORM(Object Relationship Mapping)对象关系映射。
java概念 | 数据库概念 |
---|---|
类 | 表 |
属性 | 字段/列 |
对象 | 记录/行 |
1、映射文件的命名规则:
表所对应的实体类的类名+Mapper.xml
例如:表t_user,映射的实体类为User,所对应的映射文件为UserMapper.xml
因此一个映射文件对应一个实体类,对应一张表的操作
MyBatis映射文件用于编写SQL,访问以及操作表中的数据
MyBatis映射文件存放的位置是src/main/resources/mappers目录下
2、 MyBatis中可以面向接口操作数据,要保证两个一致:
a>mapper接口的全类名和映射文件的命名空间(namespace)保持一致
b>mapper接口中方法的方法名和映射文件中编写SQL的标签的id属性保持一致
mybatis-3.5.10.pdf ----->2.1.5
<?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="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
在resources新建mappers文件夹,新建UserMapper.xml文件
<?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.gao.mybatis.mapper.UserMapper">
<!--
mapper接口和映射文件要保证两个一致:
1.mapper接口的全类名和映射文件的namespace要保持一致
2.mapper接口中的方法的方法名和映射文件中的sql的id保持一致
-->
<!--int insertUser();-->
<insert id="insertUser">
insert into t_user values(null,"admin",123456,23,'男','123456@qq.com');
</insert>
</mapper>
配置mybatis-config.xml
<!-- 引入MyBatis的映射文件-->
<mappers>
<mapper resource="mappers/UserMapper.xml"/>
</mappers>
public class MyBatisTest {
@Test
public void testInsert() throws IOException {
//获取核心配置文件的输入流
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//获取SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//获取SqlSessionFactory对象
SqlSessionFactory build = sqlSessionFactoryBuilder.build(is);
//获取SQL的SqlSession,是MyBatis提供的操作数据库的对象
SqlSession sqlSession = build.openSession();
//获取UserMapper的代理实现类对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用mapper接口中的方法,实现添加用户信息的功能
int result = mapper.insertUser();
System.out.println("结果" + result);
//提交事务
sqlSession.commit();
//关闭sqlSeesion
sqlSession.clearCache();
}
}
- SqlSession:代表Java程序和数据库之间的会话。(HttpSession是Java程序和浏览器之间的会话)
- SqlSessionFactory:是“生产”SqlSession的“工厂”。
- 工厂模式:如果创建某一个对象,使用的过程基本固定,那么我们就可以把创建这个对象的相关代码封装到一个“工厂类”中,以后都使用这个工厂类来“生产”我们需要的对象。
原始映射:
@Test
public void testInsert() throws IOException {
//获取核心配置文件的输入流
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//获取SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//获取SqlSessionFactory对象
SqlSessionFactory build = sqlSessionFactoryBuilder.build(is);
//获取SQL的SqlSession,是MyBatis提供的操作数据库的对象
SqlSession sqlSession = build.openSession();
// //获取UserMapper的代理实现类对象
// UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// //调用mapper接口中的方法,实现添加用户信息的功能
// int result = mapper.insertUser();
//提供SQL以及唯一标识找到sql并执行,唯一标识:namespace.sqlId
int result = sqlSession.insert("com.gao.mybatis.mapper.UserMapper.insertUser");
System.out.println("结果" + result);
//提交事务
sqlSession.commit();
//关闭sqlSeesion
sqlSession.clearCache();
自动提交代码:
@Test
public void testInsert() throws IOException {
//获取核心配置文件的输入流
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//获取SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//获取SqlSessionFactory对象
SqlSessionFactory build = sqlSessionFactoryBuilder.build(is);
//获取SQL的SqlSession(不会自动提交),是MyBatis提供的操作数据库的对象
// SqlSession sqlSession = build.openSession();
//获取SQL的SqlSession(不会自动提交),是MyBatis提供的操作数据库的对象
SqlSession sqlSession = build.openSession(true);
//获取UserMapper的代理实现类对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用mapper接口中的方法,实现添加用户信息的功能
int result = mapper.insertUser();
// //提供SQL以及唯一标识找到sql并执行,唯一标识:namespace.sqlId
// int result = sqlSession.insert("com.gao.mybatis.mapper.UserMapper.insertUser");
System.out.println("结果" + result);
//提交事务
// sqlSession.commit();
//关闭sqlSeesion
sqlSession.clearCache();
}
<!-- log4j日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
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>
日志的级别
FATAL(致命)>ERROR(错误)>WARN(警告)>INFO(信息)>DEBUG(调试)
从左到右打印的内容越来越详细
运行,输出日志信息:
DEBUG 07-28 10:30:18,594 ==> Preparing: insert into t_user values(null,"admin",123456,23,'男','123456@qq.com'); (BaseJdbcLogger.java:137)
DEBUG 07-28 10:30:18,610 ==> Parameters: (BaseJdbcLogger.java:137)
DEBUG 07-28 10:30:18,613 <== Updates: 1 (BaseJdbcLogger.java:137)
结果1