1. 程式人生 > >MyBatis對錶執行CRUD(增刪改查)操作

MyBatis對錶執行CRUD(增刪改查)操作

Mybatis的好處是sql與程式碼的分離,以及能夠輕鬆使用自定義的sql

下面以小例子的形式來講解一下Mybatis的增刪改查:

有以下兩種方式

1.基於XML

2.基於Annotation

前提:資料庫那邊只需要建立一張user表:create table user (id int,name text,age int);

第一種:基於XML配置檔案的CRUD

首先看一下project結構


其中:

lib中的jar包都可以在網上下載到,如果直接使用Maven則無需手動下載了;

conf.xml是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>
	<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/mybatis" />
				<property name="username" value="root" />
				<property name="password" value="930712" />
			</dataSource>
		</environment>
	</environments>
	
	<mappers>
		
		<!-- 註冊userMapper.xml檔案, 
         userMapper.xml位於com.mapping這個包下,所以resource寫成com/mapping/userMapper.xml-->
         <mapper resource="com/mapping/userMapper.xml"/>
        
	</mappers>
</configuration>
重要的是dataSource屬性和mapper屬性;

userMapper.xml中定義了sql,其內容如下:

<?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.mapping.userMapper">
	
	<!-- 
        根據id查詢得到一個user物件
     -->
	<select id="getUser" parameterType="int" resultType="com.xjtu.User">
		select * from user where id=#{id}
    </select>
    
    <!-- 
        查詢全部
     -->
    <select id="getAll" resultType="com.xjtu.User">
		select * from user
    </select>
    
    <!-- 
        插入一條記錄
     -->
    <insert id="insertUser" parameterType="com.xjtu.User">
    	insert into user(id,name,age) values(#{id},#{name},#{age})
    </insert>
    
    <!-- 
        根據id刪除一條記錄
     -->
     <delete id="deleteById" parameterType="int">
     	delete from user where id =#{id}
     </delete>
   <!-- 
        更改一條記錄
     -->
     <update id="updateUser" parameterType="com.xjtu.User">
     	update user set name=#{name},age=#{age} where id=#{id} 
     </update>
</mapper>

在標籤中編寫查詢的SQL語句, 例如:設定select標籤的id屬性為getUser,id屬性值必須是唯一的,不能夠重複
使用parameterType屬性指明查詢時使用的引數型別,resultType屬性指明查詢返回的結果集型別
resultType="com.xjtu.User"就表示將查詢結果封裝成一個User類的物件返回
User類就是user表所對應的實體類

User類:

package com.xjtu;

public class User {
	
	private int id;
	private String name;
	private int age;
	
	public void set(int id,String name,int age){
		this.id=id;
		this.name=name;
		this.age=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 "User [age=" + age + ", id=" + id + ", name=" + name + "]";
	}
	
}
最終,測試類:
package com.xjtu;

import java.io.IOException;
import java.io.Reader;
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;

public class Test {
	
	private String statement="";
	private SqlSession session=null;

	@Before
	public void init() throws IOException{
		// mybatis的配置檔案
		String resource = "conf.xml";
		
		// 使用MyBatis提供的Resources類載入mybatis的配置檔案(它也載入關聯的對映檔案)
		Reader reader = Resources.getResourceAsReader(resource);
		// 構建sqlSession的工廠
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
				.build(reader);

		// 建立能執行對映檔案中sql的sqlSession
		session = sessionFactory.openSession();
	}
	
	
	@org.junit.Test
	public void testQueryById(){
		//getUser是select標籤的id屬性值,通過select標籤的id屬性值就可以找到要執行的SQL
		statement = "com.mapping.userMapper.getUser";// 對映sql的標識字串
		// 執行查詢返回一個唯一user物件的sql
		User user = session.selectOne(statement, 1);
		System.out.println(user);
		session.close();
	}
	
	@org.junit.Test
	public void testQueryAll(){
		statement = "com.mapping.userMapper.getAll";
		List<User> userList = session.selectList(statement);
		for (User user2 : userList) {
			System.out.println(user2);
		}
		
		session.close();
	}
	
	@org.junit.Test
	public void tesInsert(){
		statement = "com.mapping.userMapper.insertUser";
		User user=new User();
		user.set(5,"ldx", 15);
		int result=session.insert(statement, user);
		
		if (result==1) {
			session.commit();
		}
		System.out.println(result);
		session.close();
	}
	
	@org.junit.Test
	public void testDelete(){
		statement = "com.mapping.userMapper.deleteById";
		int result=session.delete(statement, 2);//id=2
		
		if (result==1) {
			session.commit();
		}
		System.out.println(result);
		session.close();
	}
	
	@org.junit.Test
	public void testUpdate(){
		statement = "com.mapping.userMapper.updateUser";
		User user=new User();
		user.setId(3);
		user.setAge(30);
		user.setName("wdl");
		int result=session.update(statement, user);
		
		if (result==1) {
			session.commit();
		}
		session.close();
		
	}

}



第二種:基於Annotation(註解)的CRUD


這裡主要是把userMapper.xml用UserMapperI來代替了;

在conf.xml中把<mappers></mappers>標籤中的<mapper resource="com/mapping/userMapper.xml"/>

改為:<mapper class="com.mapping.UserMapperI" />

即把sql的定義用一個介面來定義,注意:

不需要手動實現該介面,具體的實現類由MyBatis幫我們動態構建出來,直接拿來使用即可。

UserMapperI的原始碼為:

package com.mapping;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.xjtu.User;

public interface UserMapperI {

	// 使用@Insert註解指明insert方法要執行的SQL
	@Insert("insert into user values(#{id},#{name},#{age})")
	public int insert(User user);

	@Delete("delete from user where id=#{id}")
	public int delete(int id);

	@Update("update user set name=#{name},age=#{age} where id=#{id}")
	public int update(User user);

	@Select("select * from user where id=#{id}")
	public User queryById(int id);

	@Select("select * from user")
	public List<User> queryAll();

}
最終,測試類原始碼:
package com.xjtu;

import java.io.IOException;
import java.io.Reader;
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 com.mapping.UserMapperI;

public class Test {

	private SqlSession session = null;
	private UserMapperI mapper = null;

	@Before
	public void init() throws IOException {
		// mybatis的配置檔案
		String resource = "conf.xml";

		// 使用MyBatis提供的Resources類載入mybatis的配置檔案(它也載入關聯的對映檔案)
		Reader reader = Resources.getResourceAsReader(resource);
		// 構建sqlSession的工廠
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
				.build(reader);

		// 建立能執行對映檔案中sql的sqlSession
		session = sessionFactory.openSession();
		// session = sessionFactory.openSession(boolean
		// autoCommit);//true自動提交增刪改
		mapper = session.getMapper(UserMapperI.class);
	}

	@org.junit.Test
	public void testQueryById() {

		User user = mapper.queryById(1);
		System.out.println(user);
		session.close();
	}

	@org.junit.Test
	public void testQueryAll() {

		List<User> userList = mapper.queryAll();
		for (User user : userList) {
			System.out.println(user);
		}
		session.close();
	}

	@org.junit.Test
	public void tesInsert() {

		User user = new User();
		user.set(6, "wp", 24);
		int result = mapper.insert(user);

		if (result == 1) {
			session.commit();
		}
		session.close();
	}

	@org.junit.Test
	public void testDelete() {

		int result = mapper.delete(4);

		if (result == 1) {
			session.commit();
		}
		session.close();
	}

	@org.junit.Test
	public void testUpdate() {

		User user = new User();
		user.setId(3);
		user.setAge(30);
		user.setName("wyx");
		int result = mapper.update(user);

		if (result == 1) {
			session.commit();
		}
		session.close();

	}

}
注:

1.如果你沒有設定SqlSession為自動commit

在執行增刪改後一定要執行SqlSession的commit方法,來把操作儲存到資料庫,否則會有執行成功,但資料庫無變化的問題;

自動commit設定:

SqlSession session = sessionFactory.openSession(autoCommit);//autoCommit為true,自動提交增刪改

2.以上兩種方式都比較常用,相對來說,基於註解會簡潔一點;