使用XML完成CRUD操作
查询db_mybatis/tb_student中的学生数据,并完成添加/删除/更新操作。
1. 配置mybatis-cfg.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>
<!-- 将jdbc配置文件引入项目之中 -->
<properties resource="jdbc.properties"/>
<!-- 为项目中的model声明类型别名,如果没有声明则在使用时需要包名.类名 -->
<typeAliases>
<typeAlias alias="Student" type="com.java1234.model.Student"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<!-- 类似hibernate 引入映射文件或者在使用注解时引入pojo类 -->
<mappers>
<mapper resource="com/java1234/mappers/StudentMapper.xml"/>
</mappers>
</configuration>
2. 添加jdbc.properties文件
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_mybatis
jdbc.username=root
jdbc.password=123456
3. Student.java
package com.java1234.model;
public class Student {
private int id;
private String name;
private int age;
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;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
4. StudentMapper.java
package com.java1234.mappers;
import java.util.List;
import com.java1234.model.Student;
public interface StudentMapper {
public int addStudent(Student student);
public int updateStudent(Student student);
public int deleteStudent(int stuId);
public Student findStduentById(int stuId);
public List<Student> findAllStduent();
}
5. 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.java1234.mappers.StudentMapper">
<!-- 声明插入:
<insert id="映射接口中方法名" parameterType="传入参数类型:需要mybatis-config.xml中起别名,没有起别名需要用包名.类名">
#{name} -> Student对象中的属性名
-->
<insert id="addStudent" parameterType="Student">
insert into tb_student values(null, #{name},#{age})
</insert>
<!-- 声明更新:与insert非常类似,只需要注意sql语句的正确性 -->
<update id="updateStudent" parameterType="Student">
update tb_student set age=#{age} where name=#{name}
</update>
<!-- 声明删除:
delete from tb_student where id=#{stuId},注意stuId与Mapper接口中deleteStudent的形参名对应
-->
<delete id="deleteStudent" parameterType="Integer">
delete from tb_student where id=#{stuId}
</delete>
<!-- 声明只有一个返回值的查询:
resultType="Student" 与public Student findStduentById(int stuId);对应
-->
<select id="findStduentById" parameterType="Integer" resultType="Student">
select * from tb_student where id=#{stuId}
</select>
<!-- 声明多结果查询:
需要声明一个自定义的结果集对象来存储查询到的结果
-->
<select id="findAllStduent" resultMap="StudentMap">
select * from tb_student
</select>
<!-- 声明自定义结果集:
type="Student":集合中的子元素都是Student对象
<id property="id" column="id"/>:只有主键才能够使用这个。property都是Student实体类中的属性,column对应数据库表中的行
<result property="name" column="name"/>:其他属性使用,property都是Student实体类中的属性,column对应数据库表中的行
-->
<resultMap type="Student" id="StudentMap">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
</resultMap>
</mapper>
6. 测试类 - ApplicationText.java
6.1获取Mybatis的SqlSession对象
类似Hibernate通过sqlSession对象完成所有的数据库操作。通过sqlSessionFactory获取。
package com.java1234.utils;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
private static SqlSessionFactory getSqlSessionFactory(){
if(sqlSessionFactory == null){
try {
InputStream inputStream = Resources.getResourceAsStream("mybatis-cfg.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
return sqlSessionFactory;
}
public static SqlSession getSqlSession(){
return getSqlSessionFactory().openSession();
}
}
package com.java1234.Mybatis.MybatisCRUD;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import com.java1234.mappers.StudentMapper;
import com.java1234.model.Student;
import com.java1234.utils.MybatisUtils;
import junit.framework.TestCase;
public class ApplicationTest extends TestCase {
SqlSession sqlSession = null;
@Override
protected void setUp() throws Exception {
sqlSession = MybatisUtils.getSqlSession();
}
@Override
protected void tearDown() throws Exception {
sqlSession.close();
}
@Test
public void testInsert(){
StudentMapper studentMapper = (StudentMapper) sqlSession.getMapper(StudentMapper.class);
Student student = new Student();
student.setName("Lily");
student.setAge(25);
int i = studentMapper.addStudent(student);
if(i != 0){
System.out.println("Insert success!");
}
sqlSession.commit();
}
@Test
public void testUpdate(){
StudentMapper studentMapper = (StudentMapper) sqlSession.getMapper(StudentMapper.class);
Student student = new Student();
student.setName("Lily");
student.setAge(57);
int i = studentMapper.updateStudent(student);
if(i != 0){
System.out.println("update success!");
}
sqlSession.commit();
}
@Test
public void testDelete(){
StudentMapper studentMapper = (StudentMapper) sqlSession.getMapper(StudentMapper.class);
int i = studentMapper.deleteStudent(7);
if(i != 0){
System.out.println("delete success!");
}
sqlSession.commit();
}
@Test
public void testFindById(){
StudentMapper studentMapper = (StudentMapper) sqlSession.getMapper(StudentMapper.class);
Student student = studentMapper.findStduentById(1);
if(student != null){
System.out.println("select success! "+student);
}
sqlSession.commit();
}
@Test
public void testFindAll(){
StudentMapper studentMapper = (StudentMapper) sqlSession.getMapper(StudentMapper.class);
List<Student> students = studentMapper.findAllStduent();
for(Student student : students){
System.out.println(student);
}
sqlSession.commit();
}
}
总结一下
使用Mybaitis,相较于Hibernate更加轻量级,语法也更加人性化。使用XML配置一个完整的Mybatis实例,只需要配置如下部分:
(1)mybatis-cfg.xml文件 - 完成app级别的配置
主要包含1. 配置jdbc连接器,2. 引入映射文件/映射类(Annotation),当然对于需要起别名的app也需要在本文件中声明别名。
(2)pojo类 - 对应数据库中的表
(3)**Mapper.java - 在接口中定义操作db的方法,类似与DAO类
(4)**Mapper.xml - 使用xml配置,对应Mapper接口中的每一个方法。