----------------------------------------1.10----------------------------------------
写一下初入java学到关于MyBatis踩的坑
pom引入依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
创建全局配置文件,这里要注意下面的<mapper>是后面自己写的mapper接口需要引入
<?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核心配置文件-->
<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://ip地址:3306/mag_health_db?useSSl=false&sueUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai"/>
<property name="username" value="maghealth"/>
<property name="password" value="maghealth"/>
</dataSource>
</environment>
</environments>
<!--每一个Mapper.XML都需要在Mybatis核心配置文件中注册!-->
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
新创建一个utils方法,去创建sqlSessionFactory
//编写全局配置文件
//编写mapper映射文件
//加载全局配置文件,生成SqlSessionFactory
//创建SqlSession,调用mapper映射文件中的SQL语句来执行CRUD操作
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
配置mapper接口,
对应创建xml映射文件,正常如果数据库和实体类字段是一一对应的花就用resultType映射到实体类,如果不对应就需要创建resultMap去处理映射关系
<?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">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="org.example.dao.UserMapper">
<!--select查询语句-->
<!-- <select id="getUserList" resultType="org.example.pojo.User">-->
<!-- select * from mag_health_db.user-->
<!-- </select>-->
<!-- resultMap-->
<!-- id 在命名空间中唯一的标识符-->
<!-- type 结果集映射的javabean 或者 泛型为该类型的集合-->
<resultMap id="UserMap" type="org.example.pojo.User">
<!--
id 主键映射
result 非主键映射
property javabean 中的 filed
column datatable 中的 filed
-->
<id property="idd" column="id"></id>
<result property="namee" column="name"></result>
</resultMap>
<select id="getUserList" resultMap="UserMap">
select * from mag_health_db.user
</select>
</mapper>