第一个Mybatis程序

傷城~ 2023-02-19 11:29 123阅读 0赞

1、创建数据库

  1. # 创建数据库
  2. create database `mybatis`;
  3. # 使用数据库
  4. use `mybatis`;
  5. # 创建用户表
  6. create table `user`(
  7. `id` INT(20) NOT NULL PRIMARY KEY,
  8. `name` VARCHAR(30) DEFAULT NULL,
  9. `pwd` VARCHAR(30) DEFAULT NULL
  10. )ENGINE=INNODB DEFAULT CHARSET=utf8;
  11. # 插入数据
  12. INSERT INTO `user`(`id`,`name`,`pwd`)
  13. VALUES (1,'小明',12345),(2,'张三',12345),(3,'李四',12345);

2、创建项目

创建一个普通的Maven项目
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
修改Maven地址
在这里插入图片描述

导入Maven依赖

  1. <?xml version="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. <modelVersion>4.0.0</modelVersion>
  6. <!-- 父工程-->
  7. <groupId>com.study</groupId>
  8. <artifactId>Mybatis-study</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <dependencies>
  11. <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
  12. <dependency>
  13. <groupId>mysql</groupId>
  14. <artifactId>mysql-connector-java</artifactId>
  15. <version>5.1.47</version>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.mybatis</groupId>
  19. <artifactId>mybatis</artifactId>
  20. <version>3.5.2</version>
  21. </dependency>
  22. <!-- https://mvnrepository.com/artifact/junit/junit -->
  23. <dependency>
  24. <groupId>junit</groupId>
  25. <artifactId>junit</artifactId>
  26. <version>4.12</version>
  27. <scope>test</scope>
  28. </dependency>
  29. </dependencies>
  30. </project>

删除主目录src,并新建module。这样做的好处是自动继承父工程的依赖
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
我们可以看到父工程的POM.xml文件中出现了一下内容。
在这里插入图片描述

3、编写mybatis配置文件

3.1 编写xml文件

在这里插入图片描述
在这里插入图片描述
从Mybatis官网复制配置内容

  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. <!--核心配置文件-->
  6. <configuration>
  7. <environments default="development">
  8. <environment id="development">
  9. <transactionManager type="JDBC"/>
  10. <dataSource type="POOLED">
  11. <property name="driver" value="${driver}"/>
  12. <property name="url" value="${url}"/>
  13. <property name="username" value="${username}"/>
  14. <property name="password" value="${password}"/>
  15. </dataSource>
  16. </environment>
  17. </environments>
  18. </configuration>

3.2 编写工具类获取sqlSession

编写获取sqlSession的工具类

快速创建三级目录
在这里插入图片描述
间隔使用/,如果使用.则只有一级目录。
在这里插入图片描述
在这里插入图片描述

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

4、编写实体类

在这里插入图片描述

  1. package com.study.pojo;
  2. public class User {
  3. private int id;
  4. private String name;
  5. private String pwd;
  6. public User() {
  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. }

5、Dao接口及Mapper配置文件

在这里插入图片描述

5.1 Dao接口

  1. package com.study.dao;
  2. import com.study.pojo.User;
  3. import java.util.List;
  4. public interface UserMapper {
  5. List<User> getUserList();
  6. }

5.2 接口实现类由原来的UserDaoImpl转变为Mapper配置文件

  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. <!--绑定UserMapper-->
  6. <mapper namespace="com.study.dao.UserMapper">
  7. <!--id和方法名一致-->
  8. <select id="getUserList" resultType="com.study.pojo.User">
  9. select * from user
  10. </select>
  11. </mapper>

注意:namespace对应Mapper接口,id属性对应方法名,resultType对应返回值类型

5.3 在Mybatis配置文件中注册

  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. <!--核心配置文件-->
  6. <configuration>
  7. <environments default="development">
  8. <environment id="development">
  9. <transactionManager type="JDBC"/>
  10. <dataSource type="POOLED">
  11. <property name="driver" value="com.mysql.jdbc.Driver"/>
  12. <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
  13. <property name="username" value="root"/>
  14. <property name="password" value="123456"/>
  15. </dataSource>
  16. </environment>
  17. </environments>
  18. <!--注册位置-->
  19. <mappers>
  20. <mapper resource="com/study/dao/UserMapper.xml"/>
  21. </mappers>
  22. </configuration>

mappers标签内为注册内容。

6、编写测试

在这里插入图片描述

  1. package com.study.dao;
  2. import com.study.pojo.User;
  3. import com.study.utils.MybatisUtils;
  4. import org.apache.ibatis.session.SqlSession;
  5. import org.junit.Test;
  6. import java.util.List;
  7. public class UserDaoTest {
  8. @Test
  9. public void test(){
  10. //第一步:获取sqlSession对象
  11. SqlSession sqlSession = MybatisUtils.getSqlSession();
  12. //方式一:
  13. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  14. List<User> userList = userMapper.getUserList();
  15. for(User user : userList){
  16. System.out.println(user);
  17. }
  18. //关闭sqlSession
  19. sqlSession.close();
  20. }
  21. }

运行抛出异常(maper注册了,依然出现问题)

原因是mapper.xml没有导出

  1. java.lang.ExceptionInInitializerError
  2. at com.study.dao.UserDaoTest.test(UserDaoTest.java:15)
  3. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  4. at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  5. at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  6. at java.lang.reflect.Method.invoke(Method.java:498)
  7. at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
  8. at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
  9. at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
  10. at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
  11. at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
  12. at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
  13. at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
  14. at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
  15. at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
  16. at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
  17. at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
  18. at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
  19. at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
  20. at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
  21. at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
  22. at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
  23. at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
  24. at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
  25. Caused by: org.apache.ibatis.exceptions.PersistenceException:
  26. ### Error building SqlSession.
  27. ### The error may exist in com/study/dao/UserMapper.xml
  28. ### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/study/dao/UserMapper.xml
  29. at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
  30. at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:80)
  31. at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:64)
  32. at com.study.utils.MybatisUtils.<clinit>(MybatisUtils.java:20)
  33. ... 23 more
  34. Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/study/dao/UserMapper.xml
  35. at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:121)
  36. at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:98)
  37. at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:78)
  38. ... 25 more
  39. Caused by: java.io.IOException: Could not find resource com/study/dao/UserMapper.xml
  40. at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:114)
  41. at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:100)
  42. at org.apache.ibatis.builder.xml.XMLConfigBuilder.mapperElement(XMLConfigBuilder.java:372)
  43. at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:119)
  44. ... 27 more

