1. 下载jar包
https://github.com/mybatis/mybatis-3/releases
2. 导入jar包
- mybatis -3.2.7.jar
- lib目录下所有jar包
- mysql驱动包
3. classpath目录下创建log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
4. classpath下创建SqlMapConfig.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>
<!-- 和spring整合后 environments配置将废除-->
<environments default=*"development"*>
<environment id=*"development"*>
<!-- 使用jdbc事务管理-->
<transactionManager type=*"JDBC"* />
<!-- 数据库连接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
</configuration>
5. 编写po类(bean类)
Public class User {
private int id;
private String username;// 用户姓名
private String sex;// 性别
//get/set方法
6. 创建sql映射文件User.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=*"test"*>
<select id="getUserById" parameterType="java.lang.Integer" resultType="com.itheima.pojo.User">
select * from user where id = #{id}
</select>
</mapper>
并在SqlMapConfig.xml配置
<mappers>
<mapper resource="sqlmap/User.xml"/>
</mappers>
7. 测试程序
public class Demo1 {
private SqlSessionFactory factory;
@Before
public void setUp() throws IOException {
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
this.factory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void run1() throws IOException {
SqlSession session = this.factory.openSession();
User user = session.selectOne("test.getUserById" , 1);
System.out.println(user);
}
初步的快速入门完成!