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()
}
}