maven非web專案整合mbatis實現CRUD

走馬看黃花發表於2020-10-10

在程式設計開發中,一般提起maven、mybatis這些,我們首先想到的就是javaweb的技術棧,比如spring、springboot。但是今天給大家介紹一個用maven整合mybatis的非web專案完成資料庫CRUD。

1 在idea中新建maven專案

直接新建即可,建立好後的專案結構如下

在pom檔案新增依賴

<dependencies>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.21</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.5</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.7.0</version>
        <scope>test</scope>
    </dependency>
</dependencies>

同時為了防止打包後找不到靜態資源,在pom檔案中,新增build標籤

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

2 建立資料庫和pojo實體類

首先建立資料庫

create DATABASE mybatis;
USE mybatis;
create table user(
       id int PRIMARY key not null,
       name VARCHAR(30) ,
       pwd VARCHAR(30)
) ENGINE=INNODB;
INSERT INTO `user`(`id`, `name`, `pwd`) VALUES (1, '卡卡羅特', '123456');
INSERT INTO `user`(`id`, `name`, `pwd`) VALUES (2, '阿笠博士', '12345');
INSERT INTO `user`(`id`, `name`, `pwd`) VALUES (3, '野原向日葵', '123');
INSERT INTO `user`(`id`, `name`, `pwd`) VALUES (4, '一拳超人', '12');
INSERT INTO `user`(`id`, `name`, `pwd`) VALUES (5, '庫裡林', '123321');

再建立包,在包下建立實體類,我這裡建立了一個User類。

package toutiao.pojo;
public class User {
    int id;
    String name;    String pwd;    public User() {
    }    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }    public int getId() {
        return id;
    }    public void setId(int id) {
        this.id = id;
    }    public String getName() {
        return name;
    }    public void setName(String name) {
        this.name = name;
    }    public String getPwd() {
        return pwd;
    }    public void setPwd(String pwd) {
        this.pwd = pwd;
    }    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }}

 3 在resources資料夾下面建立mybatis-config.xml 配置檔案

在這裡設定資料庫連線屬性等。同時資料庫連線動態配置等可以在application.properties檔案中配置,在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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai&useUnicode=true&character=UTF8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

4 建立mybatisUtils工具類

在這個類中讀取 mybatis-config.xml 建立 sqlSession。

package learn.utils;
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 MybatisUtils {
    private static SqlSessionFactory sqlSessionFactor;
    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);            sqlSessionFactor = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();        }    }    public static SqlSession getSqlSession(){
        return sqlSessionFactor.openSession();
    }}

此時,專案的目錄結構如下

 5 建立mapper介面檔案

package toutiao.mapper;
import toutiao.pojo.User;
import java.util.List;
public interface UserMapper {
    public List<User> getUserList();
}

 

6 在resources資料夾下面,建立對應mapper介面檔案的xml檔案

檔案裡面的sql語句的id對應介面檔案的方法名(這裡以查詢為例)

<?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="toutiao.mapper.UserMapper">
   			 <select id="getUserList" resultType="toutiao.pojo.User">
        			select * from mybatis.user;    			</select>
		</mapper>

7 在mybatis-config.xml 裡面將6中建立的xml檔案添進去

因為是在resources中,所以mapper標籤的resource路徑直接就是從resources下面的資料夾開始

<?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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai&useUnicode=true&character=UTF8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="userMapper.xml"></mapper>
    </mappers>
</configuration>

 8 查詢結果

在test包裡面建立測試類

package learn.mapper;
import learn.pojo.User;
import learn.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
import java.util.List;
public class UserMapperTest {
    @Test
    public void test(){
        Sqlession sqlSession = MybatisUtils.getSqlSession();        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userMapper.getUserList();        for(User user : userList){
            System.out.println(user);        }        sqlSession.close();    }}

 

 

相關文章