Mybatis入门例子
Mybatis是轻量级的持久化框架,的确上手非常快.
Mybatis大体上的思路就是由一个总的config文件配置全局的信息,比如mysql连接信息等。然后再mapper中指定查询的sql,以及参数和返回值。
在Service中直接调用这个mapper即可。
依赖的jar包
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
</dependency>
主要的mybatis配置文件
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置类别名 -->
<typeAliases>
<typeAlias alias="Student" type="mybatis.Student"/>
</typeAliases>
<!-- 配置mysql连接 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://192.168.56.101:3306/mysql"/>
<property name="username" value="root"/>
<property name="password" value="123qwe"/>
</dataSource>
</environment>
</environments>
<!-- 配置mapper -->
<mappers>
<mapper resource="StudentMapper.xml"/>
</mappers>
</configuration>
创建SqlSession工厂
public class MyBatisSqlSessionFactory {
private static SqlSessionFactory sqlSessionFactory;
public static SqlSessionFactory getSqlSessionFactory(){
if(sqlSessionFactory == null){
InputStream inputStream;
try{
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (IOException e){
System.out.println(e.getMessage());
}
}
return sqlSessionFactory;
}
public static SqlSession openSession(){
return getSqlSessionFactory().openSession();
}
}
创建Student类:
public class Student {
private Integer studId;
private String name;
private String email;
private Date dob;
public Integer getStudId() {
return studId;
}
public void setStudId(Integer studId) {
this.studId = studId;
}
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 Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
}
创建Mapper配置文件
<?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">
<mapper namespace="mybatis.StudentMapper">
<resultMap type="Student" id="StudentResult">
<id property="studId" column="stud_id"/>
<result property="name" column="name"/>
<result property="email" column="email"/>
<result property="dob" column="dob"/>
</resultMap>
<select id="findAllStudents" resultMap="StudentResult">
SELECT * FROM STUDENTS
</select>
<select id="findStudentById" parameterType="int" resultType="Student">
SELECT STUD_ID AS STUDID,NAME,EMAIL,DOB FROM STUDENTS WHERE STUD_ID=#{ID}
</select>
<insert id="insertStudent" parameterType="Student">
INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(#{studId},#{name},#{email},#{dob})
</insert>
</mapper>
创建Mapper接口
public interface StudentMapper {
List<Student> findAllStudents();
Student findStudentById(Integer id);
void insertStudent(Student student);
}
创建服务类和测试类
public class StudentService {
public List<Student> findAllStudents(){
SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
try{
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
return studentMapper.findAllStudents();
}finally {
sqlSession.close();
}
}
public Student findStudentById(Integer studId){
SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
return studentMapper.findStudentById(studId);
}finally {
sqlSession.close();
}
}
public void createStudent(Student student){
SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
try{
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
studentMapper.insertStudent(student);
sqlSession.commit();
}finally {
sqlSession.close();
}
}
}
单元测试类
public class StudentServiceTest {
private static StudentService studentService;
@BeforeClass
public static void setup(){
studentService = new mybatis.StudentService();
}
@AfterClass
public static void teardown(){
studentService = null;
}
@Test
public void testFindAllStudents(){
List<Student> students = studentService.findAllStudents();
Assert.assertNotNull(students);
for(Student student:students){
System.out.println(student);
}
}
@Test
public void testFindStudentById(){
Student student = studentService.findStudentById(1);
Assert.assertNotNull(student);
System.out.println(student);
}
@Test
public void testCreateStudent(){
Student student = new Student();
student.setStudId(3);
student.setName("student_"+3);
student.setEmail("student_"+3+"@email.com");
student.setDob(new Date());
studentService.createStudent(student);
Student newStudent = studentService.findStudentById(3);
Assert.assertNotNull(newStudent);
}
}
数据库脚本
create table STUDENTS(
stud_id int(11) not null auto_increment,
name varchar(50) not null,
email varchar(50) not null,
dob date default null,
primary key(stud_id)
);
insert into STUDENTS(stud_id,name,email,dob) values(1,"student1","student1@email.com","1999-08-08");
insert into STUDENTS(stud_id,name,email,dob) values(2,"student2","student2@email.com","2000-01-01");
select * from STUDENTS;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
2013-08-28 最优的cuda线程配置