<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>最新版本号</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!-- 如果mapper.xml是放在src/main/java目录下,需配置以下-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<filtering>false</filtering>
<includes>
<include>**/mapper/*.xml</include>
</includes>
</resource>
</resources>
</build>
@Configuration
//扫描dao或者是Mapper接口
@MapperScan("com.example.demo.common.orm.mapper")
public class MybatisPlusConfig {
/**
* mybatis-plus 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor page = new PaginationInterceptor();
// page.setDialectType(DBType.SQLSERVER.getDb());
page.setDialectType(DBType.SQLSERVER2005.getDb());
return page;
}
//this method is important if you want to fill common fields like create_time etc.
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource, ResourceLoader resourceLoader, GlobalConfiguration globalConfiguration) throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(dataSource);
sqlSessionFactory.setTypeAliasesPackage("com.example.demo.common.orm.mapper");
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactory.setMapperLocations(resolver.getResources("classpath*:com/cushmanwakefield/one/service/backend/common/orm/mapper/xml/*.xml"));
MybatisConfiguration configuration = new MybatisConfiguration();
sqlSessionFactory.setGlobalConfig(globalConfiguration());
configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
configuration.setJdbcTypeForNull(JdbcType.NULL);
sqlSessionFactory.setConfiguration(configuration);
sqlSessionFactory.setPlugins(new Interceptor[]{
paginationInterceptor(),
new PerformanceInterceptor(),
new OptimisticLockerInterceptor()
});
sqlSessionFactory.setGlobalConfig(globalConfiguration);
return sqlSessionFactory.getObject();
}
@Bean
public GlobalConfiguration globalConfiguration() {
GlobalConfiguration conf = new GlobalConfiguration(new LogicSqlInjector());
conf.setLogicDeleteValue("deleted");
conf.setLogicNotDeleteValue("N");
// conf.setIdType(2);
// ID 策略 AUTO->`0`("数据库ID自增") INPUT->`1`(用户输入ID") ID_WORKER->`2`("全局唯一ID") UUID->`3`("全局唯一ID")
conf.setMetaObjectHandler(new MyMetaObjectHandler());
return conf;
}
}
public class MyMetaObjectHandler extends MetaObjectHandler{
@Override
public void insertFill(MetaObject metaObject) {
super.setFieldValByName("createTime", new Date(), metaObject);
super.setFieldValByName("deleted", "N", metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
super.setFieldValByName("updateTime", new Date(), metaObject);
}
}
//************************************************************
public class BaseEntity<T> implements Serializable{
@TableId(type = IdType.ID_WORKER)
@TableField("id")
public Long id;
@ApiModelProperty(readOnly = true)
@TableLogic(delval = "Y")
@TableField(value = "deleted", fill = FieldFill.INSERT)
public String deleted;
public Serializable pkVal() {
return this.id;
}
@ApiModelProperty("创建时间")
@TableField(value = "create_time", fill = FieldFill.INSERT)
public Date createTime;
@ApiModelProperty("修改时间")
@TableField(value = "update_time", fill = FieldFill.UPDATE)
public Date updateTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDeleted() {
return deleted;
}
public void setDeleted(String deleted) {
this.deleted = deleted;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
public class AutoGengerate {
public static void main(String[] args){
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir("/home/fitch/workspace/test/src/main/java");
gc.setFileOverride(true);
gc.setActiveRecord(true);
gc.setEnableCache(true);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(true);// XML columList
gc.setAuthor("fitch");
//这个很重要 你可以在代码中 IdWork.getId()或idWork.getIdStr()自动生产一个id,
//gc.setIdType(IdType.ID_WORKER_STR);
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setServiceName("I%sService");
gc.setServiceImplName("%sServiceImap");
//gc.setControllerName("%sController");
mpg.setGlobalConfig(gc);
com.baomidou.mybatisplus.generator.config.DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setDriverName("com.mysql.jdbc.Driver");
// ?useUnicode=true&characterEncoding=UTF-8&generateSimpleParameterMetadata=true
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("com.example.demo.common.mybatis.BaseEntity");
// 自定义实体,公共字段
strategy.setSuperEntityColumns(new String[] { "create_time", "deleted","update_time","id" });
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.example.demo.common");
pc.setModuleName("orm");
mpg.setPackageInfo(pc);
// 执行生成
mpg.execute();
}
}
//reference:http://mp.baomidou.com/#/generate-code
After running AutoGengerate
, many classes are generated.
Notice:
your generated entity will be like the follow. but the type of the entities’ is long. so when the id is send to the front, it will lose precision.
TableName("home_page_banner")
public class HomePageBanner extends BaseEntity<HomePageBanner> {
private static final long serialVersionUID = 1L;
@TableField("banner_image")
private String bannerImage;
@TableField("banner_icon")
private String bannerIcon;
@TableField("banner_desc")
private String bannerDesc;
@TableField("banner_sort")
private Integer bannerSort;
@TableField("show_icon")
private String showIcon;
@TableField("show_desc")
private String showDesc;
@TableField("need_link")
private String needLink;
@TableField("link_to_module")
private String linkToModule;
@TableField("create_by")
private Long createBy;
@TableField("update_by")
private Long updateBy;
//.......
}
how to solve the problem?
you need to add a configuration in your web configuration file. Like this file:
@Configuration
public class WebSecurityConfig extends WebMvcConfigurerAdapter {
.....
}
add the following. The result is when you send id, id will be transfered into the type of String.
//对long类型传递给前台 lose precision
@Bean("jackson2ObjectMapperBuilderCustomizer")
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
Jackson2ObjectMapperBuilderCustomizer customizer = new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance)
.serializerByType(Long.TYPE, ToStringSerializer.instance);
}
};
return customizer;
}