MyBatis(1)

1.什么是框架?

        将基础的底层技术中操作起来繁琐重复的操作,封装起来以后形成的就是框架。

        提高效率,提高程序性能,提高程序可维护行【后期的代码维护和升级】。

2.MVC的架构【设计】

        几乎所有的软件都是基于MVC架构

        M---模型【数据封装,数据模型】

        V---视图【采集数据,展示数据】

        C---控制器【处理业务逻辑】

        项目中体现出MVC架构

项目分3层

        控制层【web层】---用来做数据的导航【Servlet、Struts2、SpringMVC】

        业务层---用来处理相关功能的具体实现业务【Spring】

        数据访问层【数据持久层】---用来访问数据库数据【JDBC、Hibernate、MyBatis】

三大框架:SSM---SpringMVC Spring MyBatis

                  SSH---Struts2 Spring Hibernate

3.什么是MyBatis?

MyBatis是一个基于ORM数据访问层框架

        【数据访问层---数据库操作技术---JDBC---MyBatis】

            ORM---对象关系映射
            O---JAVA对象
            R---关系型数据库【MySQL】
            M---映射【JAVA对象在关系型数据库中有对应的元素】


       我们在访问数据库的时候所编写的都是Java程序,Java程序只认识Java对象,而我们所访问的数据库大多数都是关系型数据库,那么这时Java程序要想访问关系型数据库,那么就需要将Java对象转换成关系型数据,才能被数据库认识。
       这时我们可以认为一个Java类就是关系型数据库中的一张数据表,Java类中的成员变量是数据库表中的一个列,Java类创建的Java对象就是数据库表中的一行记录。这时将Java对象对应成为数据库表记录的过程就是对象关系映射【ORM】。
    我们只需要操作我们熟悉的java对象,就可以完成数据库表记录的更新。
 

 4.为什么要使用MyBatis?

        1.为了简化数据库访问操作,提高开发的效率,提升项目的性能,增加程序的可维护性

        2.当无门使用Java程序控制Java对象的时候,数据库中的数据库表记录回随之变化

        【将原来通过java程序访问数据库表的操作,简化成通过java程序访问java对象】

使用MyBatis框架【完成添加、修改、删除、查询】

1.准备数据库表

create table t_student(
stu_id int primary key auto_increment,
stu_name varchar(20),
stu_pass varchar(20),
stu_age int,
stu_address varchar(30)
);

2.创建项目,导入依赖包,完善结构

 <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>



    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
    </dependency>

3.参考数据库表,创建javaBean类

package com.zxc.student.bean;

public class SrtudentBean {
    private int stuid;
    private String stuname;
    private String stupass;
    private int stuage;
    private String stuaddress;

    public int getStuid() {
        return stuid;
    }

    public void setStuid(int stuid) {
        this.stuid = stuid;
    }

    public String getStuname() {
        return stuname;
    }

    public void setStuname(String stuname) {
        this.stuname = stuname;
    }

    public String getStupass() {
        return stupass;
    }

    public void setStupass(String stupass) {
        this.stupass = stupass;
    }

    public int getStuage() {
        return stuage;
    }

    public void setStuage(int stuage) {
        this.stuage = stuage;
    }

    public String getStuaddress() {
        return stuaddress;
    }

    public void setStuaddress(String stuaddress) {
        this.stuaddress = stuaddress;
    }
}

 4.在src/main/resources编写数据库链接字符串的配置文件

mydrivername=com.mysql.jdbc.Driver
myurl=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8
myusername=root
mypassword=123456

5.创建数据库访问接口

        接口名称通常是Mapper结尾,例如:StudentMapper

        保存数据库访问接口的程序包使用mapper命名

package com.zxc.student.mapper;

import com.zxc.student.bean.StudentBean;

import java.util.List;

public interface StudentMapper {
    /**
     * 添加数据
     */
     boolean insertStudent(StudentBean studentBean);

    /**
     * 修改数据
     */
    boolean updateStudent(StudentBean studentBean);

    /**
     * 删除数据
     */
    boolean deleteStudentById(int stuid);

    /**
     * 根据id查询数据
     */
    StudentBean selectStudentById(int stuid);

    /**
     * 查询所有数据
     */
    List<StudentBean> selectStudent();

}

6.在src/main/resources编写数据库访问接口对应的sql映射文件,sql映射文件的名称与数据库访问接口名称一样,用".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.zxc.student.mapper.StudentMapper">
    <insert id="insertStudent" parameterType="com.zxc.student.bean.StudentBean">
        insert into t_student values(null,#{stuname},#{stupass},#{stuaghe},#{stuaddress});
    </insert>

    <update id="updateStudent" parameterType="com.zxc.student.bean.StudentBean">
        update t_student set stu_name=#{stuname},stu_pass=#{stupass},stu_age=#{stuage},stu_address=#{stuaddress} where stu_id=#{stuid};
    </update>

    <delete id="deleteStudentById" parameterType="java.lang.Integer">
        delete from t_student where stu_id=#{stuid};
    </delete>

    <resultMap id="stumap" type="com.zxc.student.bean.StudentBean">
    <id column="stu_id" property="stuid"></id>
    <result column="stu_name" property="stuname"></result>
    <result column="stu_pass" property="stupass"></result>
    <result column="stu_age" property="stuage"></result>
    <result column="stu_address" property="stuaddress"></result>
    </resultMap>

   <select id="selectStudentById" parameterType="java.lang.Integer" resultMap="stumap">
       select * from t_studentt where stu_id=#{stuid};
   </select>

    <select id="selectStudent"  resultMap="stumap">
        select * from t_student;
    </select>
</mapper>

7.在src/main/resources编写MyBatis配置文件

        名称建议使用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>
    <!-- 配置引入数据库链接字符串的资源文件 -->
    <properties resource="mydate.properties"></properties>
    <!-- 配置mybatis默认的链接数据库的环境 -->
    <environments default="development">
        <environment id="development">
            <!-- 配置事务管理器 -->
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${mydrivername}"/>
                <property name="url" value="${myurl}"/>
                <property name="username" value="${myusername}"/>
                <property name="password" value="${mypassword}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="StudentMapper.xml"></mapper>
    </mappers>
</configuration>

8.测试代码【读MyBatis配置文件,创建数据访问接口对象,调用接口方法】

package com.zxc.student.test;

import com.zxc.student.bean.StudentBean;
import com.zxc.student.mapper.StudentMapper;
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 sun.security.util.Resources_sv;

import java.util.List;

public class StudentMain {
    /**
     * 添加测试
     */
    public static void testInsert() {
        SqlSession sqlSession=null;
        try {

            //读取MyBatis配置文件。
            SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
            sqlSession=sqlSessionFactory.openSession();
            //创建数据访问接口对象
            StudentMapper studentMapper= (StudentMapper)sqlSession.getMapper(StudentMapper.class);
            //调用接口方法
            StudentBean studentBean=new StudentBean();
            studentBean.setStuname("zhangsan");
            studentBean.setStupass("123456");
            studentBean.setStuage(25);
            studentBean.setStuaddress("西安");
            studentMapper.insertStudent(studentBean);
            //提交sqlsession
            sqlSession.commit();
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }


    }

    /**
     * 修改测试
     */
    public static void testUpdate(){
        SqlSession sqlSession=null;
        //读取MyBatis配置文件
        try {
            SqlSessionFactory sqlSessionFactory= new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
            sqlSession=sqlSessionFactory.openSession();
            StudentBean studentBean=new StudentBean();
            studentBean.setStuid(20);
            studentBean.setStuname("赵六");
            studentBean.setStupass("255833");
            studentBean.setStuage(15);
            studentBean.setStuaddress("渭南");
            sqlSession.update("com.zxc.student.mapper.StudentMapper.updateStudent",studentBean);
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }
    }


    public static void testDelete(){
        SqlSession sqlSession=null;
        try{
            //读取MyBatis文件
            SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
            sqlSession= sqlSessionFactory.openSession();
            sqlSession.delete("com.zxc.student.mapper.StudentMapper.deleteStudentById",18);
            sqlSession.commit();
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }
    }

    public static void testSelectOne(){
        SqlSession sqlSession=null;
        try{
            SqlSessionFactory sqlSessionFactory=  new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
            sqlSession=sqlSessionFactory.openSession();
            StudentBean studentBean=(StudentBean)sqlSession.selectOne("com.zxc.student.mapper.StudentMapper.selectStudentById",20);
            System.out.println("name="+studentBean.getStuname());
            sqlSession.commit();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }
    }

    public static void testSelectAll(){
        SqlSession sqlSession=null;
        try{
            SqlSessionFactory sqlSessionFactory=  new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
            sqlSession=sqlSessionFactory.openSession();
            List<StudentBean> studentBeanList=sqlSession.selectList("com.zxc.student.mapper.StudentMapper.selectStudent");
            for (StudentBean studentBean:studentBeanList){
                System.out.println("name="+studentBean.getStuname());
            }
            sqlSession.commit();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }
    }
    public static void main(String[] args) {
        //testInsert();
        //testUpdate();
        //testDelete();
        //testSelectOne();
        testSelectAll();
    }
}

总结:读MyBatis配置文件,【mybatis-config.xml】

 SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));

得到SqlSession对象

SqlSession sqlSession=sqlSessionFactory.openSession();

1.得到数据访问接口对象sqlSession.getMapper(数据访问接口.class)

StudentMapper studentMapper=(StudentMapper)sqlSession.getMapper(StudentMapper.class);

数据访问接口对象调用.insertStudent/updateStudent/deleteStudent......

2.通过SqlSession对象直接调用

        int insert("数据访问接口包名+接口名+方法名" ,方法参数);

        int update("数据访问接口包名+接口名+方法名" ,方法参数);

        int delete("数据访问接口包名+接口名+方法名" ,方法参数);

        Object  selectOne("数据访问接口包名+接口名+方法名" ,方法参数);

        List<Object> selectList("数据访问接口包名+接口名+方法名" ,方法参数);

........

        提交sqlsession

sqlSession.commit();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值