MyBatis-在IDEA中用Maven实现查询功能

目录

 

1.在IDEA中创建maven项目  

2.在pom.xml文件中加入相关依赖 

3.编写MyBatis.xml主配置文件

4.编写Student实体类、StudentDao接口和sql操作的xml文件

5.编写MyTest测试类  

6.运行结果 


1.在IDEA中创建maven项目  

打开IDEA软件,新建一个Project后👇

下面的Name是创建项目的名称,自己取得,我取的名字是ch01-second ,注意的是Version 应该是1.0 

 

 

 

用Maven创建项目大概就完成了,一般它会自动给你建一个默认文件类,可以删掉。这是MyBatis的项目创建

下面是对项目的配置让让项目方便我们的使用

 

 

 

 

2.在pom.xml文件中加入相关依赖 

pom.xml文件是不能直接使用的,需要添加相关依赖,删掉不要的依赖。

下面代码是我添加好的,能够直接用的,主要有 MyBatis 依赖、MySQL驱动、junit测试依赖等, MyBatis官方文档里有详细解释和标注可以去官方查看

<?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.lhy</groupId>
  <artifactId>ch01-first</artifactId>
  <version>1.0</version>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>13</maven.compiler.source>
    <maven.compiler.target>13</maven.compiler.target>
  </properties>
    <!--依赖列表-->
  <dependencies>
  <!--mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>

    <!--mysql驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.9</version>
    </dependency>

    <!--单元测试-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <!--资源插件:处理src/maim/java目录中的xml-->
    <resources>
      <resource>
        <directory>src/main/java</directory><!--所在的目录-->
        <includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>




  </build>
</project>

相关的xml文件参考网址:https://mybatis.org/mybatis-3/zh/index.html 

3.编写MyBatis.xml主配置文件

  ***在该操作之前,应该先创建一个数据库,在添加一个表和相关数据。 

 添加一个配置文件,在创建一个MyBatis.xml文件,具体方法:在src/main目录下,新建一个 resources 目录,然后右键单击 resources → Mark Directory as → Resources Root。将此文件夹的类型修改为 Resources Root,之后在这个目录下创建一个 File,名为 MyBatis.xml。我们在MyBatis.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>
    <!--设置日志-->
<!--    <settings>-->
<!--        <setting name="logImpl" value="STDOUT_LOGGING"/>-->
<!--    </settings>-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
           <!--配置数据源,创建connection对象-->
            <dataSource type="POOLED">
                <!--driver:驱动的·内容-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--连接数据库url-->
                <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="199817"/>
            </dataSource>
        </environment>
    </environments>

    <!--指定其他mapper文件的位置  才能找到其他文件sql语句-->
    <mappers>
        <!--
            使用·mapper的resource属性指定mapper文件的路径
            这个路径是从target/classes路径开启的
            注意: resource=“mapper文件的路径,使用/分割路径”
            一个mapper resource指定一个mapper文件
        -->
        <mapper resource="com/lhy/dao/studentDao.xml"/>
<!--        <package name="com.lhy.dao"/>-->
    </mappers>
</configuration>

 

4.编写Student实体类、StudentDao接口和sql操作的xml文件

首先创建一个实体类,建议类名和属性直接用自己建的表名和属性名   在这里我有点建议将实体类单独建一个文件,接口和sql操作的xml文件另外创建在一个文件。

Student实体类

public class Student {
    private Integer id;
    private String name;
    private String email;
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getAge() {
        return age;
    }

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


