mybatis中文乱码
时间: 2023-11-07 18:01:07 浏览: 162
如果在 MyBatis 中遇到了中文乱码问题,可以尝试以下解决方案:
1. 在 jdbc 链接中添加编码参数
```xml
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
```
2. 在配置文件中添加编码过滤器
```xml
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="com.example.model"/>
</typeAliases>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
<plugins>
<plugin interceptor="com.example.plugin.MyInterceptor"/>
</plugins>
<objectFactory type="com.example.factory.MyObjectFactory"/>
<objectWrapperFactory type="com.example.factory.MyObjectWrapperFactory"/>
<reflectorFactory type="com.example.factory.MyReflectorFactory"/>
<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/test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="filters" value="stat,wall,config"/>
<property name="connectionProperties" value="druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000"/>
</dataSource>
</environment>
</environments>
<databaseIdProvider type="DB_VENDOR">
<property name="Oracle" value="oracle"/>
<property name="MySQL" value="mysql"/>
<property name="DB2" value="db2"/>
</databaseIdProvider>
<typeHandlers>
<typeHandler javaType="java.util.Date" jdbcType="DATE" handler="com.example.handler.MyDateTypeHandler"/>
</typeHandlers>
<objectWrapperFactory type="com.example.factory.MyObjectWrapperFactory"/>
<reflectorFactory type="com.example.factory.MyReflectorFactory"/>
</configuration>
```
3. 在 mapper 文件中添加字符集设置
```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.example.mapper.UserMapper">
<resultMap id="userMap" type="com.example.model.User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<result property="gender" column="gender"/>
</resultMap>
<select id="selectById" resultMap="userMap">
select * from user where id=#{id}
</select>
<insert id="insert" parameterType="com.example.model.User">
insert into user(id,name,age,gender) values(#{id},#{name},#{age},#{gender})
</insert>
</mapper>
```
阅读全文