mybatis逆向工程 是针对单表的操作:
自动生成的代码有(mapper接口,mapper.xml映射文件,pojo类)
代码生成器的配置注意:
1.最好在新项目中打开逆向工程的项目
2.逆向工程配置时代码的类的包名,mapper文件,pojo文件生成的位置应该和原项目的要一样,否则会引发很多莫名的错误,如:
报java.NopointClass,cann't find xxx类。。。。我的项目和逆向工程的目录作对如下:
逆向工程的:
我的项目的:
还有一点:sqlMapConfig.xml中不要配置pojo包的别名设置,否则也会报错,所mapper映射文件找不到实体类,贴图如下:
其中ItemExample类为自定义查询类,可理解为UserQueryCustom,自定义条件来查询(类似于hibernate的自定义hql语句)
detail字段是text类型,需要单独抽离出来
下面是ItemExample自定义查询类的使用:,以及逆向工程的增删改查:
package cn.itcast.ssm.mapper;
import cn.itcast.ssm.pojo.Items;
import cn.itcast.ssm.pojo.ItemsExample;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.mail.FetchProfile;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class ItemsMapperTest {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
ItemsMapper itemsMapper= (ItemsMapper) applicationContext.getBean("itemsMapper");
@Test
void insert() {
Items items=new Items();
items.setName("u盘");
items.setPrice((float) 12.8);
itemsMapper.insert(items);
System.out.println("ok");
}
@Test
void selectByExample() {
ItemsExample itemsExample=new ItemsExample();
//通过criteria构造自定义的查询条件
ItemsExample.Criteria criteria=itemsExample.createCriteria();
criteria.andNameEqualTo("水果");
//可能返回多条记录
List<Items>list =itemsMapper.selectByExample(itemsExample);
System.out.println(list);
}
@Test
void selectByPrimaryKey() {
Items items=itemsMapper.selectByPrimaryKey(1);
System.out.println(items);
}
@Test
void updateByExample() {
}
@Test
void updateByPrimaryKey() {
//更新时有判断,传入的更新字段的内容不能为空,故每次更新前都要查询出来再更新
Items items=itemsMapper.selectByPrimaryKey(1);
items.setName("水杯");
itemsMapper.updateByPrimaryKey(items);
//批量更新时使用updateByExampleSelective方法,直接更新,不需要先查询
// itemsMapper.updateByExampleSelective(a,b,c);
}
}
下面是springmvc的笔记。