mybatis搭建過程:
一、導入jarjava
log4j.jar
mybatis-3.4.1.jar
mysql-connector-java-5.1.37-bin.jar
二、建立mybatis的核心(全局)配置文件mybatis-config.xml,並配置mysql
<?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>
<properties resource="jdbc.properties"></properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
三、建立映射文件XxxMapper.xml,並配置sql
<?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.atguigu.mapper.UserMapper">
<select id="getuid" resultType="com.atguigu.bean.User">
select uid,userName,password,age,sex from user where uid = #{id}
</select>
</mapper>
四、建立mapper接口,實現兩個綁定:數據庫
public interface UserMapper {
User getuid(String id);
}
(1)接口全限定名要和映射文件的namespace保持一致
(2)接口中方法名和SQL語句的id保持一致
五、獲取mybatis操做數據庫的會話對象SqlSession,經過getMapper()獲取接口的動態代理實現類
六、測試mybatis
InputStream rs = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(rs);
SqlSession openSession = build.openSession();
UserMapper mapper = openSession.getMapper(UserMapper.class);
User getuid = mapper.getuid("1");
System.out.println(getuid);app