本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2024-11(1)

第一个MyBatis程序

发布于2021-03-10 18:54     阅读(554)     评论(0)     点赞(26)     收藏(3)


搭建数据库:

CREATE DATABASE `mybatis`;
USE `mybatis`;
/* */ CREATE TABLE `user`( `id` INT(20) NOT NULL PRIMARY KEY, `name` VARCHAR(30) DEFAULT NULL, `pwd` VARCHAR(30) DEFAULT NULL )ENGINE = INNODB DEFAULT CHARSET = utf8; /* */ INSERT INTO `user` (`id`,`name`,`pwd`) VALUES (1,'汪瑞杰','123456'), (2,'汪瑞杰','528582'), (3,'汪瑞杰','286353');

新建项目(maven)

导入mybatis,mysql,junit依赖 pom.xml
<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.perwrj</groupId>
  <artifactId>mybaits</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  
  
  <!-- 导入依赖 -->
  <dependencies>
  <!-- mysql驱动 -->
  <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.46</version>
  </dependency>
      <!-- mybatis -->
      <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>
  <!-- junit -->
  <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
  </dependency>
  
  </dependencies>
</project>
编写mybaits核心配置文件:mybatis-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/mybatis?useUnicode=ture&amp;characterEncoding=UTF-8&amp;serverTimezone=GMT%2B8"/>
        <property name="username" value="root"/>
        <property name="password" value="344165"/>
      </dataSource>
    </environment>
  </environments>
 <!-- 每一个Mapper.xml文件必须在mybaits核心配置文件中注册 -->
 <mappers>
      <mapper resource="com/perwrj/dao/UserMapper.xml"/>
          
  </mappers>

</configuration>
编写mybatis核心工具类:
package com.perwrj.utils;

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

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * (工厂模式)sqlSessionFactory --> sqlSession
 * @author wangruijie
 *
 */
public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //获取SqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            // TODO: handle exception
        }
    }
    
    
//    既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
//    SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
//    你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句
    
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
         
    }
}

编写代码:

  • 实体类
package com.perwrj.pojo;

public class User {
    private int id;
    private String name;
    private String pwd;
    public User() {
        super();
        // TODO Auto-generated constructor stub
    }
    public User(int id, String name, String pwd) {
        super();
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }
    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 String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", pwd=" + pwd + "]";
    }
    
}
  • UserMapper接口(原UserDao.java)
package com.perwrj.dao;

import java.util.List;

import com.perwrj.pojo.User;

public interface UserMapper {
    List<User> getUserList();
}
  • UserMapper.xml配置文件(原UserDaoImpl实现类转换的Mapper文件)
<?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绑定一个对应的Mapper/Dao接口 -->
<mapper namespace="com.perwrj.dao.UserMapper">
<!-- 查询 id=“重写的方法名” resultType=“返回值类型(全类名)” -->
  <select id="getUserList" resultType="com.perwrj.pojo.User">
    select * from mybatis.user
  </select>
</mapper>

测试(junit):

编写测试文件
package com.perwrj.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import com.perwrj.pojo.User;
import com.perwrj.utils.MyBatisUtil;

public class UserMapperTest {
    @Test
    public void test() {
        //获得SqlSession对象,
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        
        try {
//            方式一:getMapper执行sql:更加简洁,类型更加安全,推荐使用
            
              UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<User>
              userList = userMapper.getUserList();
            
              for (User user : userList) { System.out.println(user); }
    
            //方式一结束
            
//            方式二:老方法,不建议使用,
            /*
             * List<User> list =
             * sqlSession.selectList("com.perwrj.dao.UserMapper.getUserList");
             * 
             * for (User object : list) { System.out.println(object); }
             */
            //方式二结束
        }catch(Throwable e) {
            e.printStackTrace();
        }finally {
//            关闭sqlSession
            sqlSession.close();
        }    
    }
}

org.apache.ibatis.binding.BindingException: Type interface com.perwrj.dao.UserMapper is not known to the MapperRegistry.(没有在mybatis-config.xml核心配置文件中注册Mapper)
 java.lang.ExceptionInInitializerError(初始化异常失败,没有找到UserMapper.xml文件)

可能遇到的错误

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

2021-02-24



所属网站分类: 技术文章 > 博客

作者:Djfj

链接:http://www.javaheidong.com/blog/article/112363/eec28b5763b82cbeab76/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

26 0
收藏该文
已收藏

评论内容:(最多支持255个字符)