- 在application.yml内添加如下代码;
# mybatis-plus 配置内容
mybatis-plus:
configuration:
map-underscore-to-camel-case: true # 默认为 true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 用于打印详细sql语句
global-config:
db-config:
id-type: auto # ID 主键自增
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
- 创建实体类使用@TableName注解标注对应数据库;
@TableName(value = "user_personal_info")
public class UserPersonalInfo {
private String realName = null;//
private String sex = null;
private Integer age = null;
private String email = null;
private String phone = null;
private String sdf = null;
......//此处省略set和get方法
}
- 创建操作实体类对应数据库的Mapper;
@Repository
public interface UserRepository extends BaseMapper<UserPersonalInfo> {
}
BaseMapper包含了常用操作,所有可以不用写其他代码;
- 在Application上添加@MapperScan注解,注解内容为上一步创建的Mapper所在的报名
@SpringBootApplication
@MapperScan("UserRepository所在的包名")
public class TestApplication {
......//此处省略一万字
}
- 创建操作Mapper的Service,也是实际暴露对外操作类;
@Service
public class UserDataService extends ServiceImpl<UserRepository, UserPersonalInfo> {
public UserPersonalInfo findLastUser() {
UserPersonalInfo info = null;
List<UserPersonalInfo> users = baseMapper.selectList(null);
if (users.size() > 0) {
info = users.get(users.size() - 1);
} else {
info = new UserPersonalInfo();
info.setRealName("test_A");
}
return info;
}
由于使用ServiceImpl内部@Autowired自动引入Mapper对象,所以,如果3、4步配置不对,会导致启动时在这个位置报错;
@Autowired
protected M baseMapper;
- 现在可以在Controller使用对应的ServiceImpl完成数据库操作了。
2020-03-16
网友评论