思路 搭建环境->导入myBatis->编写代码-》测试
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,'张三','123'),
(3,'李四','123')
1.新建maven新项目
2.删除src目录
3.导入maven依赖
1.编写mybatis核心配置文件
2.编写mybatis工具类
public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { //使用mybatis第一步获取slqSession对象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { throw new RuntimeException(e); } } //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例 //SqlSession 提供了在数据库执行 SQL 命令所需的所有方法 public static SqlSession getSqlsession(){ SqlSession sqlSession = sqlSessionFactory.openSession(); return sqlSession ; } }
public class User { private int id; private String name ; private String pwd; public User() { } public User(int id, String name, String pwd) { 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 + '\'' + '}'; } }
<?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绑定一个对应的dao接口或这mapper接口--> <mapper namespace="dao.UserDao"> <!-- select查询语句--> <select id="getUserList" resultType="pojo.User"> select * from mybatis.user </select> </mapper>
每一个都要注册
<mappers> <mapper resource="dao.UserMapper.xml"/> </mappers>
开启资源过滤
<build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>