第一个Mybatis程序
MyBatis第一个程序
思路流程:搭建环境-->导入Mybatis--->编写代码--->测试
代码演示
1、搭建实验数据库
CREATE DATABASE `mybatis`;
USE `mybatis`;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(20) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`pwd` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `user`(`id`,`name`,`pwd`) values (1,'狂神','123456'),(2,'张三','abcdef'),(3,'李四','987654');
2、导入MyBatis相关 jar 包
- GitHub上找
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
3、编写MyBatis核心配置文件
- 查看帮助文档
<?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>
<!-- 配置mybatis的环境 -->
<environments default="development">
<!-- 配置mysql的环境 -->
<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?useSSL=true&useUnicode=true&characterEncoding=utf8"/><!--出现通讯错误把true该成false-->
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 告知mybatis映射配置的位置 -->
<mappers>
<mapper resource="com/kuang/dao/userMapper.xml"/>
</mappers>
</configuration>
4、编写MyBatis工具类
- 查看帮助文档
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//1.读取配置文件
//2.SQLSession工厂
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//获取SqlSession连接
public static SqlSession getSession(){
return sqlSessionFactory.openSession();
}
}
5、创建实体类
public class User {
private int id; //id
private String name; //姓名
private String pwd; //密码
//构造,有参,无参
//set/get
//toString()
}
6、编写Mapper接口类
import com.kuang.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> getUserList();
}
7、编写Mapper.xml配置文件
- namespace 十分重要,不能写错!
<?xml version="1.0" encoding="UTF-8" ?>
<!--编写Mapper.xml配置文件-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.dao.UserMapper">
<select id="selectUser" resultType="com.kuang.pojo.User">
select * from user
</select>
</mapper>
namespace -->对象的映射的接口
id -->对应接口的方法
resiltType -->把结果封装对象类型
8、编写测试类
- Junit 包测试
public class MyTest {
@Test
public void getUserList() {
//创建我们的实现接口的对象
SqlSession session = MybatisUtils.getSession();
//调用对应的方法
//方法一:(淘汰)
//List<User> users = session.selectList("com.kuang.mapper.UserMapper.getUserList");
//方法二:
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> users = mapper.getUserList();
//处理结果
for (User user: users){
System.out.println(user);
}
//关闭
session.close();
}
}
9、运行测试,成功的查询出来的我们的数据,ok!
问题说明
1. 可能出现问题说明:在mybatis核心配置文件里的位置写错
//java.lang.ExceptionInInitializerError
<!-- 告知mybatis映射配置的位置 -->
<mappers>
<mapper resource="com/chen/dao/userMapper.xml"/>
</mappers>
2. 可能出现问题说明:在测试包装类型过程中产生了一个错误!!!时区问题
在url设置时区为utc的时候用了小写,必须要大写
//org.apache.ibatis.exceptions.PersistenceException:
//### Error querying database. Cause: java.sql.SQLException: No timezone mapping entry for 'utc'
//### The error may exist in com/chen/dao/userMapper.xml
//### The error may involve com.chen.dao.UserMapper.selectUser
//### The error occurred while executing a query
//### Cause: java.sql.SQLException: No timezone mapping entry for 'utc'
//翻译:
// org.apache.ibatis.exceptions.PersistenceException:查询数据库时出错。原因:java.sql.SQLException:“utc”没有时区映射条目 comchendaouserMapper.xml 中可能存在错误 该错误可能涉及 com.chen.dao.UserMapper.selectUser 执行查询时发生错误原因:java.sql。 SQLException: 没有“utc”的时区映射条目
<!-- 在mybatis核心配置文件中url -->
<property name="url" value="jdbc:mysql://localhost:3306/ssm?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC"/>
MySQL5.7版本把true改为false
3. 可能出现问题说明:Maven静态资源过滤问题
<!-- 在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
<build>
<!--出现UTF-8之类的报错-->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
写在父类pom.xml里面

浙公网安备 33010602011771号