创建一个mybatis的maven项目
环境:IDEA19.3.3+jdk1.8+mysq
新建maven项目
项目名字
maven
大体框架
导包(要在pom.xml中dependencies标签里面)
2 <!-- mybatis核心包 -->3 <dependency>4 <groupId>org.mybatis</groupId>5 <artifactId>mybatis</artifactId>6 <version>3.3.0</version>7 </dependency>8 <!-- mysql驱动包 -->9 <dependency>
10 <groupId>mysql</groupId>
11 <artifactId>mysql-connector-java</artifactId>
12 <version>5.1.29</version>
13 </dependency>
14 <!-- junit测试包 -->
15 <dependency>
16 <groupId>junit</groupId>
17 <artifactId>junit</artifactId>
18 <version>4.11</version>
19 <scope>test</scope>
20 </dependency>
37 </dependencies>**mybatis-config.xml(在resources下创建XML文件(数据库的连接环境配置等)以及映射的XML文件)**<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!-- 环境配置 --><environments default="development"><environment id="development"><transactionManager type="JDBC"/><!-- 数据库连接相关配置 ,这里动态获取config.properties文件中的内容--><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/mybatis" /><property name="username" value="root" /><property name="password" value="x5" /></dataSource></environment></environments><!-- mapping文件路径配置 --><mappers><mapper resource="mapper/UserMapper.xml"/></mappers></configuration>
.创建pojo类`
package com.yhr.pojo;public class User { private int uid;private String uname;private int uage;public int getUid() {return uid;}public void setUid(int uid) {this.uid = uid;}public String getUname() {return uname;}public void setUname(String uname) {this.uname = uname;}public int getUage() {return uage;}public void setUage(int uage) {this.uage = uage;}
}创建个测试类import com.zc.dao.UserMapper;
import com.zc.pojo.User;
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 org.junit.Test;import java.io.IOException;
import java.io.Reader;
import java.sql.ClientInfoStatus;
import java.util.List;public class UserTest {@Testpublic void userFindByIdTest(){//定义读取文件名String resources = "mybatis-config.xml";//创建流Reader reader=null;try {//读取mybatis-config.xml文件到reader对象中reader= Resources.getResourceAsReader(resources);} catch (IOException e) {e.printStackTrace();}//初始化mybatis,创建SqlSessionFactory类的实例SqlSessionFactory sqlMapper=new SqlSessionFactoryBuilder().build(reader);//创建session实例SqlSession session=sqlMapper.openSession();//传入参数查询,返回结果UserMapper userMapper=session.getMapper(UserMapper.class);List<User> user=userMapper.findById(1);//输出结果System.out.println(user);//关闭sessionsession.close();}
}