SpringBoot-(9)-MyBatis 操作数据库
2024-10-21 07:47:13
这里仅仅以插入数据为例:
一, 创建基于MyBatis的项目
具体流程参考之前帖
二,创建Mapper接口
public interface AccountMapper { @Insert("insert into accounts (nickName, lastName, password, email, mobilePhone, address, photo, authority, gender) " + "values(#{nickName}, #{lastName}, #{password}, #{email}, #{mobilePhone}, #{address}, #{photo}, #{authority}, #{gender})") Boolean insertAccount(@Param("nickName") String nickName,
@Param("lastName") String lastName,
@Param("password") String password,
@Param("email") String email,
@Param("mobilePhone") String mobilePhone,
@Param("address") String address,
@Param("photo") String photo,
@Param("authority") String authority,
@Param("gender") String gender);
}
三,在入口类注解 Mapper扫描路径(包名)
@MapperScan
@SpringBootApplication
@MapperScan("com.nfdw.accountsystem.mappers")
public class AccountSystemApplication { public static void main(String[] args) {
SpringApplication.run(AccountSystemApplication.class, args);
} }
四,声明Service类,操作database
@EnableAutoConfiguration
@Component
public class AccountService { @Autowired
private AccountMapper accountMapper; public Boolean registerAccount(Account account) {
/*
* @Param("nickName") String nickName,
@Param("lastName") String lastName,
@Param("password") String password,
@Param("email") String email,
@Param("mobilePhone") String mobilePhone,
@Param("address") String address,
@Param("photo") String photo,
@Param("authority") String authority,
@Param("gender") String gender
* */
boolean result = false;
try {
result = accountMapper.insertAccount(
account.getNickName(),
account.getLastName(),
account.getPassword(),
account.getEmail(),
account.getMobilePhone(),
account.getAddress(),
account.getPhoto(),
account.getAuthority(),
account.getGender()
);
} catch (Exception e) {
System.out.println("register error: " + e);
result = false;
}
return result;
} }
@EnableAutoConfiguration 运行自动配置
@Component 注解为组件,运行@Autowired自动注入
五, 调用service类,插入数据
@EnableAutoConfiguration
@RestController
public class AccountController { private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private AccountService accountService; @PostMapping("/register")
public String register(@RequestBody AccountEntity account) {
logger.info("----------\nregister with account info: " + account);
boolean result = accountService.registerAccount(account); return "register result: " + result;
}
}
最新文章
- JavaScript高级程序设计 读书笔记 第二章
- hash表C语言实现
- Git学习(4)基本操作
- Maven学习3-使用Maven构建项目
- 十天学会单片机Day5 IIC总线AT2402芯片(EEPROM)应用
- 解决xcode7添加启动图片不显示
- weimi 短信API post方式的简易代码。
- php 获取远程图片
- 处理Google Play的相关方法
- Magento Block设计分析(深入分析)
- Red and Black
- ppt画笔标记在哪里|ppt中画笔工具功能怎么用?
- js中的注意事项(持续整理)
- php language construct 语言构造器
- 基于visual Studio2013解决面试题之0303数组求和
- Oracle12C如何启动PDB数据库
- .NET Core2.0+MVC 用Redis/Memory+cookie实现的sso单点登录
- java 基础之枚举
- 微服务架构:Eureka参数配置项详解
- Freemaker Replace函数的正则表达式运用