JDBC:(Java database connectivity)
目的:将Java语言和数据库解耦和,使得一套Java程序能对应不同的数据库。
方法:sun公司制定了一套连接数据库的接口(API)。这套API叫做JDBC,JDBC的接口的实现类由数据库厂家负责编写,打包成jar包进行发布,这些jar包通常被称为“驱动”,
Jar包:mysql-connector-java-*.*.*-bin.jar
JDBC开发的六部曲:
1、 注册驱动:
DriverManager.registerDriver(new Driver())
或者Class.forName(“com.mysql.jdbc.Driver”)这种方式将com.mysql.jdbc.Driver类装载在JVM当中,装载过程中会自动执行静态代码块,完成驱动的注册。
2、 获取数据库的连接对象
Connection conn = DriverManager.getConnection(url,user,password)
3、 获取数据库的操作对象
Statement state = conn.createStatement()
为了防止数据库的注入攻击
PreparedStatement ps = conn.createPreparedStatement()
4、 执行SQL语句
ResultSet res = ps.executeQuery(sql)
Boolean bool = ps.execute(sql)
5、 处理查询的结果集
如果是查询结果集,这里采用迭代器的原理,进行遍历
While(res.next()){}
6、 释放资源
先关ResultSet,再关PreparedStatement 最后关Connection
res.close()
ps.close()
conn.close()
Mybatis:本是apache的一个开源项目iBatis
JDBC虽然解决了Java代码和数据库的解耦和问题,但是它过于繁琐,重复的代码太多,因此Mybatis实际上是对JDBC的数据库操作的封装,它使得开发者只需要关注SQL本身。
1、mybatis-config.xml :mybatis的核心配置文件,配置了Mybatis运行过程中所需要的全局性信息。
<?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"/>
<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="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
2、通过Mybatis核心配置文件mybatis-config.xml 构建SqlSessionFactory即会话工厂
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
3、由会话工厂获取SqlSession,操作数据库是通过SqlSession来完成的
SqlSession session = sqlSessionFactory.openSession();
try {
// do work
} finally {
session.close();
}
4、Mybatis底层自定义了Executor执行器接口操作数据库,Executor接口有两个实现,一个是基本执行器、一个是缓存执行器。
5、Mapped Statement也是Mybatis一个底层封装对象,它包装了Mybatis配置信息及sql映射信息等。Mapper.xml文件中一个sql对应一个Mapped Statement对象,sql的id即是Mapped statement的id。
<?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="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
6、 Mapped Statement对sql执行输入参数进行定义,包括简单类型、HashMap和自定义pojo,Executor通过Mapped Statement在执行sql前将输入的java对象映射至