1. 程式人生 > >maven搭建專案--實現mybatis增刪改差、一對多及一對一關係

maven搭建專案--實現mybatis增刪改差、一對多及一對一關係

1、建立maven專案

這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

2、配置pom.xml,引入相應的jar包

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId
>
com.danni</groupId> <artifactId>mybatis-maven</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId
>
<version>3.4.5</version> </dependency> <!-- java連線資料庫的包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-Java</artifactId> <version>5.1.6</version
>
</dependency> <!-- 日誌包 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency> </dependencies> </project>

3、在Eclipse安裝mybatis generator自動生成工具

(1)下載mybatis生成架包工具MyBatis_Generator_1.3.1.zip,解壓jar包把features、plugins資料夾下的架包分別拷貝到eclipse安裝目錄下的features、plugins資料夾(複製和替換eclipse原有的這兩個資料夾)。然後重啟eclipse。
這裡寫圖片描述

(2)在pom.xml中新增mybatis-generator-maven-plugin的jar包

<!-- mybatis generator自動生成jar包 -->
<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.2</version>
    <type>maven-plugin</type>
</dependency>

(3)配置generator.xml檔案

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!-- 資料庫驅動包位置 (改成自己存放的具體路徑) -->
    <classPathEntry location="D:/softwaretools/someNeeded/mysql-connector-java-5.1.34.jar" /> 

    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <!-- 資料庫連結URL、使用者名稱、密碼 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/student" userId="root" password="root"> </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- 生成模型的包名和位置 ,targetPackage:包名,targetProject:你的專案名-->
        <javaModelGenerator targetPackage="com.danni.model.entity" targetProject="mybatis-maven">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- 生成的對映檔案包名和位置 -->
        <sqlMapGenerator targetPackage="com.danni.model.dao" targetProject="mybatis-maven">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!-- 生成DAO的包名和位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.danni.model.dao" targetProject="mybatis-maven">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!-- tableName:資料庫中的表名,domainObjectName:表名對應的類名 -->
        <table tableName="admins" domainObjectName="Admins" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
        <table tableName="employee" domainObjectName="Employee" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
        <table tableName="department" domainObjectName="Department" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
    </context>
</generatorConfiguration>

(4)選中generator.xml,右鍵選擇Generate MyBatis/IBATIS Artifacts,點選即可生成程式碼檔案。

這裡寫圖片描述

4、編寫資料庫和日誌的properties檔案

這裡寫圖片描述
jdbc.properties

driver = com.mysql.jdbc.Driver
url = jdbc:mysql:///student?characterEncoding=utf-8
username = root
password = root

log4j.properties

log4j.rootLogger=DEBUG, Console 
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
#log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n 
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG 

5、配置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檔案 -->
    <properties resource="jdbc.properties"/>

    <settings>
        <setting name="logImpl" value="LOG4J" />
        <!-- 開啟二級快取(總開關) -->
        <setting name="cacheEnabled" value="true"/>         
    </settings>

    <!-- 配置別名 -->
    <typeAliases>
        <typeAlias type="com.danni.model.entity.Admins" alias="Admins"/>
        <typeAlias type="com.danni.model.entity.Department" alias="Department"/>
        <typeAlias type="com.danni.model.entity.Employee" alias="Employee"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com/danni/model/dao/AdminsMapper.xml" />
        <mapper resource="com/danni/model/dao/DepartmentMapper.xml" />
        <mapper resource="com/danni/model/dao/EmployeeMapper.xml" />
    </mappers>
</configuration>

6、建立工具類來獲取SqlSession

