mybatis入门基础(一)JDBC的简介以及Mybatis的入门程序

来源:互联网 发布:使命召唤mac 编辑:程序博客网 时间:2024/06/05 17:44

JDBC编程步骤以及其优缺点

JDBC程序

实现的是表查询的操作

Public static void main(String[] args) {            Connection connection = null;            PreparedStatement preparedStatement = null;            ResultSet resultSet = null;            try {                //加载数据库驱动                Class.forName("com.mysql.jdbc.Driver");                //通过驱动管理类获取数据库链接                connection =  DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "mysql");                //定义sql语句 ?表示占位符            String sql = "select * from user where username = ?";                //获取预处理statement                preparedStatement = connection.prepareStatement(sql);                //设置参数,第一个参数为sql语句中参数的序号(从1开始),第二个参数为设置的参数值                preparedStatement.setString(1, "王五");                //向数据库发出sql执行查询,查询出结果集                resultSet =  preparedStatement.executeQuery();                //遍历查询结果集                while(resultSet.next()){                    System.out.println(resultSet.getString("id")+"  "+resultSet.getString("username"));                }            } catch (Exception e) {                e.printStackTrace();            }finally{                //释放资源                if(resultSet!=null){                    try {                        resultSet.close();                    } catch (SQLException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                }                if(preparedStatement!=null){                    try {                        preparedStatement.close();                    } catch (SQLException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                }                if(connection!=null){                    try {                        connection.close();                    } catch (SQLException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                }            }        }

JDBC的编程步骤
1、加载数据库驱动
2、创建并获取数据库链接
3、创建jdbc statement对象
4、设置sql语句
5、设置sql语句中的参数(使用preparedStatement)
6、通过statement执行sql并获取结果
7、对sql执行结果进行解析处理
释放资源(resultSet、preparedstatement、connection)

JDBC的问题总结
1、数据库链接创建、释放频繁造成系统资源浪费从而影响系统性能,如果使用数据库链接池可解决此问题。
2、Sql语句在代码中硬编码,造成代码不易维护,实际应用sql变化的可能较大,sql变动需要改变java代码。
3、使用preparedStatement向占有位符号传参数存在硬编码,因为sql语句的where条件不一定,可能多也可能少,修改sql还要修改代码,系统不易维护。
4、对结果集解析存在硬编码(查询列名),sql变化导致解析代码变化,系统不易维护,如果能将数据库记录封装成pojo对象解析比较方便。


Mybatis简介

yBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis,实质上Mybatis对ibatis进行一些改进。
MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码。
Mybatis通过xml或注解的方式将要执行的各种statement(statement、preparedStatemnt、CallableStatement)配置起来,并通过java对象和statement中的sql进行映射生成最终执行的sql语句,最后由mybatis框架执行sql并将结果映射成java对象并返回。

Mybatis架构

这里写图片描述

1、mybatis配置
SqlMapConfig.xml,此文件作为mybatis的全局配置文件,配置了mybatis的运行环境等信息。
mapper.xml文件即sql映射文件,文件中配置了操作数据库的sql语句。此文件需要在SqlMapConfig.xml中加载。

2、通过mybatis环境等配置信息构造SqlSessionFactory即会话工厂
3、由会话工厂创建sqlSession即会话,操作数据库需要通过sqlSession进行。
4、mybatis底层自定义了Executor执行器接口操作数据库,Executor接口有两个实现,一个是基本执行器、一个是缓存执行器。
5、Mapped Statement也是mybatis一个底层封装对象,它包装了mybatis配置信息及sql映射信息等。mapper.xml文件中一个sql对应一个Mapped Statement对象,sql的id即是Mapped statement的id。
6、Mapped Statement对sql执行输入参数进行定义,包括HashMap、基本类型、pojo,Executor通过Mapped Statement在执行sql前将输入的java对象映射至sql中,输入参数映射就是jdbc编程中对preparedStatement设置参数。
7、Mapped Statement对sql执行输出结果进行定义,包括HashMap、基本类型、pojo,Executor通过Mapped Statement在执行sql后将输出结果映射至java对象中,输出结果映射过程相当于jdbc编程中对结果的解析处理过程。

Mybatis入门程序

以下入门程序实在没有MVC架构下的入门程序

需求:

实现以下功能:
根据用户id查询一个用户信息
根据用户名称模糊查询用户信息列表
添加用户
更新用户
删除用户

第一步:创建工厂
第二步:加入jar包
第三步:配置log4j.properties

在classpath下创建log4j.properties如下:

# Global logging configurationlog4j.rootLogger=DEBUG, stdout# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
第四步:配置SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <!-- 和spring整合后 environments配置将废除-->    <environments default="development">        <environment id="development">        <!-- 使用jdbc事务管理-->            <transactionManager type="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="mysql" />            </dataSource>        </environment>    </environments></configuration>

SqlMapConfig.xml是mybatis核心配置文件,上边文件的配置内容为数据源、事务管理。

第五步:配置po类

Po类作为mybatis进行sql映射使用,po类通常与数据库表对应,User.java如下:

Public class User {    private int id;    private String username;// 用户姓名    private String sex;// 性别    private Date birthday;// 生日    private String address;// 地址get/set……
第六步:在classpath下的sqlmap目录下创建sql映射文件Users.xml:

namespace :命名空间,用于隔离sql语句,后面会讲另一层非常重要的作用。

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="test"><!-- 根据id获取用户信息 -->    <select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User">        select * from user where id = #{id}    </select>    <!-- 自定义条件查询用户列表 -->    <select id="findUserByUsername" parameterType="java.lang.String"             resultType="cn.itcast.mybatis.po.User">       select * from user where username like '%${value}%'     </select></mapper>
第七步:加载映射文件

mybatis框架需要加载映射文件,将Users.xml添加在SqlMapConfig.xml,如下:

<mappers>        <mapper resource="sqlmap/User.xml"/></mappers>
第八步:测试程序:
public class Mybatis_first {    //会话工厂    private SqlSessionFactory sqlSessionFactory;    @Before    public void createSqlSessionFactory() throws IOException {        // 配置文件        String resource = "SqlMapConfig.xml";        InputStream inputStream = Resources.getResourceAsStream(resource);        // 使用SqlSessionFactoryBuilder从xml配置文件中创建SqlSessionFactory        sqlSessionFactory = new SqlSessionFactoryBuilder()                .build(inputStream);    }    // 根据 id查询用户信息    @Test    public void testFindUserById() {        // 数据库会话实例        SqlSession sqlSession = null;        try {            // 创建数据库会话实例sqlSession            sqlSession = sqlSessionFactory.openSession();            // 查询单个记录,根据用户id查询用户信息            User user = sqlSession.selectOne("test.findUserById", 10);            // 输出用户信息            System.out.println(user);        } catch (Exception e) {            e.printStackTrace();        } finally {            if (sqlSession != null) {                sqlSession.close();            }        }    }    // 根据用户名称模糊查询用户信息    @Test    public void testFindUserByUsername() {        // 数据库会话实例        SqlSession sqlSession = null;        try {            // 创建数据库会话实例sqlSession            sqlSession = sqlSessionFactory.openSession();            // 查询单个记录,根据用户id查询用户信息            List<User> list = sqlSession.selectList("test.findUserByUsername", "张");            System.out.println(list.size());        } catch (Exception e) {            e.printStackTrace();        } finally {            if (sqlSession != null) {                sqlSession.close();            }        }    }}
0 0
原创粉丝点击