先创建一个java工程MybatisProject,在src下面建包和实体类,并在数据库创建相同的person表,然后导入mybatis-3.4.6.jar包
package com.liusong.entity; public class Person { private int id; private String name; private int age; public Person() { super(); this.id = id; this.name = name; this.age = age; } public Person(int id, String stu_name, int age) { super(); this.id = id; this.name = stu_name; this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getstu_name() { return name; } public void setName(String stu_name) { this.name = stu_name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "编号:" + getId() + ", 姓名:" + getstu_name() + ", 年纪" + getAge(); } }
在实体类下面创建一个XML文件PersonMapper.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">
<!--映射文件路径 -->
<mapper namespace="com.liusong.entity.PersonMapper">
<select id="queryPersonById" resultType="com.liusong.entity.Person">
select * from person where id = #{id}
</select>
</mapper>
再创建配置信息config.xml,从官方文档导入头信息
并做修改,导入jdbc的驱动jar包
<?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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED">
<!--配置数据库信息 --> <property name="driver" value="com.mysql.cj.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/shop?serverTimezone=UTC" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments>
<!--加载映射文件 --> <mappers> <mapper resource="com/liusong/entity/PersonMapper.xml" /> </mappers> </configuration>
写测试类测试一下
package com.liusong.entity; import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class TestDemo { public static void queryStudentById() throws IOException { //将config.xml变为流 Reader reader = Resources.getResourceAsReader("conf.xml"); //创建sessionFactory对象,sessionFactory是一个接口,不能new,需要用到SqlSessionFactoryBuilder,并使用其中的build(Reader reader)方法 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sessionFactory.openSession(); String stament = "com.liusong.entity.PersonMapper.queryPersonById"; Person person = session.selectOne(stament, 1); System.out.println(person); session.close(); } public static void main(String[] args) throws IOException { queryStudentById(); } }
测试结果:编号:1, 姓名:zs, 年纪23