20.Mybatis逆向工程自动生成代码

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

1.什么是逆向工程

mybatis需要程序员自己编写sql语句,mybatis官方提供逆向工程,可以针对单表自动生成mybatis执行所需要的代码(mapper.java、mapper.xml、po..)

企业实际开发中,常用的逆向工程方式:由数据库的表生成java代码。

2.将提供的逆向工程打开(参见github)

20.Mybatis逆向工程自动生成代码_第1张图片
图片.png

3.修改generatorConfig.xml

20.Mybatis逆向工程自动生成代码_第2张图片
数据库改成自己的
20.Mybatis逆向工程自动生成代码_第3张图片
将包名改成自己的,生成代码的存放位置
20.Mybatis逆向工程自动生成代码_第4张图片
指定数据表

4.修改GeneratorSqlmap.java

指定自己generatorConfig.xml的位置

5.运行GeneratorSqlmap.java

20.Mybatis逆向工程自动生成代码_第5张图片
运行完后自动生成代码

6.将自己所需要的mapper包内内容和po包内内容复制到工程下。

20.Mybatis逆向工程自动生成代码_第6张图片
复制items相关内容

7.新建测试类

20.Mybatis逆向工程自动生成代码_第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 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()
    }

}

你可能感兴趣的:(20.Mybatis逆向工程自动生成代码)