15.MyBatis配置文件1

 

添加日志文件log4j.properties

添加log4j日志文件,可以打印mybatis实际执行的sql语句,方便代码调试

新建日志文件log4j.properties

1
2
3
4
5
6
7
8
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

在mybatis.cfg.xml添加log4j的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?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">

<!-- MyBatis的整体配置 -->
<configuration>

<!-- mybatis.cfg.xml配置文件的<configuration>节点的子节点是有顺序要求的 -->
<!--
The content of element type "configuration" must match
"(properties?,settings?,typeAliases?,typeHandlers?,
objectFactory?,objectWrapperFactory?,reflectorFactory?,
plugins?,environments?,databaseIdProvider?,mappers?)".

<properties></properties>
<typeAliases></typeAliases>
<plugins></plugins>
<environments></environments>
<mappers></mappers>
-->

<settings>
<!-- 让log4j去记录sql日志,打印mybatis执行的sql语句 -->
<setting name="logImpl" value="LOG4J"/>
<!-- https://mybatis.org/mybatis-3/zh/configuration.html#properties -->
</settings>

<!-- 数据源环境配置,default默认数据源的id -->
<environments default="mysql_test">

<!-- mysql 测试数据库 -->
<environment id="mysql_test">

<!-- mybatis的事务管理器 -->
<transactionManager type="JDBC"></transactionManager>

<!-- 配置数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis_test"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>

<!-- mysql 生产数据库 -->
<!-- <environment id="mysql_prod"></environment> -->

<!-- oracle 数据库 -->
<!-- <environment id="oracle"></environment> -->

</environments>

<!-- 配置Mapper.xml文件 -->
<mappers>
<mapper resource="com/course/mapper/UserMapper.xml" />
</mappers>
</configuration>
1
2
3
4
5
6
7
8
9
10
DEBUG [main] - Opening JDBC Connection
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
DEBUG [main] - Created connection 2059461664.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7ac0e420]
DEBUG [main] - ==> Preparing: select * from user
DEBUG [main] - ==> Parameters:
DEBUG [main] - <== Total: 10
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7ac0e420]
DEBUG [main] - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7ac0e420]
DEBUG [main] - Returned connection 2059461664 to pool.

添加工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.course.util;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {

private static InputStream inputStream = MyBatisUtil.class.getResourceAsStream("/mybatis.cfg.xml");

private static SqlSessionFactoryBuilder sessionFactoryBuilder = new SqlSessionFactoryBuilder();

private static SqlSessionFactory sqlSessionFactory = sessionFactoryBuilder.build(inputStream);

public static SqlSession openSqlSession() {
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}

public static void closeSqlSession(SqlSession sqlSession) {
sqlSession.commit();
sqlSession.close();
}
}