    @Override
    public String toString() {
        return "学生实体的信息{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

studentDao接口

import com.lhy.domain.Student;

public interface studentDao {
   public Student selectstudentId(Integer id);

   int insertStudent(Student student);

}

 studentDao的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 namespace="dao接口的全限定名称">-->
<!--    &lt;!&ndash;使用insert,uodate,delete,select标签写sql&ndash;&gt;-->

<!--</mapper>-->
<mapper namespace="com.lhy.dao.studentDao">
   <!-- <select id="selectBlog" resultType="Blog">
        select * from Blog where id = #{id}
    </select>  -->

    <!-- 查询学生student
    id要执行的sql语句的唯一标识,后面一般是接口的方法
    resultType:告诉mybits,执行失去了语句,把数据赋值给那个类型的Java对象
        resultType的值现在使用的Java对象的权限的名称
    -->
    <select id="selectstudentId" resultType="com.lhy.domain.Student">
        select id,name,email,age from student where id= #{id}
    </select>
<!--添加inert
    如果传入给mybatis是一个java对象,使用3{属性名}  #{}表示占位符,属性要放到花括号内相当于getXX
-->
    <insert id="insertStudent">
        <!--insert into student values(10002,"张三","zhangsan@qq.com",20)-->
    insert into student values(#{id},#{name},#{email},#{age})
    </insert>
</mapper>
<!-- 约束文件  :"http://mybatis.org/dtd/mybatis-3-mapper.dtd"
        约束文件的作用:定义和限制当前文件中可以使用的标签和属性以及标签出现的位置

      mapper是跟标签
         namespace:命名空间必须有唯一值  建议使用Dao接口的权限定名称
         作用:参与识别SQL语句的作用
      在mapper里可以写insert,update,delete,select标签
-->

 

5.编写MyTest测试类  

编写测试类,验证是否正确。 

查询学号为10002的学生,插入编号为10003,名字叫做王五的学生。


import com.lhy.domain.Student;
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.Test;

import java.io.IOException;
import java.io.InputStream;

/**
 *
 */
public class myTest {

    @Test
    public void testSelectStudentById() throws IOException {
        //1.定义mybatis主配值文件的位置,从路径开始的相对位置
        String confid = "mybatis.xml";
        //2.读取主配置文件,使用mybatis框架中的Resources类
        InputStream inputStream = Resources.getResourceAsStream(confid);
        //3.创建SqlSessionFactory对象,使用SqlSessionFactoryBuidler类
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        //4.获取SqlSession 对象
        SqlSession session=factory.openSession();
        //5.指定要执行的sql语句的id  sql的id=namespace+“.”+select|update|insert|delete标签的id属性值
        String sqlId="com.lhy.dao.studentDao.selectstudentId";
        //6.通过sqlSession的方法执行sql语句
        //Student student=session.selectOne(sqlId);
        Student student=session.selectOne(sqlId,10002);
        System.out.println("使用Mybatis查询一个学生:"+student);
        //7.关闭sqlSession对象
        session.close();
    }
    @Test
    public void testInsertStudentById() throws IOException {
        //同上,固定格式
        String confid = "mybatis.xml";
        InputStream inputStream = Resources.getResourceAsStream(confid);
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session=factory.openSession();


        String sqlId="com.lhy.dao.studentDao.insertStudent";

       /* int student=session.insert(sqlId);
        System.out.println("使用Mybatis添加一个学生:"+student);*/
        Student student=new Student();
        student.setId(10003);
        student.setName("王五");
        student.setEmail("wangwu@qq.com");
        student.setAge(26);
        int stu= session.insert(sqlId,student);
        System.out.println("使用Mybatis添加一个学生:"+stu*9);
        //mybatis默认的执行sql语句是  手动提交事务模式, 在做insert,update,delete后需要提交事务
        //手动模式提交事务   SqlSession session=factory.openSession();当openSession(true)时,自动提交
        session.commit();

        //7.关闭sqlSession对象
        session.close();
    }
}

@Test是单元测试注解,用于测试相关模块的。

每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例。
从 XML 文件中构建 SqlSessionFactory 的实例非常简单,建议使用类路径下的资源文件进行配置。 但也可以使用任意的输入流(InputStream)实例,比如用文件路径字符串或 file:// URL 构造的输入流。MyBatis 包含一个名叫 Resources 的工具类,它包含一些实用方法,使得从类路径或其它位置加载资源文件更加容易。

6.运行结果 

 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值