gitHub地址:https://github.com/Ching-Lee/generatorSqlmapCustom
1.什么是逆向工程
mybatis需要程序員自己編寫sql語句,mybatis官方提供逆向工程,可以針對單表自動生成mybatis執行所需要的代碼(mapper.java、mapper.xml、po..)
企業實際開發中,常用的逆向工程方式:由數據庫的表生成java代碼。
2.將提供的逆向工程打開(參見github)
圖片.png
3.修改generatorConfig.xml
數據庫改成自己的
將包名改成自己的,生成代碼的存放位置
指定數據表
4.修改GeneratorSqlmap.java
指定自己generatorConfig.xml的位置
5.運行GeneratorSqlmap.java
運行完后自動生成代碼
6.將自己所需要的mapper包內內容和po包內內容復制到工程下。
復制items相關內容
7.新建測試類
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;
/**
* 測試自動生成的代碼
*/
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 {
//構造items對象
Items items=new Items();
items.setName("手機");
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構建查詢條件
ItemsExample.Criteria criteria=itemsExample.createCriteria();
criteria.andNameEqualTo("筆記本");
//可能返回多條記錄
List<Items> list=itemsMapper.selectByExample(itemsExample);
System.out.println(list);
}
//根據主鍵查詢
@Test
public void selectByPrimaryKey() throws Exception {
Items item=itemsMapper.selectByPrimaryKey(1);
System.out.println(item);
}
//更新數據
@Test
public void updateByPrimaryKeySelective() throws Exception {
//對所有字段進行更新,需要先查詢出來再更新
Items item=itemsMapper.selectByPrimaryKey(1);
item.setName("水杯");
itemsMapper.updateByPrimaryKey(item);
//傳入字段不為null才更新,在批量更新中使用,不需要先查詢再更新
//itemsMapper.updateByPrimaryKeySelective()
}
}