1.在数据库新建一个数据库,然后再建一个表,我这里如下图所示
2.新建一个maven工程
3.在工程pom文件导入依赖
依赖内容为
mysql
mysql-connector-java
5.1.47
org.mybatis
mybatis
3.5.3
junit
junit
4.12
test
编写好后等待maven自动导入依赖。
4.导入好以后删除原工程src源文件,新建一个mybatis module
我这里的名字mybatis_01。
5.编写javabean和接口
package com.atguigu.bean;
/**
* @author hjystart
* @create 2021-04-07 20:09
*/
public class Emplooy {
private Integer id;
private String empname;
private Integer gender;
private String email;
public Emplooy() {
}
public Emplooy(Integer id, String empname, Integer gender, String email) {
this.id = id;
this.empname = empname;
this.gender = gender;
this.email = email;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Emplooy{" +
"id=" + id +
", empname='" + empname + '\'' +
", gender=" + gender +
", email='" + email + '\'' +
'}';
}
}
package com.atguigu.dao;
import com.atguigu.bean.Emplooy;
/**
* @author hjystart
* @create 2021-04-07 20:14
*/
public interface EmplooyDao {
public Emplooy getEmplooyById(Integer id);
}
6.编写配置文件
在resource目录下新建一个mybatis核心配置文件
配置内容为:
编写接口配置文件,我这里的名字为EmplooyDao.xml
内容为:
配置完成,最后编写测试代码
import com.atguigu.bean.Emplooy;
import com.atguigu.dao.EmplooyDao;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
public class MyBatisTest {
// 工厂一个
@Test
public void test02() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession opensession=sqlSessionFactory.openSession();
EmplooyDao emplooyDao=opensession.getMapper(EmplooyDao.class);
Emplooy emplooy=emplooyDao.getEmplooyById(1);
System.out.println(emplooy);
}
}
其实到这里已经全部编写完成,但是还会有一个小错误,找不到EmplooyDao.xml文件,在这里需要在pom.xml配置如下代码:在这里插入代码片 <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>