Maven-mybatis的使用与配置

69 阅读1分钟

开发步骤

  1. 建库建表
  2. 创建maven项目
  3. 添加依赖
  4. 创建mybatis全局配置文件
  5. 创建实体类
  6. 创建映射文件
  7. 编写测试类,启动项目

设置setting.xml文件

官网下载压缩包并解压到某路径,打开conf中的setting.xml文件

  1. 创建仓库文件并将路径写到配置信息中

微信截图_20230716104109.png

  1. 配置阿里云镜像仓库
<mirror>
		<id>aliyun</id>
		<name>aliyun Maven</name>
		<mirrorOf>*</mirrorOf>
          <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
</mirror>
  1. 配置profile的jdk
<profile>
		<id>jdk-1.8</id>
		<activation>
		<activeByDefault>true</activeByDefault>
		<jdk>1.8</jdk>
		</activation>
		<properties>
                <maven.compiler.source>1.8</maven.compiler.source>
                <maven.compiler.target>1.8</maven.compiler.target>
		 <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
		</properties>
</profile>

创建maven项目

方法一:创建maven项目默认配置,在setting里设置 微信图片_20230716110328.jpg

方法二:创建maven项目同时配置好

微信截图_20230716110650.png

微信截图_20230716110738.png

微信截图_20230716110836.png

配置pom.xml文件

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.6</version>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.47</version>
</dependency>

创建mybtis全局配置文件

微信截图_20230716175848.png

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config //EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <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/msb?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/BookMapper.xml"></mapper>
    </mappers>
</configuration>

创建实体类(与数据库对应)

uTools_1691055846311.png

public class Book {
    private int id;
    private String type;
    private String name;
    private String description;
    // getter setter方法
}

创建映射文件

uTools_1691063049998.png

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper //EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper>
    <select id="selectAllBooks" resultType="com.msb.pojo.Book">
        select * from t_book
    </select>
</mapper>

uTools_1691063912823.png

编写测试类

uTools_1691069144576.png