20191231 - mybatis review the first day

jdbc program
run jdbc program, need to join the jar package
database-driven package (MySQL)
IDEA in a jar introduced
in the project folder create a lib folder, specialized storage jar package
and then file -> project structure to find modules, found dependencies, adding an entire lib go, we can find our import jar package can double-click to open the point, then explain this jar package is imported correctly.
Simple naming
project name all lowercase
package name all lowercase
class name capitalize the first letter of each word
method name hump nomenclature
company named "com. Company name Project name Module name ...."
Domain name suffix
international domain name (international top-level domain-names , referred to iTDs), also known as the international top-level domain. This is also the earliest and most extensive use of the domain name. For example, represents the industrial and commercial enterprises .com, creativity and innovation represent .xyz three-dimensional space, showing .net network provider, it represents a non-profit organization .org, represents the top-end .top, public, well-known .pub indicating good fortune, enthusiastic, hard-working .red.
IDEA create class templates and template methods
in order to open the File-> settings-> Editor-> File and Code Templates-> Includes
input template class comment

/**
 * @Classname ${NAME}
 * @Description TODO
 * @Date ${DATE} ${TIME}
 * @Created by ${USER}
 */

IDEA connection with github
github link with the idea

Native jdbc program
Here Insert Picture Description

package cn.mmz.mybatis.jdbc;

import java.sql.*;

/**
 * @Classname JdbcTest
 * @Description 通过jdbc,总结其中的问题
 * @Date 2019/12/31 17:17
 * @Created by mmz
 */
public class JdbcTest {
    public static void main(String[] args) {
        //数据库连接
        Connection connection = null;
        //预编译的statement 。使用预编译的Statement提高数据库的性能
        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", "password");
            //定义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();
                }
            }

        }

    }
}

问题总结
1)数据库连接的时候创建,不使用的时候就释放,相当于数据库频繁连接与关闭,造成数据库资源浪费,影响数据库性能
解决方案:使用数据库连接池

2)需求会变,sql中定义的语句条件会根据需求进行改变,硬编码不利于系统的维护
解决方案:使用配置文件xml中,不需要对java代码进行编写

  1. 向preparedStatement中设置参数的时候,对占位符号位置和设置变量,硬编码在java代码中
    解决方案:将sql语句及参数也放在xml中

4)从resultSet遍历结果集数据,存在硬编码,将获取表的字段进行硬编码
解决方案:结果自动映射成java对象,不需要在代码中硬编码了

mybatis框架
持久层框架,apache顶级项目。解决了上面的问题。
mybatis托管到google上,最后托管到github上

mybatis使程序员将主要精力放在sql上,通过mybatis的映射方式,自由灵活生成满足需求的sql语句

mybatis可以将向preparedStatement中的输入参数自动输出映射,将查询结果集灵活映射出java对象

mybatis框架图
Here Insert Picture Description

入门程序
根据id主键查询用户信息
根据用户名称模糊查询用户信息
添加用户
删除用户
更新用户

添加jar包与运行环境

创建log4j文件
作为输出日志


根据用户ID查询信息
首先配置好SqlMapConfig.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>
    <!-- 和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="password" />
            </dataSource>
        </environment>
    </environments>

</configuration>

创建一个映射文件,配置sql语句
User.xml 但是mapper代理却不是这个命名方式是UserMapper.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="test">
</mapper>

简单讲解这个User.xml文件
namespace 命名空间,作用就是对sql进行分类化管理。理解sql隔离
使用mapper开发,namespace有特殊重要的作用

通过select标签可以进行查询
id:用于标识映射文件的sql,成为statement的id
将来sql会封装到mapperStatement中
#{}表示占位符

paratmeterType 是指定输入参数的类型
#{id} 其中的id表示接入输入的参数,参数名称就是id,如果输入是简单类型,#{}中的参数的名称可以任意,可以写value或其他都行

resultType 是指定输出结果的类型,select指定resultType表示将单条记录映射成为java对象
我们这里就需要定义一个pojo类

pojo
POJO(Plain Ordinary Java Object)简单的Java对象,实际就是普通JavaBeans,是为了避免和EJB混淆所创造的简称。使用POJO名称是为了避免和EJB混淆起来, 而且简称比较直接. 其中有一些属性及其getter setter方法的类,没有业务逻辑,有时可以作为VO(value -object)或dto(Data Transform Object)来使用.当然,如果你有一个简单的运算属性也是可以的,但不允许有业务方法,也不能携带有connection之类的方法。

建立一个pojo的包,在里面生成一个User类,里面的属性要和数据库返回的结果集一一对应

Then create getter / setter objects

package cn.mmz.mybatis.pojo;

import java.util.Date;

/**
 * @Classname User
 * @Description pojo User类
 * @Date 2019/12/31 23:32
 * @Created by mmz
 */
public class User {
        private int id;
        private String username;// 用户姓名
        private String sex;// 性别
        private Date birthday;// 生日

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    private String address;// 地址
}

Last User.xml file

<?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="test">
    <select id="findUserById" parameterType="int" resultType="cn.mmz.mybatis.pojo.User">
        select * from user where id = #{id}
    </select>
</mapper>

In the mapping file written in sqlmapconfig load file written user.xml

  <mappers>
        <mapper resource="sqlmap/User.xml"></mapper>
    </mappers>

Writing programs

MybatisFirst.java created file, the file is introduced junit unit test
1) to create a session factory incoming mybatis profile information
mybatis has a resource class, a file stream can be obtained by this class

String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //创建会话工厂,
        SqlSessionFactory sqlSessionFactory  = new SqlSessionFactoryBuilder().build(inputStream);

2) obtained by plant sqlsession

        SqlSession sqlSession = sqlSessionFactory.openSession();

3) by operation of a database sqlsession
first parameter: id mapping file = namespace + statement.id the statement
parameters match the specified paramter and mapping files of parameter: the second parameter

        User user =  sqlSession.selectOne("test.findUserById",1);
        System.out.println(user);

4) release of resources

        sqlSession.close();

Total MybatisFirst.java

package cn.mmz.mybatis.first;

import cn.mmz.mybatis.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;

/**
 * @Classname MybatisFirst
 * @Description 入门程序
 * @Date 2019/12/31 23:37
 * @Created by mmz
 */
public class MybatisFirst {
    //根据id查询用户信息
    @Test
    public void findUserById() throws Exception{
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //创建会话工厂,
        SqlSessionFactory sqlSessionFactory  = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession sqlSession = sqlSessionFactory.openSession();

        User user =  sqlSession.selectOne("test.findUserById",1);
        System.out.println(user);

        sqlSession.close();
    }
}

Running time reported a mistake, you need to config folder as source file and

Here Insert Picture Description

Published 657 original articles · won praise 39 · views 60000 +

Guess you like

Origin blog.csdn.net/qq_36344771/article/details/103786236