Mybatis学习笔记
总
mybatis学习1
mybatis学习2
mybatis学习3
mybatis学习4
mybatis学习5
mybatis学习6
Mybatis代码
Mybatis入门
写一个Mybatis项目
1、新建一个Maven项目
2、导入依赖集
<!-- 导入依赖 -->
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
3、创建模块,配置mybatis核心文件mybatis-config.xml
<?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.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 每一个Mapper.xml都需要在mybatis核心配置文件中注册! -->
<mappers>
<mapper resource="com/github/subei/dao/UserMapper.xml"/>
</mappers>
</configuration>
连接了数据库,创建对象类(pojo)
创建Dao层(业务逻辑操作)接口
创建一个userDao
package com.github.dao;
import com.github.pojo.User;
import java.util.List;
public interface UserDao {
List<User> getUserList();
}
接下来继承这个接口
<?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="com.github.subei.dao.UserDao">
<!--select查询语句-->
<select id="getUserList" resultType="com.github.subei.pojo.User">
select * from mybatis.user;
</select>
</mapper>
报错问题
1、Error creating document instance. Cause: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 1 字节的 UTF-8 序列的字节 1 无效。
解决方法:在settings中找到file encoding 将字符集设置为utf-8
2、java.lang.ExceptionInInitializerError at com.kuang.dao.UserDaoTest.test(UserDaoTest.java:15)
在所有xml代码中添加一下代码
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<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>
学习六
报错
问题:找不到pojo类中包的函数
解决:idea中,如果把UserMapper放在com.github.dao下,而UserMapper放在resource里的com.github.dao下,会导致报错。
(在生成的target文件中两个文件没有生成在同一目录下)
将同名文件放在同一个目录下