1.先去mybatis官网把mybatis的jar下载下来,我用的3.1.1版本。mybatis的jar和连接mysql数据库的jar都放进创建的java工程里面。
2.创建mybatis数据库与user表

3.创建如图所示的包及xml文件。

4.配置文件conf.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> <!-- development : 开发模式 work : 工作模式 --> <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" /> <property name="username" value="root" /> <property name="password" value="" /> </dataSource> </environment> </environments> <mappers> <!-- 写mapper所在的包的路径 --> <mapper resource="com/kpzc/test1/userMapper.xml"/> </mappers> </configuration>
5.创建user的bean
package com.kpzc.bean;
public class User {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public User() {
super();
}
public User(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
6.写userMapper.xml
<?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">
<!-- 一般写包的路径(不带.xml) -->
<mapper namespace="com.kpzc.test1.userMapper">
<!--
根据id查询得到一个user对象
parameterType id的参数类型
resultType 写bean对象
-->
<select id="getUser" parameterType="int" resultType="com.kpzc.bean.User">
select * from users where id=#{id}
</select>
</mapper>
7.最后写一个测试方法
package com.kpzc.test1;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.kpzc.bean.User;
/*
* @author kpzc
*/
public class Test {
public static void main(String[] args) throws IOException {
//加载mybatis的配置文件,也加载关联的映射文件
String resource = "conf.xml";
InputStream is = Test.class.getClassLoader().getResourceAsStream(resource);
//构建SqlSession工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//创建能执行映射文件中sql的SqlSession
SqlSession session = factory.openSession();
//映射sql标识字符串
String statement = "com.kpzc.test1.userMapper.getUser";
//执行查询返回一个指定的user
User user = session.selectOne(statement,1);
System.out.println(user);
}
}
8.运行结果

有什么不正之处欢迎大家之处,鄙人不胜感激。