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