• MyBatis_HelloWorld


    MyBatis是目前使用最多的ORM框架之一,今天学习了MyBatis基本配置,使用MyBatis读取数据库内容并直接映射为对象

    MyBatis简化了DAO层与DB层间操作

    下面通过最简单的一个实例了解MyBatis

    一、构建项目

    1.建立JAVA项目结构如下,导入MySQL、MyBatis jar包:

    2.Mybatis数据库如下:

    建表SQL语句:

     1 SET FOREIGN_KEY_CHECKS=0;
     2 
     3 -- ----------------------------
     4 -- Table structure for tbl_employee
     5 -- ----------------------------
     6 CREATE TABLE `tbl_employee` (
     7   `id` int(11) NOT NULL AUTO_INCREMENT,
     8   `last_name` varchar(255) DEFAULT NULL,
     9   `gender` char(1) DEFAULT NULL,
    10   `email` varchar(255) DEFAULT NULL,
    11   PRIMARY KEY (`id`)
    12 ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
    13 
    14 -- ----------------------------
    15 -- Records of tbl_employee
    16 -- ----------------------------
    17 INSERT INTO `tbl_employee` VALUES ('1', 'tom', '0', 'tom@atguigu.com');

    3.编写与关系数据库对应的JavaBean:

     1 package com.atguigu.mybatis.bean;
     2 
     3 public class Employee {
     4 
     5     private Integer id;
     6     private String lastName;
     7     private String gender;
     8     private String email;
     9     public Integer getId() {
    10         return id;
    11     }
    12     public void setId(Integer id) {
    13         this.id = id;
    14     }
    15     public String getLastName() {
    16         return lastName;
    17     }
    18     public void setLastName(String lastName) {
    19         this.lastName = lastName;
    20     }
    21     public String getGender() {
    22         return gender;
    23     }
    24     public void setGender(String gender) {
    25         this.gender = gender;
    26     }
    27     public String getEmail() {
    28         return email;
    29     }
    30     public void setEmail(String email) {
    31         this.email = email;
    32     }
    33     
    34     @Override
    35     public String toString() {
    36         return "Employee [id=" + id + ", lastName=" + lastName + ", gender=" + gender + ", email=" + email + "]";
    37     }
    38 }

    二、配置MyBatis

    1.在conf/下建立全局配置文件mybatis-config.xml:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!DOCTYPE configuration
     3  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
     4  "http://mybatis.org/dtd/mybatis-3-config.dtd">
     5 <configuration>
     6     <environments default="development">
     7         <environment id="development">
     8             <transactionManager type="JDBC"/>
     9             <dataSource type="POOLED">
    10                 <property name="driver" value="com.mysql.jdbc.Driver"/>
    11                 <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
    12                 <property name="username" value="root"/>
    13                 <property name="password" value="root"/>
    14             </dataSource>
    15         </environment>
    16     </environments>
    17     
    18     <!-- 配置SQL语句映射文件 -->
    19     <mappers>
    20         <mapper resource="EmployeeMapper.xml"/>
    21     </mappers>
    22 </configuration>

    2.建立SQL语句映射文件EmployeeMapper.xml

     1 <?xml version="1.0" encoding="UTF-8" ?>
     2 <!DOCTYPE mapper
     3  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
     4  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
     5 <!-- namespace可以任意填写,只是为了便于区分 -->
     6 <mapper namespace="com.atguigu.mybatis.EmployeeMapper">
     7 
     8     <!-- id是sql唯一标识,resultType相当于返回类型 -->
     9     <select id="selectEmp" resultType="com.atguigu.mybatis.bean.Employee">
    10     
    11         <!-- 查询结果字段与Employee属性保持一致才可以正确映射,所以这里使用别名lastName -->
    12         select id,last_name lastName,gender,email from tbl_employee where id = #{id}
    13     </select>
    14 </mapper>

    三、建立单元测试文件

     1 package com.atguigu.mybatis.test;
     2 
     3 import java.io.IOException;
     4 import java.io.InputStream;
     5 
     6 import org.apache.ibatis.io.Resources;
     7 import org.apache.ibatis.session.SqlSession;
     8 import org.apache.ibatis.session.SqlSessionFactory;
     9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    10 import org.junit.jupiter.api.Test;
    11 
    12 import com.atguigu.mybatis.bean.Employee;
    13 
    14 class MybatisTest {
    15 
    16     @Test
    17     void test() throws IOException {
    18         
    19         /**
    20          * 使用mybatis-config.xml获取sqlSession工厂sqlSessionFactory
    21          */
    22         String resource = "mybatis-config.xml";
    23         InputStream inputStream = Resources.getResourceAsStream(resource);
    24         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    25     
    26         /**
    27          * 通过sqlSessionFactory获取SqlSession
    28          */
    29         SqlSession openSession = sqlSessionFactory.openSession();
    30         try {
    31             Employee employee = openSession.selectOne("com.atguigu.mybatis.EmployeeMapper.selectEmp", 1);
    32             System.out.println(employee);
    33         }finally {
    34             openSession.close();    //必须关闭
    35         }
    36 
    37     }
    38 
    39 }

    四、执行结果

    五、本次学习中遇到的问题:

    1.运行测试文件时提示找不到mybatis-config.xml文件:

    java.io.IOException: Could not find resource mybatis-config.xml
        at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:114)
        at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:100)
        at com.atguigu.mybatis.test.MybatisTest.test(MybatisTest.java:23)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
     ……

    解决办法:

    新建conf文件夹时选择Source Folder而不是Folder(参考https://ask.csdn.net/questions/252045下面xl1007的评论)

  • 相关阅读:
    面向对象(三大特性)
    SQL Server数据库(SQL Sever语言 事务)
    面向对象(简介)
    SQL Server数据库(SQL Sever语言 存储过程及触发器)
    SQL Server数据库(SQL Sever语言 函数以及SQL编程)
    SQL Server数据库(作业讲解和复习)
    SQL Server语言 函数以及SQL编程
    数据库(作业讲解和复习)
    SQL中CRUD C——create 添加数据 R——read 读取数据 U——update 修改数据 D——delete 删除数据
    SQL server数据库基础
  • 原文地址:https://www.cnblogs.com/lzq666/p/9284509.html
Copyright © 2020-2023  润新知