第一次使用MyBatis(在IDEA下),总结一下使用过程:
mybatis-3.4.1.jar
mysql-connector-java-5.1.46.jar
log4j-1.2.17.jar(方便查看日志信息)
--导入log4j包同时还要导入log4j.xml()文件
2)创建数据库表和对应的javabean对象
我这里创建了一个Student的表
接着创建一个POJO类Student
package com.chang.bean; public class Student { private Integer id; private String name; private Integer age; private String sex; public Student(){} //若使用了有参构造函数,一定要写出无参构造函数 public Student(Integer id, String name, Integer age, String sex) { this.id = id; this.name = name; this.age = age; this.sex = sex; } //...... }
3)配置mybatis_config.xml文件和绑定数据库和java对象的StudentMapper.xml文件
mybits_config.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> <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/school"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="StudentMapper.xml"/> </mappers> </configuration>StudentMapper.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.chang.StudentMapper"> <!--id用于方法调用的标识,resultType为select查询的返回值类型 --> <select id="selectStud" resultType="com.chang.bean.Student"> select * from student where id = #{id} </select> </mapper>
4)测试
我们需要先获得一个sqlSessionFactory来实例一个sqlSession对象,SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
package com.chang.test; import com.chang.bean.Student; 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.InputStream; public class MybatisTest { @Test public void test() throws IOException { //获取sqlSessionFactory实例 String resource = "mybatis_config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //获取sqlSession实例 SqlSession openSession = sqlSessionFactory.openSession(); try{ Student student = openSession.selectOne("com.chang.StudentMapper.selectStud",1); //sql的唯一标识 , 2参数 System.out.println(student); }finally { openSession.close(); } } }
执行测试结果: