在resources目录下,创建一个sqlMapConfig.xml文件,用于做一些全局的mybatis基本的配置,
【一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义】
浏览器打开:qq.cn.hn/FTf 开源分享
例如数据库连接信息,事务,mapper映射文件路径,日志实现,类的别名,也包含了分页插件的基本配置。
Student实体类
package pojo;
public class Student {
private Integer id;
private String name;
private String email;
private Integer age;
public Student() {
}
public Student(Integer id, String name, String email, Integer age) {
this.id = id;
this.name = name;
this.email = email;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return “Student{” +
“id=” + id +
“, name=’” + name + ‘’’ +
“, email=’” + email + ‘’’ +
“, age=” + age +
‘}’;
}
}
mapper接口
package mapper;
import pojo.Student;
import java.util.List;
public interface StudentMapper {
//查询所有学生
List selectAll();
}
Mapper映射文件
<?xml version="1.0" encoding="UTF-8" ?>select * from student order by id
在sqlMapConfig文件中指定Mapper文件位置
编写MyBatisUtils
package 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;
/**
- 工具类:创建SqlSession对象
*/
public class MyBatisUtil {
private static SqlSessionFactory factory = null;
static {
String config=“sqlMapConfig.xml”;
try {
InputStream inputStream =Resources.getResourceAsStream(config);
factory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//创建方法,获取SqlSession对象
public static SqlSession getSqlSession(){
SqlSession session = null;
if( factory != null ){
session =factory.openSession();// openSession(true);
}
return session;
}
}