或者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.course.util;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil2 {

private static SqlSessionFactory sqlSessionFactory = null;

static {
InputStream inputStream = MyBatisUtil2.class.getResourceAsStream("/mybatis.cfg.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
}

public static SqlSession openSqlSession() {
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}

public static void closeSqlSession(SqlSession sqlSession) {
sqlSession.commit();
sqlSession.close();
}
}

接口的实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.course.dao.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.course.dao.UserDao;
import com.course.util.MyBatisUtil;
import com.course.util.MyBatisUtil2;
import com.course.vo.User;

public class UserDaoImpl implements UserDao {

@Override
public void addUser(User user) {
// 1.得到sqlSession
SqlSession sqlSession = MyBatisUtil.openSqlSession();
// 2.进行CRUD
/**
* 参数1: 对应的是UserMapper.xml里面<insert>节点的命名空间+id属性值
* 参数2: UserMapper.xml里面<insert id="参数1">的parameterType属性对应的类型的对象
*/
sqlSession.insert("com.course.dao.abc.UserDao.addUserXml", user);
// 3.提交事务,关闭session
MyBatisUtil.closeSqlSession(sqlSession);

}

@Override
public void updateUser(User user) {
// 1.得到sqlSession
SqlSession sqlSession = MyBatisUtil.openSqlSession();
// 2.进行CRUD
sqlSession.update("com.course.dao.abc.UserDao.updateUser", user);
// 3.提交事务,关闭session
MyBatisUtil.closeSqlSession(sqlSession);

}

@Override
public void deleteUser(Integer id) {
// 1.得到sqlSession
SqlSession sqlSession = MyBatisUtil.openSqlSession();
// 2.进行CRUD
sqlSession.delete("com.course.dao.abc.UserDao.deleteUser", id);
// 3.提交事务,关闭session
MyBatisUtil.closeSqlSession(sqlSession);

}

@Override
public User getUserById(Integer id) {
// 1.得到sqlSession
SqlSession sqlSession = MyBatisUtil.openSqlSession();
// 2.进行CRUD
User user = sqlSession.selectOne("com.course.dao.abc.UserDao.getUserById", id);
// 3.提交事务,关闭session
MyBatisUtil.closeSqlSession(sqlSession);

return user;
}

@Override
public List<User> getAllUser() {
// 1.得到sqlSession
SqlSession sqlSession = MyBatisUtil2.openSqlSession();
// 2.进行CRUD
List<User> userList = sqlSession.selectList("com.course.dao.abc.UserDao.getAllUser");
// 3.提交事务,关闭session
MyBatisUtil2.closeSqlSession(sqlSession);

return userList;
}
}

mybatis.cfg.xml配置文件详解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?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">

<!-- MyBatis的整体配置 -->
<configuration>

<settings>
<!-- 让log4j去记录sql日志,打印mybatis执行的sql语句 -->
<setting name="logImpl" value="LOG4J"/>
<!-- https://mybatis.org/mybatis-3/zh/configuration.html#properties -->
</settings>

<!-- 数据源环境配置,default默认数据源的id -->
<!-- 数据源环境配置 default默认数据源的ID
environments 指mybatis可以配置多个环境,default指向默认的环境
每个SqlSessionFactory对应一个环境environment
-->
<environments default="mysql_test">

<!-- 环境
可以配置多个数据源 但是能使用一个
-->
<!-- mysql 测试数据库 -->
<environment id="mysql_test">

<!-- mybatis的事务管理器 -->
<!-- 配置mybatis的事务管理器
type 的配置
JDBC【建议】 – 这个配置直接使用JDBC 的提交和回滚功能。它依赖于从数据源获得连接来管理
事务的生命周期。
MANAGED – 这个配置基本上什么都不做。它从不提交或者回滚一个连接的事务。而是让
容器(例如:Spring 或者J2EE 应用服务器)来管理事务的生命周期
-->
<transactionManager type="JDBC"></transactionManager>

<!-- 配置数据库连接池 -->
<!-- 这个环境里面的数据源
type:POOLED【建议】
这个数据源的实现缓存了JDBC 连接对象,用于避免每次创建新的数据库连接时都初始
化和进行认证,加快程序响应。并发WEB 应用通常通过这种做法来获得快速响应。
UNPOOLED:每次连接数据库时都创建新的连接【不推荐】
JNDI:使用外部的数据源 如tomcat可以配置数据源在这里使用
-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis_test"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>

<!-- mysql 生产数据库 -->
<!-- <environment id="mysql_prod"></environment> -->

<!-- oracle 数据库 -->
<!-- <environment id="oracle"></environment> -->

</environments>

<!-- 配置Mapper.xml文件 -->
<mappers>
<mapper resource="com/course/mapper/UserMapper.xml" />
</mappers>

</configuration>

引入db.properties

新建db.properties

1
2
3
4
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis_test
username=root
password=123456

修改mybatis.cfg.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<?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">

<!-- MyBatis的整体配置 -->
<configuration>

<properties resource="db.properties"></properties>

...

</configuration>