mybatis测试步骤
1. 添加jar包(两个jar包)
添加在WebContent—WEB-INF—lib下,然后选中libr目录下的文件,右键点击buildPath->add Path”
【mybatis】
mybatis-3.1.1.jar
【MYSQL驱动包】
mysql-connector-java-5.1.7-bin.jar
2.建表加库
3.添加Mybatis的配置文件conf.xml
//localhost:3306是本地路径 xskc是数据库名字
4.定义表所对应的实体类
public class User{
private int id;
private String name;
private int age;
//get.set 方法
}
要有无参构造方法
toString是取相应的值
5.定义操作users表(数据库中表的名字)的sql映射文件userMapper.xml
6.在conf.xml文件中注册userMapper.xml文件
mappers>
mapper resource=“com/mybatis_test/userMapper.xml”/>
/mappers>
7.编写测试代码
public class Test {
public static void main(String[] args) throws IOException {
String resource = “conf.xml”;
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sessionFactory = new
SqlSessionFac toryBuilder().build(reader);
SqlSession session = sessionFactory.openSession(true);
String statement = “com.mybatis_test.userMapper”+".selectUser";
User user = session.selectOne(statement, 1);
System.out.println(user);
System.out.println(user.getAge());
System.out.println(user.getId());
System.out.println(user.getName());
}
}
String statement = “com.mybatis_test.userMapper”+".selectUser";
//"selectUser"为userMapper.xml中的id值