package org.danni.utils;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class SqlSessionUtils {

    private static SqlSessionFactory sqlSessionFactory;
    private static SqlSession sqlSession;

    public static SqlSessionFactory openSessionFactory() {
        if (sqlSessionFactory == null) {
            try {
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sqlSessionFactory;
    }

    public static SqlSession openSession() {
        if (sqlSession == null) {
            sqlSession = openSessionFactory().openSession();
        }
        return sqlSession;
    }
}

這裡寫圖片描述

7、建立AdminsTest測試類來了解mybatis用法

AdminsTest:記得要提交事務

package com.danni.test;

import org.apache.ibatis.session.SqlSession;
import org.danni.utils.SqlSessionUtils;

import com.danni.model.dao.AdminsMapper;
import com.danni.model.entity.Admins;

public class AdminsTest {
    // 增
    public static void add() {
        // 開啟sqlSession
        SqlSession sqlSession = SqlSessionUtils.openSession();

        Admins admins = new Admins();
        admins.setAdminname("小紅");
        admins.setAdminpwd("123");

        // 法一:直接呼叫
        Integer row = sqlSession.insert("com.danni.model.dao.AdminsMapper.insert", admins);
        sqlSession.commit();

        System.out.println(row);
    }

    // 增
    public static void add1() {
        // 開啟sqlSession
        SqlSession sqlSession = SqlSessionUtils.openSession();

        Admins admins = new Admins();
        admins.setAdminname("小白");
        admins.setAdminpwd("123");

        // 法二:採用介面代理的方式(然後就直接呼叫介面中相應的方法,他會去實現類也就對應的xml中找對應的方法)
        AdminsMapper adminsDao = sqlSession.getMapper(AdminsMapper.class);
        Integer row = adminsDao.insert(admins);
        // 提交事務
        sqlSession.commit();
        System.out.println(row);
    }

    // update
    public static void update() {
        SqlSession sqlSession = SqlSessionUtils.openSession();

        // 因為update,因此需要設定id,根據id進行更新
        Admins admins = new Admins();
        admins.setAdminname("呵呵");
        admins.setAdminpwd("123");
        admins.setAid(11);

        AdminsMapper adminsDao = sqlSession.getMapper(AdminsMapper.class);
        adminsDao.updateByPrimaryKey(admins);
        // 提交事務
        sqlSession.commit();
    }


    public static void main(String[] args) {
        // add();
        // add1();
        update();
    }
}

8、一對一關係

(1)修改Employee.java檔案:

public class Employee implements Serializable{
    private Integer eid;
    private String ename;
    private String esex;
    private Department department;
    //get和set方法不貼出來了,自己補全
}

(2)修改EmployeeMapper.xml檔案:需要把sql語句中對應的物件中原來的did全部換成department.did
這裡寫圖片描述

<?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.danni.model.dao.EmployeeMapper">

  <resultMap id="BaseResultMap" type="com.danni.model.entity.Employee">
    <id column="eid" jdbcType="INTEGER" property="eid" />
    <result column="ename" jdbcType="VARCHAR" property="ename" />
    <result column="esex" jdbcType="VARCHAR" property="esex" />

    <!-- select:去department中根據id查詢,column:表明關聯的依據 -->
    <association property="department" column="did" select="com.danni.model.dao.DepartmentMapper.selectByPrimaryKey"></association>
  </resultMap>

  <sql id="Base_Column_List">
    eid, ename, esex, did
  </sql>

  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from employee
    where eid = #{eid,jdbcType=INTEGER}
  </select>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from employee
    where eid = #{eid,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.danni.model.entity.Employee">
    insert into employee (eid, ename, esex, 
      did)
    values (#{eid,jdbcType=INTEGER}, #{ename,jdbcType=VARCHAR}, #{esex,jdbcType=VARCHAR}, 
      #{department.did,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="com.danni.model.entity.Employee">
    insert into employee
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="eid != null">
        eid,
      </if>
      <if test="ename != null">
        ename,
      </if>
      <if test="esex != null">
        esex,
      </if>
      <if test="did != null">
        did,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="eid != null">
        #{eid,jdbcType=INTEGER},
      </if>
      <if test="ename != null">
        #{ename,jdbcType=VARCHAR},
      </if>
      <if test="esex != null">
        #{esex,jdbcType=VARCHAR},
      </if>
      <if test="did != null">
        #{department.did,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.danni.model.entity.Employee">
    update employee
    <set>
      <if test="ename != null">
        ename = #{ename,jdbcType=VARCHAR},
      </if>
      <if test="esex != null">
        esex = #{esex,jdbcType=VARCHAR},
      </if>
      <if test="did != null">
        did = #{department.did,jdbcType=INTEGER},
      </if>
    </set>
    where eid = #{eid,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.danni.model.entity.Employee">
    update employee
    set ename = #{ename,jdbcType=VARCHAR},
      esex = #{esex,jdbcType=VARCHAR},
      did = #{department.did,jdbcType=INTEGER}
    where eid = #{eid,jdbcType=INTEGER}
  </update>
</mapper>

(3)測試類EmpDepartTest:

public class EmpDepartTest {

    // 查詢職工,會通知查詢出職工在的部門物件
    public static void queryEmpByDid() {
        SqlSession sqlSession = SqlSessionUtils.openSession();
        EmployeeMapper employeeDao = sqlSession.getMapper(EmployeeMapper.class);
        Employee employee = employeeDao.selectByPrimaryKey(10);
        System.out.println(employee.getEname() + " " + employee.getDepartment().getDepartname());
    }

    public static void main(String[] args) {
        queryEmpByDid();
    }
}

9、多對一關係

一個部門對應多個員工。因此在部門中增加員工集合作為它的屬性
(1)修改Department.java

public class Department implements Serializable{
    private Integer did;
    private String departname;
    private List<Employee> empLists;
    //get和set方法自己補,我就不貼出來了
}

(2)修改DepartmentMapper.xml的結果對映

<resultMap id="BaseResultMap" type="com.danni.model.entity.Department">
    <id column="did" jdbcType="INTEGER" property="did" />
    <result column="departname" jdbcType="VARCHAR" property="departname" />

    <!-- 一對多關係:去員工中查詢did為某個值的員工物件 -->
    <collection property="empLists" column="did" select="com.danni.model.dao.EmployeeMapper.selectByDid"></collection>
  </resultMap>

(2)員工中新增selectByDid方法
EmployeeMapper.java:先去介面中新增對應方法宣告
EmployeeMapper.xml:增加對應的實現

 <select id="selectByDid" parameterType="int" resultType="BaseResultMap">
    select * from employee where did = #{did} 
 </select>

(3)編寫測試類中對應方法

// 查詢某個部門的全部員工(查詢部門的時候同時會把屬於這個部門的所欲員工集合查詢出來,就達到了一對多的關係)
public static void queryDepartEmps() {
    SqlSession sqlSession = SqlSessionUtils.openSession();
    DepartmentMapper departmentMapper = sqlSession.getMapper(DepartmentMapper.class);
    Department department = departmentMapper.selectByPrimaryKey(3);
    System.out.println(department.getEmpLists().size());
}

public static void main(String[] args) {
    // queryEmpByDid();
    queryDepartEmps();
}

10、分頁

(1)在EmployeeMapper.java介面中新增對應方法宣告

List<Employee> queryByPage(Map<String, Integer> map);

(2)在EmployeeMapper.xml中新增實現方法
注意:這裡我傳遞的是一個map集合,集合的鍵的名字必須和測試類中map中的見得名字要對應相等

<select id="queryByPage" parameterType="map" resultMap="BaseResultMap">
    select * from employee limit #{startNum},#{pageSize}
</select>

(3)新增對應測試類

// 分頁(把頁碼作為引數)
public static void queryByPage(Integer pageIndex) {
    SqlSession sqlSession = SqlSessionUtils.openSession();
    EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);

    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("startNum", (pageIndex-1)*3);       //limit的第一個引數
    map.put("pageSize", 3);                     //limit的第二個引數
    List<Employee> empLists = employeeMapper.queryByPage(map);
    System.out.println("");
}

public static void main(String[] args) {
    // queryEmpByDid();
    // queryDepartEmps();
    queryByPage(2);
}

11、排序,$符號的使用

(1)首先在介面中定義方法

List<Employee> queryBySort(String name);

(2)在實現類中新增相應的實現方法

<!-- 注意:這裡一定要使用value,他是預設的,不然就找不到 -->
<select id="queryBySort" parameterType="string" resultMap="BaseResultMap">
    select * from employee order by ${value}
</select>

(3)新增對應測試類

// 排序
public static void queryBySort() {
    SqlSession sqlSession = SqlSessionUtils.openSession();
    EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);

    List<Employee> empLists = employeeMapper.queryBySort("ename");
    System.out.println("");
}

public static void main(String[] args) {
    // queryEmpByDid();
    // queryDepartEmps();
    // queryByPage(2);
    queryBySort();
}

12、動態sql

<insert id="insertSelective" parameterType="com.danni.model.entity.Employee">
    insert into employee
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="eid != null">
        eid,
      </if>
      <if test="ename != null">
        ename,
      </if>
      <if test="esex != null">
        esex,
      </if>
      <if test="did != null">
        did,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="eid != null">
        #{eid,jdbcType=INTEGER},
      </if>
      <if test="ename != null">
        #{ename,jdbcType=VARCHAR},
      </if>
      <if test="esex != null">
        #{esex,jdbcType=VARCHAR},
      </if>
      <if test="did != null">
        #{department.did,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>

update:

<update id="updateByPrimaryKeySelective" parameterType="com.danni.model.entity.Employee">
    update employee
    <set>
      <if test="ename != null">
        ename = #{ename,jdbcType=VARCHAR},
      </if>
      <if test="esex != null">
        esex = #{esex,jdbcType=VARCHAR},
      </if>
      <if test="did != null">
        did = #{department.did,jdbcType=INTEGER},
      </if>
    </set>
    where eid = #{eid,jdbcType=INTEGER}
  </update>