Mybatis
MyBatis 是支持定制化 SQL、存储过程以及高级映射的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
1.使用mysql数据库(MySQLWorkbench):
建库建表,填充数据。
2.创建实体类Category
public class Category {
private int id;
private String name;
}
3.配置文件mybatis-config.xml(src目录下创建)
下面可以配置多个元素节点,而每个节点可以配置两个东西,一个是事务管理器配置,另一个是数据源配置。
<?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>
<typeAliases>
<package name="com.bean" />
</typeAliases>
<!-- 设置别名,自动扫描com.bean下类型, 在Category.xml使用resultType时不用写全com.bean.Category,直接用Category -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" /><!-- 使用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="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/bean/Category.xml" />
</mappers><!-- 映射Category.xml -->
</configuration>
4.配置Category.xml(com.bean目录)
<?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.bean">
<select id="listCategory" resultType="Category"><!-- 因为myBatis-config.xml直接写Category -->
select * from category_
</select>
</mapper>
5.测试类TestMybatis
public class TestMybatis {
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 通过配置文件"mybatis-config.xml"得到SQLSessionFactory(创建SqlSession对象的工厂)
SqlSession session = sqlSessionFactory.openSession();
// 通过SQLSessionFactory得到Session
List<Category> cs = session.selectList("listCategory");
// 通过session的selectList方法,调用sql语句listCategory。
for (Category c : cs) {
System.out.println(c.getName());
}
}
}
原理:
1. 应用程序找mybatis要数据
2. mybatis从数据库中请求数据
- 通过mybatis-config.xml 定位数据库
- 通过Category.xml执行对应的select语句
- 基于Catgory.xml把返回的数据库记录封装在Category对象中
- 把多个Category对象装在一个Category集合中
3. 返回一个Category集合