创建我的,第一个MyBtis项目

本文详细介绍如何使用Maven创建MyBatis项目,包括所需依赖、实体类定义、核心配置、Mapper文件设置、实用帮助类及测试方法。通过具体示例,帮助初学者快速掌握MyBatis的基本操作。

第一个MyBtis项目

Maven:pom.xml所需依赖

       <!--mysql的驱动包-->
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>5.1.47</version>
       </dependency>
       <!--mydatis-->
       <dependency>
           <groupId>org.mybatis</groupId>
           <artifactId>mybatis</artifactId>
           <version>3.5.2</version>
       </dependency>
       <!--junit-->
       <dependency>
           <groupId>junit</groupId>
           <artifactId>junit</artifactId>
           <version>4.12</version>
       </dependency>

idea使用maven创建Mybatis项目操作持久层时,常遇到资源导出失败问题,(解决方法)

在maven的pom.xml文件中添加

        <build>
            <!--配置resource防止资源导出失败ExceptionInInitializerError-->
            <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>

创建环境

  • pojo(实体类) 根据数据库中的数据类型自行更改
public class Student {
    private int id;
    private String name;
    private int age;
    private int sex;

    public Student() {
    }

    public Student(int id, String name, int age, int sex) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    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 int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex=" + sex +
                '}';
    }
}

核心配置

  • Dao <以接口形式创建,无需实现>
public interface StudentDao {
    List<Student> getStudentList();
}
  • 与Dao相对应的Mapper文件:StudentMapper.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"><!--头文件-->
        
        
<!--namespace用来绑定一个dao/mapper接口 填写dao对应类全类名-->
<mapper namespace="com.xzb.dao.StudentDao">
    <!--id对应dao接口的方法名-->  <!--id对应dao接口的方法的返回值类型全类名-->
    <select id="getStudentList" resultType="com.xzb.pojo.Student">
        <!--sql语句-->
        select * from student
    </select>
</mapper>

  • 核心配置类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.jdbc.Driver"/><!--连接数据库所需驱动-->
                <property name="url" value="jdbc:mysql://localhost:3306/stu?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/><!--连接数据库url及一些常用配置-->
                <property name="username" value="root"/><!--数据库用户名-->
                <property name="password" value="root"/><!--数据库用户密码-->
            </dataSource>
        </environment>
        <!--可配置多套环境 由environments中的default="environment的id"决定使用哪一套环境-->
    </environments>

    <!--每一个mapper都需要在config中注册-->
    <mappers>
        <mapper resource="com/xzb/dao/StudentMapper.xml"/>
    </mappers>
    <!--将创建的mapper文件注册进config文件中(重要)-->
</configuration>
  • utils帮助类
/**
 * 获取sqlSessionFactory  继而 获取 sqlSession
 */
public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory = null;
    static {
        try {
            //1.加载mybatis的config核心配置文件,获取获取sqlSessionFactory对象
            String resource = "config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (IOException e){

        }finally {

        }
    }
    /**
     *使用sqlSessionFactory获取sqlSession,sqlSession中包含了执行sql语句的方法
     */
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

测试

  • 测试类(此处使用junit测试)
public class UserDaoTest {
    @Test
    public void test(){
        SqlSession sqlSession = null;
        try {
            //获取sqlsession
            sqlSession = MyBatisUtil.getSqlSession();

            //执行mapper文件中的sql语句

            //1.获取对应对象 用于执行方法  方式一getMapper()
            StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
            //方式二,不建议使用
            //List<Student> studentList = sqlSession.selectList("com.xzb.dao.StudenrDao.getStudentList");

            //2.执行对象的方法 相当于执行mapper中的sql语句 (方法名 -对应- <sudi的id>) 获取返回值
            List<Student> studentList = studentDao.getStudentList();
            //查看结果
            for (Student student : studentList) {
                System.out.println(student);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭sqlSession
            sqlSession.close();
        }
    }
}

注意事项:

  • mapper配置文件必须在config核心配置文件中注册
  • 绑定接口mapper文件中的<mapper namespace="接口全路径>
  • 绑定接口中的方法名<select id="接口中的方法名"></select>
  • 返回值类型<select resultType="返回值的类型的全类名"></select>
  • Maven导出时需配置resource防止导出失败报错ExceptionInInitializerError
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值