网上解决的都是实体字段和表字段冲突而不能正常取值的问题。但是!我即使冲突了,但是还能正常从数据库中拿数据输出到控制台,很奇怪。
给大家看一下我的相关配置。
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<!--导入日志相关依赖-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
核心配置类
<?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="hh">
<environment id="hh">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/emp ? serverTimezone=GMT&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
<!--映射mapper文件的位置-->
<mappers>
<mapper resource="com/leezy/dao/UserDao.xml"></mapper>
<mapper resource="com/leezy/dao/EmpDao.xml"></mapper>
</mappers>
</configuration>
mapper接口。这里写的Dao,初学阶段,命名还没改过来
public interface EmpDao {
List<Emp> findList();
int insertEmp(Emp emp);
}
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.leezy.dao.EmpDao">
<select id="findList" resultType="com.leezy.pojo.Emp">
select * from tb_emp
</select>
<insert id="insertEmp" parameterType="com.leezy.pojo.Emp">
insert into tb_emp(eid,emp_name,emp_sex,emp_age,emp_salary,birthday) values (#{eid},#{empName},#{empSex},#{empAge},#{empSalary},#{birthday})
</insert>
</mapper>
测试类。没有完全贴出代码,大家肯定看得懂
resourceAsStream = Resources.getResourceAsStream(s);
//创建工厂对象
build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//从工厂获取对象
sqlSession = build.openSession();
EmpDao mapper = sqlSession.getMapper(EmpDao.class);
List<Emp> list = mapper.findList();
for (Emp emp : list) {
System.out.println(emp);
}
sqlSession.commit();
sqlSession.close();
控制台输出结果
按理来说我应该在mapper.xml加上一个resultmap标签,就是以下图