Maven项目整合Mybatis

2021-02-21
预计阅读时间:3分钟

下面详细记录下Maven项目整合Mybatis的详细步骤:

  1. 在IDEA中开始界面选择“New Project”

image-20230222001542370

  1. 左侧项目类型选择“Maven”,右侧选择jdk版本,这里不选取项目模板来进行全新创建

image-20230222001110117

  1. 填写项目名称、GroupId、ArtifactId,选择项目存储位置后点击“Finish”

image-20230222001234346

  1. 创建项目完成后,继续完成下面的项目结构
src
 └ main
	 └ java
	 	└ mapper
	 		StudentMapper.java
	 	└ pojo
	 		Student.java
	 	└ service
	 		StudentService.java
	 		└ Impl
	 			StudentServiceImpl.java
	 	└ util
	 		DataBaseUtil.java
	 └ resources
		└ mappers
			StudentMaper.xml
		MyBatisConfig.xml
		jdbc.properties	
 └ test
	└ java	
		MybatisTest.java		
pom.xml
  • 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>com.devon</groupId>
    <artifactId>mybatis_quiz</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
      	<!-- 开启lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
            <optional>true</optional>
        </dependency>
    </dependencies>

</project>
  • StudentMapper.java——定义Mapper接口方法:
package mapper;

import pojo.Student;

import java.util.List;

public interface StudentMapper {

    List<Student> getList();
}
  • Student.java——定义实体类:
package pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {

    private Integer number;

    private String name;

    private String sex;

    private Integer age;

    private String dept;

}
  • StudentService.java——定义service层接口方法,与mapper层同名:
package service;

import pojo.Student;

import java.util.List;

public interface StudentService {

    List<Student> getList();
}
  • StudentServiceImpl.java——定义service接口实现类:
package service.impl;

import mapper.StudentMapper;
import org.apache.ibatis.session.SqlSession;
import pojo.Student;
import service.StudentService;
import util.DataBaseUtil;

import java.util.List;

public class StudentServiceImpl implements StudentService {

    @Override
    public List<Student> getList() {
        List<Student> students = null;
        SqlSession session = DataBaseUtil.getSqlSession();
        StudentMapper stumapper = session.getMapper(StudentMapper.class);
        students = stumapper.getList();
        return students;
    }
}
  • DataBaseUtil.java——定义数据库连接工具类:
package util;

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.InputStream;

public class DataBaseUtil {

    private static SqlSessionFactory sqlSessionFactory;

    private DataBaseUtil(){};

    public static SqlSession getSqlSession(){

        try {
            //加载核心配置文件
            InputStream resourceAsStream = Resources.getResourceAsStream("MyBatisConfig.xml");

            if (sqlSessionFactory == null){
                //获取SqlSessionFactoryBuilder
                SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
                //将获得的 SqlSessionFactory 对象赋给初始化的对象 sqlSessionFactory
                sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);
            }
            //获取SqlSession
            SqlSession sqlSession = sqlSessionFactory.openSession();
            return sqlSession;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
  • StudentMaper.xml——绑定与mapper接口对应的SQL语句:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--注意:这里的 namespace 属性需要填写上面 mapper 接口的全类名-->
<mapper namespace="mapper.StudentMapper">

    <select id="getList" resultType="pojo.Student">
        select * from student
    </select>

</mapper>
  • MyBatisConfig.xml——Mybatis核心配置文件:
<?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="jdbc.properties"></properties>

    <!-- 环境配置时主体内容 -->
    <environments default="development">
        <environment id="development">
          	<!-- 单独使用时配置成 MANAGED 没有事务 -->
            <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>
    <!--加载映射文件,注意这个是XML文件,路径使用“/”,而不是包使用com.bjwl.mapper-->
    <mappers>
        <mapper resource="mappers/StudentMapper.xml"/>
    </mappers>
</configuration>
  • MybatisTest.java——测试service接口是否正常:
import org.junit.Test;
import pojo.Student;
import service.impl.StudentServiceImpl;

import java.util.List;

public class MybatisTest {

    @Test
    public void studentTest(){

        StudentServiceImpl studentService = new StudentServiceImpl();
        List<Student> list = studentService.getList();
        if(list != null){
            for (int i = 0; i < list.size(); i++) {
                System.out.println(list.get(i).toString());
            }
        }
    }
}

完成上述编码,执行测试类,执行结果如下:

image-20230222101945593

jdbc.properties(可选)

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://<IP>:3306/<databaseName>?serverTimezone=GMT%2b8
username=<username>
password=<password>

:student 表建表 SQL 语句

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `number` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `sex` varchar(10) NOT NULL,
  `age` int(11) NOT NULL,
  `dept` varchar(100) NOT NULL,
  PRIMARY KEY (`number`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of student
-- ----------------------------
BEGIN;
INSERT INTO `student` (`number`, `name`, `sex`, `age`, `dept`) VALUES (1, '张三', '男', 21, '初三(1)班');
INSERT INTO `student` (`number`, `name`, `sex`, `age`, `dept`) VALUES (2, '李四', '女', 22, '高三(4)班');
INSERT INTO `student` (`number`, `name`, `sex`, `age`, `dept`) VALUES (3, '李娜', '女', 18, '高一(1)班');
INSERT INTO `student` (`number`, `name`, `sex`, `age`, `dept`) VALUES (4, '王强', '男', 19, '高三(10)班');
COMMIT;