1. 程式人生 > >Mybatis - 使用XML配置完成CRUD操作

Mybatis - 使用XML配置完成CRUD操作

使用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介面中的每一個方法。

 

>> 使用Annotation完成Mybatis CRUD