Mybatis实例应用

Mybatis实例应用

1、新建空项目

打开软件,点击“Empty Project”。
image-20210724190347555
项目命名任意,例如我的是“day003”。
image-20210724190427352弹出以下对话框,先“取消”,先检查配置。
image-20210724190457780

2、配置检查

主要检查maven的配置,因为是通过它构建的。这里有一个前提,就是你的电脑已经安装了maven,这里不作展开。检查maven设置,先根据下图打开setting。

image-20210725093534826
检查①②③处配置,具体的位置是根据你的maven安装位置和配置。
image-20210725094358794在setting点击“Project Structure”,检查java相关配置。
image-20210725095216725
红色两处要对应,比如我使用的是java11,SDK也要选择版本11。
image-20210724190544694

3、新建父maven模块

新建Module。
image-20210724175840660直接下一步。
image-20210724190606816例如我取了个名“00base”。
image-20210724190627499
下一步。

image-20210724190703047
完成后,出现如下界面,目前打开的是文件是“00base”,先点击右下角自动使能导入。
image-20210724175949281

添加以下程序,注意第4、5行,要跟java的版本对应。

   <packaging>pom</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>

        </dependency>
        <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>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

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

删除00base下的src文件夹。

image-20210725221310327

4、新建子maven模块

选中00base,右键新建->模块。注:一定要选中00base再右键.

image-20210725221407409
根据下图三个箭头所指进行配置。

image-20210727150237430填入01first
image-20210725221509646去掉自动生成的下划线。当然不去掉问题也不大。

image-20210724180206637最后提示框出现BUILD SUCCESS

image-20210724180232414
同时会弹出01first的页面,删掉红框里面的内容,因为在父maven模块中配置过了。

image-20210727150707032

5、创建实体类

新建包com.xp,在这个包下新建bean,dao ,test三个包。daotest两个以后会用到,先在bean包下新建Student类。

image-20210727152051448image-20210727153029123

package com.xp.bean;

public class Student {
    private int id;
    private String name;
    private int age;
    private double score;

    public Student() {

    }

    public Student(String name, int age, double score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }
}

6、创建数据库

打开Navicat Premium软件,新建MySQL.

image-20210727153723670

连接名任意取,例如xp01,设置一个密码,不要忘了,后面还要用。

image-20210727153806878
选中新建的xp01,点击新建查询

image-20210727153849048

在①处输入test,注意,在配置mybatis.xml文件中还会用到。在②处输入SQL语句,点击运行。

image-20210727154049474

CREATE TABLE `t_student` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(20) NULL,
  `age` INT NULL,
  `score` DOUBLE NULL,
  PRIMARY KEY (`id`));

新建成功后提示OK

image-20210727163026515

同时也可以在test下看到t_student,到此为止数据库配置完成。

image-20210727163106507

7、创建dao接口

dao接口用于跟数据库打交道。在dao包下新建接口StudentDao,接口中添加一个方法insertStudent,该方法需要传入一个Student类型的参数。

image-20210727155904185

8、添加映射文件

映射主要用于java和数据库的联系,该文件里面主要编写SQL语句。在dao包下新建StudentMapper.xml文件。

image-20210727160521682
image-20210727160556029

<?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="xp">
    <!--parameterType可省略-->
    <insert id="insertStudent" parameterType="com.xp.bean.Student">
        INSERT INTO t_student(name,age,score) VALUES (#{name},#{age},#{score})
    </insert>
</mapper>

9、添加mybatis的主配置文件

先在主函数下新建resources文件夹。

image-20210727161111453
resources文件夹标志为Resources Root

image-20210727161146037
resources文件夹中新建mybatis.xml文件。

image-20210727161222552
复制以下内容到mybatis.xml文件,需要注意的是第11/12/13行,在第11行中有个test,要跟数据库中新建的表明对应起来。第12/13行就是创建Mysql用的用户名和密码。

<?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.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/test?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="1234"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--注册映射文件-->
        <mapper resource="com/xp/dao/StudentMapper.xml"/>
    </mappers>
</configuration>

10、添加日志

添加日志主要是为了调试方便,按下图操作。

image-20210727161634816

log4j.rootLogger=trace,console

#控制台附加器
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern= [%-5p][%d{yyyy-MM-dd HH:mm:ss}]%m%n

11、创建接口的实现类

在到包下新建StudentDaoImpl类,完成以下代码。

image-20210727161912392
第13行的参数注意下,第一个参数:"insertStudent"要跟映射文件中的第7行对应起来。第二个参数:传Student类型对象。

public class StudentDaoImpl implements StudentDao {
    public void insertStudent(Student student) {

        try {

            InputStream input =  Resources.getResourceAsStream("mybatis.xml");

            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(input);

            //创建SqlSession对象
            SqlSession sqlSession = sessionFactory.openSession();
            //新增数据操作
            sqlSession.insert("insertStudent", student);
            //提交SqlSession
            sqlSession.commit();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

12、测试连接

所有工作完成后使用Mysql对数据库中的数据进行插入。在test包中新建一个StudentTest测试类。

image-20210727162200371

public class StudentTest {

@Test
    public void  insertStudent(){
         StudentDaoImpl studentDao = new StudentDaoImpl();
         Student student = new Student("jack", 18, 99.5);
         studentDao.insertStudent(student);
}
}

运行,左侧出现绿色图标表示操作成功。

image-20210727163146587刷新下数据库,数据显示!
image-20210727163222585

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值