JavaEE使用Mybatis

maven配置pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>cn.itcast.com</groupId>
    <artifactId>MybatisDemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.18</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

</project>

配置文件 SqlMapConfig.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>
    <typeAliases>
        <!-- 配置实体类的别名 -->
        <package name="cn.itcast.orm.entity"/>
    </typeAliases>
    <environments default="Mysql">
        <environment id="Mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis-demo?characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="Wangj001"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="cn.itcast.orm.mapper" />
    </mappers>
</configuration>

实体类编写 DeptEmployee.java

package cn.itcast.orm.entity;

import lombok.Data;

// 实体类
@Data
public class DeptEmployee {
    private String deptName;
    private Integer employeeNum;
}

映射接口 DeptEmployeeMapper.java

package cn.itcast.orm.mapper;

import cn.itcast.orm.entity.DeptEmployee;

import java.util.List;

public interface DeptEmployeeMapper {
    List<DeptEmployee> getEmployeeNumByDept();
}

映射文件 DeptEmployeeMapper.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映射文件-->
<mapper namespace="cn.itcast.orm.mapper.DeptEmployeeMapper">
    <resultMap id="getEmployeeNumByDept" type="DeptEmployee">
        <result property="deptName" column="deptName"></result>
        <result property="employeeNum" column="employeeNum"></result>
    </resultMap>
    <select id="getEmployeeNumByDept" resultMap="getEmployeeNumByDept" resultType="cn.itcast.orm.entity.DeptEmployee">
        select a.name as deptName,count(*) as employeeNum
        from dept as a, employee as b
        where a.id=b.deptId
        GROUP BY b.deptId
    </select>
</mapper>

测试类编写 MybatisDemoTest.java

import cn.itcast.orm.entity.DeptEmployee;
import cn.itcast.orm.mapper.DeptEmployeeMapper;
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 org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MybatisDemoTest {
    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void init() throws IOException {
        // 1、创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        // 2、加载配置文件
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 3、创建SqlSessionFactory对象
        sqlSessionFactory = builder.build(inputStream);
    }

    @Test
    public void testGetEmployeeNumByDept(){
        // 4、创建sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 5、获取员工分组统计信息
        // 方法一
//        List<DeptEmployee> deptEmployeeList = sqlSession.selectList("getEmployeeNumByDept");
        // 方法二
        DeptEmployeeMapper deptEmployeeMapper = sqlSession.getMapper(DeptEmployeeMapper.class);
        List<DeptEmployee> deptEmployeeList = deptEmployeeMapper.getEmployeeNumByDept();
        // 6、打印结果
        for (DeptEmployee de:
             deptEmployeeList) {
            System.out.println(de.toString());
        }
        // 7、释放资源
        sqlSession.close();
    }
}

数据库文件 mybatis-demo.sql

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for dept
-- ----------------------------
DROP TABLE IF EXISTS `dept`;
CREATE TABLE `dept` (
  `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `name` varchar(255) DEFAULT NULL COMMENT '部门名称',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of dept
-- ----------------------------
INSERT INTO `dept` VALUES ('1', '技术部');
INSERT INTO `dept` VALUES ('2', '运营部');
INSERT INTO `dept` VALUES ('3', '产品部');
INSERT INTO `dept` VALUES ('4', '市场部');

-- ----------------------------
-- Table structure for employee
-- ----------------------------
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
  `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '员工ID',
  `deptId` bigint(11) NOT NULL COMMENT '部门id',
  `name` varchar(255) DEFAULT NULL COMMENT '员工名称',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of employee
-- ----------------------------
INSERT INTO `employee` VALUES ('1', '1', 'java1号');
INSERT INTO `employee` VALUES ('2', '1', 'php1号');
INSERT INTO `employee` VALUES ('3', '1', '前端1号');
INSERT INTO `employee` VALUES ('4', '2', '微信运营1号');
INSERT INTO `employee` VALUES ('5', '2', '社区运营1号');
INSERT INTO `employee` VALUES ('6', '3', '产品经理');
INSERT INTO `employee` VALUES ('7', '3', '产品经理助理');
INSERT INTO `employee` VALUES ('8', '4', '电话营销');
INSERT INTO `employee` VALUES ('9', '4', '地推营销');
INSERT INTO `employee` VALUES ('10', '4', '客服');

最后贴上工程目录

附上另外一个同学写的教程

https://www.jianshu.com/p/8fc176b2e13b

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值