MyBatis框架使用(一)

时间:2022-04-12 05:11:31

首先声明下:下面大部分代码取自传智播客视频。

以下代码尽供参考,学习之用。若有问题请联系本人。qq362601125

首先整个工程的结构图如下所示:

MyBatis框架使用(一)

Mybatis一共有两个配置文件:myBatis-config.xml和实体类对应的XXXMapper.xml文件(这里以StudentMapper.xml为例)

Mybatis文件存放在src目录下

StudentMapper.xml和实体类Student在同一个目录下

整体的结构就是这个样子。

首先创建实体类Student:

package com.robert.Bean;

public class Student
{
private int id;
private String name;
private int age;
private String birthday;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}

public String toString() {
return "id="+id+"\tname="+name+"\tage="+age+"\tbirthday="+birthday;
}
}

Student对应的StudentMapper.xml文件如下所示:

<?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="com.robert.Bean.Student">
<select id="selectStudents" resultType="com.robert.Bean.Student">
select * from Student;
</select>
</mapper>

myBatis-config.xml配置文件如下:

<?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>
<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://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/robert/Bean/StudentMapper.xml"/>
</mappers>
</configuration>

测试程序如下:

package com.robert.test.Student;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

import org.apache.ibatis.io.*;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.robert.Bean.*;

public class StudentTest
{
public static void main(String[] args)
{
String resource = "myBatis-config.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sessionFactory.openSession();
List<Student> students = session.selectList("selectStudents");

for(Student stu:students)
{
System.out.println(stu);
}
reader.close();
session.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}


!!!

注意:在工程中要加入mysql驱动和mybatis.jar

建表的语句如下:

MyBatis框架使用(一)

 

应该没什么问题了。

 

javaQQ交流群3728967,欢迎加入。