Mybatis细节处理之mapper.xml的存放,properties配置文件,类型别名以及创建log4j配置文件
程序员文章站
2022-07-15 10:38:16
...
一.解决mapper.xml存放在resources以外路径中的读取问题
在pom.xml文件最后追加< build >标签,以便可以将xml文件复制到classes中,并在程序运行时正确读取。
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
二.properties配置文件
1.对于mybatis-config.xml的核心配置中,如果存在需要频繁改动的数据内容,可以提取到properties中。
#jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/example?useUnicode=true&characterEncpding=utf8
username=root
password=123456
#jdbc.properties
#有多个.properties文件时可以加上jdbc,则对应的mybatis-config.xml中${jdbc.driver}...
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/example?useUnicode=true&characterEncpding=utf8
jdbc.username=root
jdbc.password=123456
2.修改mybatis-config.xml。注意!properties至于顶部(点击)
<?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>
<!--添加properties配置文件路径(外部配置、动态替换)-->
<properties resource="jdbc.properties" />
<environments default="MySqlDB">
<environment id="MySqlDB">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--使用$ + 占位符-->
<property name="driver" value="${driver}"/>
<!--<property name="driver" value="${jdbc.driver}"/>-->
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserDaoMapper.xml" />
</mappers>
</configuration>
三.类型别名
为实体类定义别名,提高书写效率。
<?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>
<properties ... />
<!--定义别名二选一-->
<typeAliases>
<!--定义类的别名-->
<typeAlias type="com.cos.entity.User" alias="user" />
<!--自动扫描包,将原类名作为别名-->
<package name="com.cos.entity" />
</typeAliases>
...
</configuration>
四.创建log4j配置文件
1.pom.xml添加log4j依赖
<!-- log4j日志依赖 https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2.创建并配置log4j.properties
# 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
上一篇: 计算存款本息(错误记录)