1. 程式人生 > >mybatis逆向生成對映檔案實體類 單元測試test 增刪改查方法

mybatis逆向生成對映檔案實體類 單元測試test 增刪改查方法

package cn.itcast.ssm.mapper;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.itcast.ssm.po.Items;
import cn.itcast.ssm.po.ItemsExample;

public class ItemsMapperTest {

    private ApplicationContext applicationContext;
    
    private ItemsMapper itemsMapper;

    //在setUp這個方法得到spring容器
    @Before
    public void setUp() throws Exception {
        applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
        itemsMapper = (ItemsMapper) applicationContext.getBean("itemsMapper");
    }

    //根據主鍵刪除
    @Test
    public void testDeleteByPrimaryKey() {
        
    }

    //插入
    @Test
    public void testInsert() {
        //構造 items物件
        Items items = new Items();
        items.setName("手機");
        items.setPrice(999f);
        itemsMapper.insert(items);
    }

    //自定義條件查詢
    @Test
    public void testSelectByExample() {
        ItemsExample itemsExample = new ItemsExample();
        //通過criteria構造查詢條件 select * from where id=1 and name='筆記本3‘;
        ItemsExample.Criteria criteria = itemsExample.createCriteria();
        criteria.andNameEqualTo("筆記本3");

        //可能返回多條記錄
        List<Items> list = itemsMapper.selectByExample(itemsExample);
        
        System.out.println(list);
        
    }

    //根據主鍵查詢
    @Test
    public void testSelectByPrimaryKey() {
        Items items = itemsMapper.selectByPrimaryKey(1);
        System.out.println(items);
    }

    //更新資料
    @Test
    public void testUpdateByPrimaryKey() {
        
        //對所有欄位進行更新,需要先查詢出來再更新
        Items items = itemsMapper.selectByPrimaryKey(1);
        
        items.setName("水杯");
        
        itemsMapper.updateByPrimaryKey(items);
        //如果傳入欄位不空為才更新,在批量更新中使用此方法,不需要先查詢再更新
        //itemsMapper.updateByPrimaryKeySelective(record);
        
    }

}