- 准备环境:
mysql数据库5.7,一定要记住root密码;
navicat(或者别的dbms,或者直接在mysql的shell中建库建表),在navicat中可以检验是否安装好mysql;
mysql对应的jar包,目前官网上下载到的是版本8,在配置驱动时会和一些老版教程有些出入,这是后话,如果maven中自动导的话只有6.0.6,不知道是不是我的idea内置的maven的问题;
mybatis的jar包,也可以用maven导
junit单元测试,可以用maven导,或者自带jar包 - 建一个普通的maven项目
- 建数据库,表,示例数据
- 创建目录结构,添加mybatis-config.xml配置文件,db.properties文件
- 运行测试。
mysql安装略,最好安5.7版本,而且用msi文件安装,比较不容易犯错,创建一个mybatis01的库,新建一张表,添加一条数据如下:
在网上可以找到类似的jar包,下载到某个文件夹下,备用
mybatis和junit可以用maven下载的:
复制这些东西到pom.xml的dependencies标签内
junit junit 3.8.2 test org.mybatis mybatis 3.4.6
之后应该在此处发现maven下载的包
自己新建一个lib目录,和src同级,把mysql驱动复制进去,右键add as library
按如下目录建包,类,xml,
如何新建xml文件和properties文件?只要new一个普通文件,自己添加后缀就行了
不要点下面那个XML Configuration File!!
db.properties中写如下内容,第一行的驱动要写最新的,第二行的端口号和数据库名可能要修改,useSSL如果不写会爆红,密码填自己的
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis01?useSSL=true jdbc.username=root jdbc.password=
mybatis-config.xml中写如下内容,注意mapper标签就行了,别的都是死的
实体类,属性照抄列名,重写一个toString方法
package com.junko.bean;
public class Student {
int id;
String sname;
String sdescrip;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", sname='" + sname + ''' +
", sdescript='" + sdescrip + ''' +
'}';
}
}
mapper是一个接口,注意不用写方法体!加注解不报错就说明mybatis导入正常
package com.junko.mapper;
import com.junko.bean.Student;
import org.apache.ibatis.annotations.Select;
public interface StudentInfoMapper {
@Select("select * from tb_student where sid = #{id}")
public Student selectStudentById(int id);
}
test类这样写
package com.junko.test;
import com.junko.bean.Student;
import com.junko.mapper.StudentInfoMapper;
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.InputStream;
public class test {
private SqlSessionFactory sqlSessionFactory;
private SqlSession sqlSession;
@Test
public void selectStudentByID(){
String resource = "mybatis-config.xml";
InputStream inputStream;
try{
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession();
}
catch (Exception e){
e.printStackTrace();
System.out.println(
"error"
);
}
StudentInfoMapper studentInfoMapper = sqlSession.getMapper(StudentInfoMapper.class);
Student student = studentInfoMapper.selectStudentById(1);
System.out.println(student);
}
}
正常结果:
可能的错误分析:
在这个例子中,因为没有用到xml做Mapper,那就只有db.properties和mybatis-config.xml放的位置可能出错。
首先,放在resource文件夹下是绝对没问题的
如果把两个文件放在src下,test类中加上src也会找不到,所以结论是老老实实放在resource下吧。



