Mybatis是一款优秀的开源持久层框架。
入门demo
第一步:下载mybatis的jar包,github下载地址https://github.com/mybatis/mybatis-3
解压,把mybatis-3.3.0.jar,以及lib下的所有jar,额外引入mysql的驱动包到Eclipse的lib目录,并加入到classpath中。
第二步:新建数据库表,建立mybatis数据库,表student,字段id,name,age。
第三步:新建Student实体类,加入log4j的配置文件。
Student.java文件
package com.hbk.pojo;
public class Student {
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;
}
}
log4j.properties文件
log4j.rootLogger=DEBUG,Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
第四步:新建mybatis的配置文件和student的mapper文件
mybatis-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"></transactionManager>
<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="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/hbk/map/student.xml"/>
</mappers>
</configuration>
student.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.hbk.mybatis.Student">
<select id="findById" resultType="com.hbk.pojo.Student">
select * from student where id = #{id}
</select>
</mapper>
第五步:测试类:
package com.hbk.test;
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;
import com.hbk.pojo.Student;
public class StudentTest {
public static void main(String[] args) {
String resource = "com/hbk/map/mybatis-config.xml";
try {
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sqlSessionFactory.openSession();
Student student = sqlSession.selectOne("findById", 1);
System.out.println(student.getName());
sqlSession.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
输出结果:
工程目录结构图: