(二)Mybatis總結之經過Dao層與數據交互

Mybatis概述

定義: Mybatis是一個支持普通sql查詢,存儲過程和高級映射的優秀持久層框架。java

  • Mybatis是(半自動的)跟數據庫打交道的orm(object relationship mapping 對象 關係 映射)框架.
  • MyBatis 是一個優秀的基於 Java 的持久層框架,它內部封裝了 JDBC(Java數據庫鏈接),使開發者只需關注 SQL 語句自己,而不用再花費精力去處理諸如註冊驅動、建立 Connection、配置 Statement 等繁雜過程。

對框架的粗淺理解

框架做用:解耦,即下降耦合度,減小開發時間(偷懶)的東西,可是並不表明框架的運行速度很高。如下兩個原則是框架的重要思想。mysql

重構原則:事不過三,三則重構(有三個地方代碼重複)sql

  • 「高內聚低耦合」作法:
    • 寫且只寫一次
    • 一個類只作一種事
    • 一個方法只作一件事

Mybatis的特色

  • Sql語句寫在XML文件中,實現了代碼與Sql分離,下降耦合度
  • 半自動的mybatis更利於開發人員設計Sql語句
  • 簡單易學
  • 支持動態Sql

Mybatis配置和初步使用

Mybatis經過dao層與數據交互

1.pom.xml導入相應依賴數據庫

<!-- mybatis核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <!-- mysql驅動包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
        </dependency>

Maven要按照大佬博客說的配置,接下來file-->settings-->Maven-->Maven home directory設置爲Maven安裝包路徑 而後user settings file 設置爲安裝包路徑\conf\settings.xml,不然導依賴失敗apache

2.mybatis核心配置mybatis-config.xmlsession

<?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="mysql.properties"/>
    
    <settings>
        <!--全局性設置懶加載。若是設爲‘false’,則全部相關聯的都會被初始化加載,默認值爲false-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--當設置爲‘true’的時候,懶加載的對象可能被任何懶屬性所有加載。不然,每一個屬性都按需加載。默認值爲true-->
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>
    <typeAliases>
        <!-- 其實就是將bean的替換成一個短的名字-->
        <typeAlias type="com.qf.pojo.User" alias="User"/>
    </typeAliases>
    <!--對事務的管理和鏈接池的配置-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED"><!--POOLED:使用Mybatis自帶的數據庫鏈接池來管理數據庫鏈接-->
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--mapping文件路徑配置-->
    <mappers>
        <mapper resource="mapper/UserMapper.xml"/>
    </mappers>

</configuration>

3.配置mysql.propertiesmybatis

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/demo1?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
jdbc.username=root
jdbc.password=123456

其中?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8是爲了防止亂碼而加的app

4.配置映射文件,如下有增刪改查sql語句框架

<?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.qf.mybatisdemo.pojo.User">
 
    <!--部分查詢->
    <select id="getUserByName" resultType="com.qf.mybatisdemo.pojo.User" parameterType="java.lang.String">
        SELECT * FROM USER where username = #{username}
    </select>
   
    <insert id="addUser" parameterType="com.qf.mybatisdemo.pojo.User" >
        insert into USER(username,age) values(#{username},#{age})
    </insert>

    <update id="updateUserAge" parameterType="com.qf.mybatisdemo.pojo.User">
        update user set age=#{age} where username=#{username}
    </update>

    <delete id="deleUser" parameterType="com.qf.mybatisdemo.pojo.User">
        delete from user where username=#{username} and age=#{age}
    </delete>
</mapper>

5.建立與數據庫表的字段對應的實體類ide

package com.qf.mybatisdemo.pojo;

public class User {
    String username;
    int age;

    public String getUsername() {
        return username;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", age=" + age +
                '}';
    }
}

6.建立會話(dao層與數據庫交互數據的介質)接口

package com.qf.mybatisdemo.dao;

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 java.io.IOException;
import java.io.Reader;

public class BaseDao {
    public SqlSession getSqlSession() {
        String fileName = "mybatis-config.xml";
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}

7.增刪改查接口

package com.qf.mybatisdemo.dao;

import com.qf.mybatisdemo.pojo.User;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class UserDao extends BaseDao{
    User user;

    /**
     * 根據名字查詢
     */
    public User getUserByName(String userName) {
        SqlSession sqlSession = this.getSqlSession();
        user = sqlSession.selectOne("getUserByName",userName);
        return user;
    }


    /**
     * 增
     */
    public int addUser(User user) {
        int count = 0;
        SqlSession sqlSession = this.getSqlSession();
        count = sqlSession.insert("addUser",user);
        sqlSession.commit();
        return count;
    }

    /**
     * 改
     */
    public int updateUserAge(User user) {
        int count= 0;
        SqlSession sqlSession = this.getSqlSession();
        count = sqlSession.update("updateUserAge",user);
        sqlSession.commit();
        return count;
    }

    /**
     * 刪除
     */
    public int deleUser(User user) {
        int count= 0;
        SqlSession sqlSession = this.getSqlSession();
        count = sqlSession.update("deleUser",user);
        sqlSession.commit();
        return count;
    }
}

8.測試類

package com.qf.mybatisdemo;

import com.qf.mybatisdemo.dao.UserDao;
import com.qf.mybatisdemo.pojo.User;
import org.junit.Test;

import javax.jws.soap.SOAPBinding;


public class TestMybatis {
    UserDao userDao;
    /**
     * 根據名字查詢
     */
    @Test
    public void getUserByName () {
        User user;
        user = userDao.getUserByName("張三");
        System.out.println(user);
    }


    public static void main(String[] args) {
            UserDao userDao = new UserDao();

        /**
         * 增
         */
//            User user = new User();
//            int count = 0;
//            user.setAge(18);
//            user.setUsername("小風");
//            count = userDao.addUser(user);
//            System.out.println(count);

        /**
         * 改
         */
//        User user = new User();
//        int count = 0;
//        user.setAge(20);
//        user.setUsername("小風");
//        count = userDao.updateUserAge(user);
//        System.out.println("新的"+count);



        /**
         * 刪
         */
        User user = new User();
        int count = 0;
        user.setAge(20);
        user.setUsername("小風");
        count = userDao.deleUser(user);
        System.out.println(count);
    }
}
相關文章
相關標籤/搜索