20.Mybatis逆向工程自動(dòng)生成代碼

gitHub地址:https://github.com/Ching-Lee/generatorSqlmapCustom

1.什么是逆向工程

mybatis需要程序員自己編寫sql語(yǔ)句,mybatis官方提供逆向工程,可以針對(duì)單表自動(dòng)生成mybatis執(zhí)行所需要的代碼(mapper.java、mapper.xml、po..)

企業(yè)實(shí)際開發(fā)中,常用的逆向工程方式:由數(shù)據(jù)庫(kù)的表生成java代碼。

2.將提供的逆向工程打開(參見github)

圖片.png

3.修改generatorConfig.xml

數(shù)據(jù)庫(kù)改成自己的
將包名改成自己的,生成代碼的存放位置
指定數(shù)據(jù)表

4.修改GeneratorSqlmap.java

指定自己generatorConfig.xml的位置

5.運(yùn)行GeneratorSqlmap.java

運(yùn)行完后自動(dòng)生成代碼

6.將自己所需要的mapper包內(nèi)內(nèi)容和po包內(nèi)內(nèi)容復(fù)制到工程下。

復(fù)制items相關(guān)內(nèi)容

7.新建測(cè)試類

package com.chinglee.ssm.mapper;

import com.chinglee.ssm.po.Items;
import com.chinglee.ssm.po.ItemsExample;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Date;
import java.util.List;

/**
 * 測(cè)試自動(dòng)生成的代碼
 */
public class ItemsMapperTest {
    private ApplicationContext applicationContext;
    private ItemsMapper itemsMapper;
    @Before
    public void setUp() throws Exception {
      applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
      itemsMapper= (ItemsMapper) applicationContext.getBean("itemsMapper");
    }

    @Test
    public void deleteByPrimaryKey() throws Exception {

    }

    @Test
    public void insert() throws Exception {
        //構(gòu)造items對(duì)象
        Items items=new Items();
        items.setName("手機(jī)");
        items.setPrice(999f);
        Date createTime=new Date(System.currentTimeMillis());
        items.setCreatetime(createTime);
        itemsMapper.insert(items);

    }

    //自定義條件查詢
    @Test
    public void selectByExample() throws Exception {
        ItemsExample itemsExample=new ItemsExample();
        //通過Criteria構(gòu)建查詢條件
       ItemsExample.Criteria criteria=itemsExample.createCriteria();
       criteria.andNameEqualTo("筆記本");
       //可能返回多條記錄
        List<Items> list=itemsMapper.selectByExample(itemsExample);
        System.out.println(list);

    }

    //根據(jù)主鍵查詢
    @Test
    public void selectByPrimaryKey() throws Exception {
       Items item=itemsMapper.selectByPrimaryKey(1);
       System.out.println(item);
    }

    //更新數(shù)據(jù)
    @Test
    public void updateByPrimaryKeySelective() throws Exception {
        //對(duì)所有字段進(jìn)行更新,需要先查詢出來(lái)再更新
        Items item=itemsMapper.selectByPrimaryKey(1);
        item.setName("水杯");
        itemsMapper.updateByPrimaryKey(item);
        //傳入字段不為null才更新,在批量更新中使用,不需要先查詢?cè)俑?        //itemsMapper.updateByPrimaryKeySelective()
    }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容