maven搭建项目--实现mybatis增删改差、一对多及一对一关系

1、创建maven项目

maven搭建项目--实现mybatis增删改差、一对多及一对一关系_第1张图片

maven搭建项目--实现mybatis增删改差、一对多及一对一关系_第2张图片

maven搭建项目--实现mybatis增删改差、一对多及一对一关系_第3张图片

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.0modelVersion>
    <groupId>com.dannigroupId>
    <artifactId>mybatis-mavenartifactId>
    <version>0.0.1-SNAPSHOTversion>

    <dependencies>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.4.5version>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-JavaartifactId>
            <version>5.1.6version>
        dependency>

        
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.12version>
        dependency>
    dependencies>
project>


3、在Eclipse安装mybatis generator自动生成工具

(1)下载mybatis生成架包工具MyBatis_Generator_1.3.1.zip,解压jar包把features、plugins文件夹下的架包分别拷贝到eclipse安装目录下的features、plugins文件夹(复制和替换eclipse原有的这两个文件夹)。然后重启eclipse。
maven搭建项目--实现mybatis增删改差、一对多及一对一关系_第4张图片

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


<dependency>
    <groupId>org.mybatis.generatorgroupId>
    <artifactId>mybatis-generator-maven-pluginartifactId>
    <version>1.3.2version>
    <type>maven-plugintype>
dependency>

(3)配置generator.xml文件



<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>

        
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/student" userId="root" password="root"> jdbcConnection>

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

        
        <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>

        
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.danni.model.dao" targetProject="mybatis-maven">
            <property name="enableSubPackages" value="true" />
        javaClientGenerator>

        
        <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,点击即可生成代码文件。

maven搭建项目--实现mybatis增删改差、一对多及一对一关系_第5张图片

4、编写数据库和日志的properties文件

maven搭建项目--实现mybatis增删改差、一对多及一对一关系_第6张图片
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



<configuration>
    
    <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;
    }
}

maven搭建项目--实现mybatis增删改差、一对多及一对一关系_第7张图片

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
maven搭建项目--实现mybatis增删改差、一对多及一对一关系_第8张图片



<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" />

    
    <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 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" />

    
    <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 queryBySort(String name);

(2)在实现类中添加相应的实现方法


<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 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:

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}
  

你可能感兴趣的:(java框架)