确保可以正常使用mybatis
pom引入依赖包,starter需要配合@Mapper注解使用,这里采用这种方式,或者使用@MapperScan注解,@tk.mybatis.spring.annotation.MapperScan(basePackages = "扫描包")配合原生mapper使用。
tk.mybatis
mapper-spring-boot-starter
{version}
我使用的版本是2.0.2
Mybatis 扫描配置(Deprecated, spring 自动配置)
@Configuration
//TODO 注意,由于MapperScannerConfigurer执行的比较早,所以必须有下面的注解
@AutoConfigureAfter(MybatisAutoConfiguration.class)
public class MyBatisMapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePackage("org.springboot.sample.mapper");
Properties properties = new Properties();
// 这里要特别注意,不要把MyMapper放到 basePackage 中,也就是不能同其他Mapper一样被扫描到。
properties.setProperty("mappers", MyMapper.class.getName());
properties.setProperty("notEmpty", "false");
properties.setProperty("IDENTITY", "MYSQL");
mapperScannerConfigurer.setProperties(properties);
return mapperScannerConfigurer;
}
}
新建BaseMapper类,该类不能被当做普通Mapper一样被扫描 ,不加@Mapper注解,或者放在不同文件夹
package com.zj.mapper;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface BaseMapper extends Mapper, MySqlMapper {
}
业务处理dao层,扩展BaseMapper
package com.zj.mapper;
import com.zj.model.OrderInfo;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface OrderInfoMapper extends BaseMapper {}
其他和使用普通mybatis一致,service层部分代码
orderInfoMapper.insertSelective(info);
OrderInfo info = orderInfoMapper.selectByPrimaryKey(id);
通用mapper提供常用的一些操作方法: deleteByPrimaryKey, insert, insertSelective, selectByPrimaryKey, updateByPrimaryKeySelective, updateByPrimaryKey, insertList等很多方法,需要你进一步探索
主键id问题
当使用insert,insertSelective等方法时,希望返回由数据库产生的逐渐,需要在实体类上增加注解
@Id
@GeneratedValue(generator = "JDBC")
private Long orderInfoId;
generator="JDBC"表示 MyBatis 使用 JDBC 的 getGeneratedKeys 方法来取出由数据库内部生成的主键 ,适用于MySQL,SQL Server等的自增主键。
或者:
@Id
@KeySql(useGeneratedKeys = true)
private Long id;
如果实体字段和数据库字段不一致,可以使用@Column注解,其他注解 参见注解
@Column(name="SCORE_SUM")
private String sumScore;
更多细节参见wiki