開發一個新項目,用的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