1、表结构2、创建Maven项目,在pom.xml中引入以下代码:3、创建Student类4、Dao层5、jdbc.properties6、mybatis-config.xml7、MybatisUtils工具类8、测试类
1、表结构 2、创建Maven项目,在pom.xml中引入以下代码:3、创建Student类junit junit 4.12 org.mybatis mybatis 3.5.7 mysql mysql-connector-java 5.1.47 src/main/java ***.xml false src/main/resources ***.xml false
写上构造方法、setter和getter方法,还有toString方法
public class Student {
private String Sno;
private String Sname;
private String Ssex;
private int Sage;
private String Sdept;
4、Dao层
StudentMapper接口:
public interface StudentMapper {
//查询所有学生
List selectStudent();
}
StudentMapper.xml
5、jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver #如果使用的事 MySql 8.0+ ,则需加上一个时区配置&serverTimezone=Asia/Shanghai jdbc.url=jdbc:mysql://localhost:3306/test1?useSSL=true&useUnicode=true&characterEncoding=utf8 jdbc.username=root jdbc.password=root6、mybatis-config.xml
7、MybatisUtils工具类
package com.luhang.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 MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource="mybatis-config.xml";
InputStream inputStream= Resources.getResourceAsStream(resource);
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//获取SqlSession连接
public static SqlSession getSession(){
return sqlSessionFactory.openSession();
}
}
8、测试类
public class Test {
@org.junit.Test
public void test(){
SqlSession sqlSession= MybatisUtils.getSession();
StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
List students=studentMapper.selectStudent();
for (Student student: students){
System.out.println(student);
}
//注意点:增、删、改操作需要提交事务!
//提交事务,重点!不写的话不会提交到数据库
//session.commit();
sqlSession.close();
}
}
一个简单的mybatis项目例子,到此结束!



