JDBC->Dbutils(QueryRunner)->jdbcTemplate:工具
框架:整体解决方案
以前是硬编码高耦合,把SQL语句写在Java代码中,采取ORM(Object relation mapping)框架
javaBean----->DBRecords
Hibernate 全自动ORM全映射,把(编写sql,预编译,设置参数,执行SQL,封装结果等过程全部变成黑箱操作),意在消除SQL,不能优化SQL语言,不能定制sql语句,(HQL可以实现定制)
希望SQL语句交给开发人员编写,希望不失去灵活性
将编写SQL语句放在配置文件
SQL语句与Java编码分类:SQL是开发人员控制
MyBatis是半自动的持久层框架,轻量级的框架
在哪里找MyBatis
https://github.com/mybatis/mybatis-3/
MyBatis_Hello World
步骤:
1.首先在数据库中建立table
create table tbl_employee(
id int(11)primary key auto_increment,
last_name varcher(255),
gender char(1),
email varcher(255)
)
2.写一个与数据库相对应的Java类
public class Employee {
private Integer id;
private String lastname;
private String email;
private String gender;
gettrer 和setter方法生成
}
3.加入jar包
mybatis-3.4.jar
mybatis-connector.jar
log4j.jar
4.创建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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:8080/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="EmployeeMapper.xml"/> //将写好的sql映射在配置文件中,如果有包用/分割
</mappers>
</configuration>
5.在Java Test类中写如下代码
public class MybatisTest{
@Test
public void test(){
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession=sqlSessionFactory.openSession();
try{ Employee employee=sqlSession.selectOne("com.guigu.mybatis.EmployeeMapping.selectEmployee",1);
}finally{
sqlSession.close();}
}}
6.编写SQL语句EmployeeMapper.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="com.guigu.mybatis.EmployeeMapping">
<!--namespace为命名空间, id为唯一标识,resultType返回值类型用类全路径,#{id}从传递的参数中取出id 值>
<select id="selectEmployee" resultType="com.guigu.mybatis.Employee">
select id,last_name lastName,email,gender from tbl_employee where id = #{id}
</select>
</mapper>
注:1.全局配置文件,数据源
2.Sql映射文件配置了SQL语句,SQL封装规则
3.将Sql映射文件注册在全局配置文件中
4.写Java代码
全局配置文件–》 SqlSessionFactory–》 SqlSession–》select
最后别忘了而关闭
一个 SqlSession就是代表和数据库一次会话