• 编写一个Mybatis程序


            思路:搭建环境 --> 导入Mybatis --> 编写代码 --> 测试

    搭建环境

        搭建数据库

    1. CREATE DATABASE `mybatis`;
    2. USE `mybatis`;
    3. CREATE TABLE `user`(
    4. `id` INT(20) NOT NULL PRIMARY KEY,
    5. `name` VARCHAR(30) DEFAULT NULL,
    6. `pwd` VARCHAR(30) DEFAULT NULL
    7. ) ENGINE=INNODB DEFAULT CHARSET=utf8;
    8. INSERT INTO `user`(`id`,`name`,`pwd`) VALUES
    9. (1,'小明','123456'),
    10. (2,'张三','123456'),
    11. (3,'李四','123456');

        新建项目

    1. 新建一个普通的maven项目

    2. 删除src目录(作为父工程)

    3. 在pom.xml文件下导入maven依赖

    1. <dependencies>
    2. <dependency>
    3. <groupId>mysqlgroupId>
    4. <artifactId>mysql-connector-javaartifactId>
    5. <version>5.1.47version>
    6. dependency>
    7. <dependency>
    8. <groupId>org.mybatisgroupId>
    9. <artifactId>mybatisartifactId>
    10. <version>3.5.7version>
    11. dependency>
    12. <dependency>
    13. <groupId>junitgroupId>
    14. <artifactId>junitartifactId>
    15. <version>4.12version>
    16. dependency>
    17. dependencies>

    创建一个模板

            编写mybatis的核心配置文件(mybatis-config.xml)

    1. "1.0" encoding="UTF-8" ?>
    2. 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"
    12. value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
    13. <property name="username" value="root"/>
    14. <property name="password" value="123456"/>
    15. dataSource>
    16. environment>
    17. environments>
    18. <mappers>
    19. <mapper resource="com/yuan/dao/UserMapper.xml"/>
    20. mappers>
    21. configuration>

            在java.com.xxx.utils层下编写mybatis工具类

    1. import org.apache.ibatis.io.Resources;
    2. import org.apache.ibatis.session.SqlSession;
    3. import org.apache.ibatis.session.SqlSessionFactory;
    4. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    5. import java.io.IOException;
    6. import java.io.InputStream;
    7. //sqlSessionFactory --> sqlSession
    8. public class MybatisUtils {
    9. private static SqlSessionFactory sqlSessionFactory;
    10. static {
    11. //获取sqlSessionFactory对象
    12. String resource = "mybatis-config.xml";
    13. try {
    14. InputStream inputStream = Resources.getResourceAsStream(resource);
    15. sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    16. } catch (IOException e) {
    17. e.printStackTrace();
    18. }
    19. }
    20. //既然有了SqlSessionFactory,顾名思义,我们就可以从中获得SqlSession的实例了
    21. //SqlSession 完全包含了面向数据库执行SQL命令所需的所有方法
    22. public static SqlSession getSqlSession(){
    23. //SqlSession sqlSession = sqlSessionFactory.openSession();
    24. return sqlSessionFactory.openSession();
    25. }
    26. }

    编写代码

            在java.com.xxx.pojo层下编写实体类(以User为例)

    1. public class User {
    2. private int id;
    3. private String name;
    4. private String pwd;
    5. public User(int id) {
    6. this.id = id;
    7. }
    8. public User(int id, String name, String pwd) {
    9. this.id = id;
    10. this.name = name;
    11. this.pwd = pwd;
    12. }
    13. public int getId() {
    14. return id;
    15. }
    16. public void setId(int id) {
    17. this.id = id;
    18. }
    19. public String getName() {
    20. return name;
    21. }
    22. public void setName(String name) {
    23. this.name = name;
    24. }
    25. public String getPwd() {
    26. return pwd;
    27. }
    28. public void setPwd(String pwd) {
    29. this.pwd = pwd;
    30. }
    31. @Override
    32. public String toString() {
    33. return "User{" +
    34. "id=" + id +
    35. ", name='" + name + '\'' +
    36. ", pwd='" + pwd + '\'' +
    37. '}';
    38. }
    39. }

           在 java.com.xxx.dao下编写UserMapper(即Dao接口)

    1. import java.util.List;
    2. import java.util.Map;
    3. public interface UserMapper {
    4. //获取全部用户
    5. List getUserList();
    6. }

            在 java.com.xxx.dao编写接口实现类UserMapper.xml(由原来的UserDaoImpl转为一个Mapper配置文件)

    1. "1.0" encoding="UTF-8" ?>
    2. mapper
    3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    5. <mapper namespace="com.yuan.dao.UserMapper">
    6. <select id="getUserList" resultType="com.yuan.pojo.User">
    7. select id, name, pwd from `user`
    8. select>
    9. mapper>

    测试

            修改pom.xml文件

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    5. <parent>
    6. <artifactId>Mybatis-StudyartifactId>
    7. <groupId>com.yuangroupId>
    8. <version>1.0-SNAPSHOTversion>
    9. parent>
    10. <modelVersion>4.0.0modelVersion>
    11. <artifactId>mybatis-01artifactId>
    12. <properties>
    13. <maven.compiler.source>8maven.compiler.source>
    14. <maven.compiler.target>8maven.compiler.target>
    15. properties>
    16. <build>
    17. <resources>
    18. <resource>
    19. <directory>src/main/resourcesdirectory>
    20. <includes>
    21. <include>**/*.propertiesinclude>
    22. <include>**/*.xmlinclude>
    23. includes>
    24. <filtering>falsefiltering>
    25. resource>
    26. <resource>
    27. <directory>src/main/javadirectory>
    28. <includes>
    29. <include>**/*.propertiesinclude>
    30. <include>**/*.xmlinclude>
    31. includes>
    32. <filtering>falsefiltering>
    33. resource>
    34. resources>
    35. build>
    36. project>

            在test.java.com.xxx.dao下编写UserDaoTest

    1. import com.yuan.pojo.User;
    2. import com.yuan.utils.MybatisUtils;
    3. import org.apache.ibatis.session.SqlSession;
    4. import org.junit.Test;
    5. import java.util.List;
    6. public class UserDaoTest {
    7. @Test
    8. public void test(){
    9. //第一步:获得SqlSession对象
    10. SqlSession sqlSession = MybatisUtils.getSqlSession();
    11. try{
    12. //方式一:getMapper
    13. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    14. List userList = userMapper .getUserList();
    15. //方式二:
    16. // List userList = sqlSession.selectList("com.yuan.dao.UserDao.getUserList");
    17. for(User user : userList){
    18. System.out.println(user);
    19. }
    20. }catch(Exception e){
    21. e.printStackTrace();
    22. }finally {
    23. //关闭SqlSession
    24. sqlSession.close();
    25. }
    26. }
    27. }

    目录

      在创建Mybatis中可能会出现的错误

    • 配置文件没有注册
    • 绑定接口错误
    • 方法名不对
    • 返回类型不对
    • Maven导出资源问题

  • 相关阅读:
    微服务:Sentinel篇
    阿里云安全中心需要购买吗?功能及价格告诉你值不值!
    (web前端网页制作课作业)使用HTML+CSS制作非物质文化遗产专题网页设计与实现
    【牛客网】另类加法
    【前端知识】Node——http模块&url模块的常用操作
    19.cuBLAS开发指南中文版--cuBLAS中的Level-2函数gemv()
    vscode-server安装和部分配置
    【21天学习挑战赛】Python学习第四篇:多线程 threading 模块
    六、SSL开源项目-Open虚拟私有网络
    css-解决Flex布局下居中溢出滚动截断问题
  • 原文地址:https://blog.csdn.net/weixin_48426115/article/details/126551545