开发一个新项目,用的springboot,相关配置不太熟悉,致使一些配置没配,到具体开发时问题就暴露出来了,记录第一个配置问题————Mybatis配置—自动使用驼峰命名 属性(userId)映射字段(user_id)。spring
实体类:sql
@Table(name = "bg_posting") public class BgPosting { /** * 帖子id */ @Id @Column(name = "posting_id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long postingId; /** * 帖子标题 */ @Column(name = "posting_title") private String postingTitle; /** * 发帖人id */ @Column(name = "user_id") private Long userId; ... }
错误:实体类用了@Table和@Column等注解,觉得在**Mapper.xml中作查询等操做时,会自动映射,例如:posting_id ——> postingId,然而测试结果告诉我,若是没有写
要在mybatis的配置文件中加上以下代码:apache
@Bean public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception { SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); factory.setDataSource(dataSource); factory.setTypeAliasesPackage(MODEL_PACKAGE); ... org.apache.ibatis.session.Configuration configuration=new org.apache.ibatis.session.Configuration(); configuration.setUseGeneratedKeys(true);//使用jdbc的getGeneratedKeys获取数据库自增主键值 configuration.setUseColumnLabel(true);//使用列别名替换列名,如:select user as User configuration.setMapUnderscoreToCamelCase(true);//-自动使用驼峰命名属性映射字段,如userId user_id factory.setConfiguration(configuration); return factory.getObject(); }
这样即便实体类不加@Column等注解,依然能够根据驼峰规则,映射成功springboot