3. MyBatis基於註解的CRUD

    前面說了基於 PersonMappe.xml 配置文件的操作, 現在咱們說一下基於註解的配置如何操作.

    一般我們不用基於註解的配置.

    大體瞭解一下吧,

  首先, 要想使用基於註解的配置, 首先得把之前建立的 PersonMapper.xml 文件刪掉, 然後在 cong.xml 文件中接觸註冊.


一: 定義 SQL 映射的接口

package com.mybatis.entities;

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;

public interface PersonMapper {
	
	@Insert("INSERT INTO person(name, age) VALUES(#{name}, #{age})")
	public int insertPerson(Person Person);

	@Delete("DELETE FROM person WHERE id=#{id}")
	public int deletePersonById(int id);
			
	@Update("UPDATE person SET name=#{name},age=#{age} WHERE id=#{id}")
	public int updatePerson(Person Person);

	@Select("SELECT id, name, age FROM person WHERE id=#{id}")
	public Person getPersonById(int id);

	@Select("SELECT id, name, age FROM Person")
	public List<Person> getAllPerson();

	
}


二: 在conf.xml中註冊

    <mappers>
		<mapper class="com.mybatis.entities.PersonMapper"/>
    </mappers>



三: 調用

package com.mybatis.test;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import com.mybatis.entities.Person;
import com.mybatis.entities.PersonMapper;
import com.mybatis.util.MyBatisUtil;

public class TestPersonAnnotation {
	
	@Test
	public void testGetPersonById(){
		
		SqlSession session = MyBatisUtil.getSqlSession();
		PersonMapper mapper = session.getMapper(PersonMapper.class);
		Person person = mapper.getPersonById(2);
		System.out.println(person);
		
	}
	
}


    就這麼點東西.

    本篇博文源代碼點擊 http://pan.baidu.com/s/1YVgce 下載.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章