解决方法:

maven由于它的约定大于配置,我们之后可能遇到编写的配置文件,无法被导出或者生效的问题,解决方案

  1. <!--在build中配置resources,来防止我们资源导出失败-->
  2. <build>
  3. <resources>
  4. <resource>
  5. <directory>src/main/resources</directory>
  6. <includes>
  7. <include>**/*.properties</include>
  8. <include>**/*.xml</include>
  9. </includes>
  10. <filtering>true</filtering>
  11. </resource>
  12. <resource>
  13. <directory>src/main/java</directory>
  14. <includes>
  15. <include>**/*.properties</include>
  16. <include>**/*.xml</include>
  17. </includes>
  18. <filtering>true</filtering>
  19. </resource>
  20. </resources>
  21. </build>

完整的pom.xml文件

  1. <?xml version="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. <modelVersion>4.0.0</modelVersion>
  6. <!-- 父工程-->
  7. <groupId>com.study</groupId>
  8. <artifactId>Mybatis-study</artifactId>
  9. <packaging>pom</packaging>
  10. <version>1.0-SNAPSHOT</version>
  11. <modules>
  12. <module>study-01</module>
  13. </modules>
  14. <dependencies>
  15. <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
  16. <dependency>
  17. <groupId>mysql</groupId>
  18. <artifactId>mysql-connector-java</artifactId>
  19. <version>5.1.47</version>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.mybatis</groupId>
  23. <artifactId>mybatis</artifactId>
  24. <version>3.5.2</version>
  25. </dependency>
  26. <!-- https://mvnrepository.com/artifact/junit/junit -->
  27. <dependency>
  28. <groupId>junit</groupId>
  29. <artifactId>junit</artifactId>
  30. <version>4.12</version>
  31. <scope>test</scope>
  32. </dependency>
  33. </dependencies>
  34. <build>
  35. <resources>
  36. <resource>
  37. <directory>src/main/resources</directory>
  38. <includes>
  39. <include>**/*.properties</include>
  40. <include>**/*.xml</include>
  41. </includes>
  42. <filtering>true</filtering>
  43. </resource>
  44. <resource>
  45. <directory>src/main/java</directory>
  46. <includes>
  47. <include>**/*.properties</include>
  48. <include>**/*.xml</include>
  49. </includes>
  50. <filtering>true</filtering>
  51. </resource>
  52. </resources>
  53. </build>
  54. </project>

运行结果

  1. User{
  2. id='1', name='小明', pwd='12345'}
  3. User{
  4. id='2', name='张三', pwd='12345'}
  5. User{
  6. id='3', name='李四', pwd='12345'}
  7. Process finished with exit code 0

可能会遇到的问题

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

发表评论

表情:
评论列表 (有 0 条评论,123人围观)

还没有评论,来说两句吧...

相关阅读