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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值