java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Mybatis模板

详解Mybatis模板(已优化)适合小白

作者:acmmmm

这篇文章主要介绍了Mybatis模板(已优化)适合小白,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

1.搭建数据库(我用的是mysql 5.5)

#创建一个mybatis数据库
create database `mybatis`;
 
#使用mybatis数据库
use `mybatis`;
 
#创建一个user表,有id、username、password三个字段
create table `user`(
  `id` int(10) not null primary key auto_increment,
  `username` varchar(30) default null,
  `password` varchar(30) default null
)engine=InnoDB default charset=utf8;
 
#插入数据
insert into `user`(`username`,`password`) values
('张三',123456),
('李四',123456),
('王五',123456);

2.导入mybatis相关的jar包(COPY,建议创建一个父子项目)

<dependencies>
    <dependency>
<!--mysql依赖包-->
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.19</version>
    </dependency>
<!--mybatis依赖包-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.2</version>
    </dependency>
<!--junit依赖包,为什么要用junit依赖包?@Test做单元测试用的-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
  </dependencies>
 
<!--maven静态资源过滤问题:配置报错,不设置会报错:ExceptionInInitializerError-->
  <build>
  <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>

3.编写MyBatisUtil工具类(COPY,低层原理还没有搞懂,直接复制的条件是要创建一个mybatis-config.xml文件  文件名要一致)

package com.kuang.utils;
 
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 
import java.io.IOException;
import java.io.InputStream;
 
public class MybatisUtil {
  private static SqlSessionFactory sqlSessionFactory;
  static{
    try {
      String resource = "mybatis-config.xml";
      InputStream inputStream = Resources.getResourceAsStream(resource);
      //SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);因为重复定义导致空指针异常
      sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  public static SqlSession getSqlSession(){
    return sqlSessionFactory.openSession();
  }
 
}

4.1编写db.properties配置文件(COPY,是后来优化的)

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username=root
password=root

4.2编写MyBatis核心配置文件(COPY,mybatis-config.xml,已优化)

<?xml version="1.0" encoding="UTF8" ?>
<!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">
<!--第一个问题:
com.mysql.jdbc.Driver和mysql-connector-java 5一起用。
com.mysql.cj.jdbc.Driver和mysql-connector-java 6+ 一起用。
第二个问题:
serverTimezone=Asia/Shanghai 要加时区,不加时区会报错
-->
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${passwprd}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="com/super/dao/UserMapper.xml"/>
  </mappers>
</configuration>

5.编写User实体类

public class User {
  
  private int id; //id
  private String name;  //姓名
  private String pwd;  //密码
  
  //构造,有参,无参
  //set/get
  //toString()
  
}

6.编写Mapper接口类(Mapper.java)

package com.kuang.dao;
 
import com.kuang.pojo.User;
 
import java.util.List;
 
public interface Mapper {
  List<User> getUserList();
}

7.编写mapper.xml配置文件

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.super.dao.UserDao">
  <select id="getUserList" resultType="com.kuang.pojo.User">
  select * from mybatis.user;
 </select>
</mapper>

8.编写测试类

package com.kuang.dao;
 
import com.kuang.pojo.User;
import com.kuang.utils.Mybatise;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
 
import java.util.List;
 
public class UserDaoTest {
  @Test
  public void test(){
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    UserDao mapper = sqlSession.getMapper(Mapper.class);
    List<User> userList = mapper.getUserList();
    for(User user:userList){
      System.out.println(user);
    }
    //sqlSession.commit();增删改需要添加事务
    sqlSession.close();
  }
}

到此这篇关于Mybatis模板(已优化)适合小白的文章就介绍到这了,更多相关Mybatis模板内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文