MyBatis初步学习(一)
MyBatis初步学习(一)
一 MyBatis简单认识
二 MyBatis环境搭建
1、下载并在项目中导入MyBatis的jar包,与相关JDBK驱动
2、对主配置文件: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>
<!-- 关联配置文件(可不配,但要将${driver}等改为具体值 -->
<properties resource="dataSources.properties"></properties>
<environments default="development">
<environment id="development">
<!-- ? -->
<transactionManager type="JDBC"/>
<!-- 配置数据源 -->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- 关联局部配置文件 -->
<mappers>
<mapper resource="cn/java/dao/DaoMapper.xml"/>
</mappers>
</configuration>
3、对局部配置文件:局部配置文件.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="cn.java.dao.DaoMapper">
<select id="方法名" resultType="java.util.Map">
select * from 表名
</select>
</mapper>
4、配置 局部配置文件.xml 的 关联class文件:
package cn.java.dao;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
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 DaoMapper {
private SqlSession session;
public void init() {
try {
SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
InputStream is = Resources.getResourceAsStream("mybatic-config.xml");
SqlSessionFactory ssf = ssfb.build(is);
session = ssf.openSession();
} catch (IOException e) {
e.printStackTrace();
}
}
public void select() {
List<Map<String, Object>> userList = session.selectList("cn.java.dao.DaoMapper.select");
for (Map<String, Object> map : userList) {
System.out.println(map.toString());
}
}
}
5、测试是否搭建成功
package cn.java.main;
import cn.java.dao.DaoMapper;
public class Window {
public static void main(String[] args) {
DaoMapper dao = new DaoMapper();
dao.init();
dao.select();
}
}
三 MyBatis在xml文件中的常见操作
四 MyBatis的常用注解
五 MyBatis中常见的面试问题
1、#与$的区别?