创建一个简单的MyBatis入门程序,实现对学生信息的增删改查功能(基于XML配置)
一、新建一个Java工程,导入MyBatis核心jar包、日志相关的jar包以及连接Oracle数据库所需驱动包,目录结构如下
二、创建MyBatis核心配置文件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>
<!-- 引入资源文件 -->
<properties resource="db.properties"></properties>
<environments default="development">
<environment id="development">
<!-- 配置事务管理方式 -->
<transactionManager type="JDBC" />
<!-- 配置数据源 -->
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<!-- 指定映射文件 -->
<mappers>
<mapper resource="com/heaven/dao/StudentMapper.xml"/>
</mappers>
</configuration>
三、创建POJO类Student.java
package com.heaven.bean;
import java.util.Date;
public class Student {
private Integer studId;
private String name;
private String email;
private Date dob;
public Student() {
}
public Student(Integer studId, String name, String email, Date dob) {
this.studId = studId;
this.name = name;
this.email = email;
this.dob = 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;
}
@Override
public String toString() {
return "Student [studId=" + studId + ", name=" + name + ", email=" + email + ", dob=" + dob + "]";
}
}
四、创建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.heaven.dao.StudentMapper">
<!-- 保存学生信息 -->
<insert id="saveStudent" parameterType="com.heaven.bean.Student">
insert into students(stud_id,name,email,dob) values(#{studId},#{name},#{email},#{dob})
</insert>
<!-- 根据Id查询学生信息 -->
<select id="selectById" parameterType="Integer" resultType="com.heaven.bean.Student">
select stud_id studId,name,email,dob from students where stud_id = #{id}
</select>
<!-- 查询所有学生信息 -->
<select id="findAll" resultType="com.heaven.bean.Student">
select stud_id studId,name,email,dob from students
</select>
<!-- 更新学生信息 -->
<update id="updateStudent" parameterType="com.heaven.bean.Student">
update students set email = #{email} where stud_id = #{studId}
</update>
<!-- 根据Id删除学生信息 -->
<delete id="deleteById" parameterType="Integer">
delete from students where stud_id = #{id}
</delete>
</mapper>
五、创建映射接口StudentMapper.java
package com.heaven.dao; import java.util.List; import com.heaven.bean.Student; public interface StudentMapper { /** * 保存学生信息 * @param stu 入参 :Student对象 */ void saveStudent(Student stu); /** * 根据id查询学生信息 * @param id 入参:id * @return 返回值:Student对象 */ Student selectById(Integer id); /** * 查询所有学生信息 */ List<Student> findAll(); /** * 删除学生信息 * @param id 入参:id */ void deleteById(Integer id); /** * 更新学生信息:入参:Student对象 * @param stu */ void updateStudent(Student stu); }
六、编写JUnit测试类Test.java
package com.heaven.test; import java.io.IOException; import java.util.Date; import java.util.List; 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.Before; import org.junit.Test; import com.heaven.bean.Student; import com.heaven.dao.StudentMapper; public class TestMapper { private SqlSessionFactory factory; private SqlSession sqlSession; private StudentMapper mapper; /** * 执行测试方法之前执行,用于创建SqlSessionFactory并获取SqlSession对象 */ @Before public void init() { try { //创建SqlSessionFactory,加载mybatis核心配置文件 factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); //获取SqlSession接口对象 sqlSession = factory.openSession(); //使用动态代理方式创建mapper接口的代理对象 mapper = sqlSession.getMapper(StudentMapper.class); } catch (IOException e) { e.printStackTrace(); } } @Test public void saveStudent() { Student stu = new Student(1001,"TOM","123456",new Date()); mapper.saveStudent(stu); sqlSession.commit(); sqlSession.close(); } @Test public void selectById(){ Student student = mapper.selectById(1001); System.out.println(student); } @Test public void findAll(){ List<Student> list = mapper.findAll(); System.out.println(list.toString()); } @Test public void updateStudent(){ Student stu = new Student(1001, "Tom", "123@", new Date()); mapper.updateStudent(stu); sqlSession.commit(); } @Test public void deleteById(){ mapper.deleteById(1001); sqlSession.commit(); } }
七、其他相关文件
数据库连接配置db.properties
driver=oracle.jdbc.driver.OracleDriver url=jdbc:oracle:thin:@127.0.0.1:1521:XE username=heaven password=heaven
log4j配置文件log4j.properties
#设置日志输出级别,输出方式
log4j.rootLogger=DEBUG, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n #show sql log4j.logger.java.sql.ResultSet=INFO log4j.logger.org.apache=INFO log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG