1. 创建项目
加入相关依赖
2. 定义数据源
在配置文件中设置使用数据库的相关配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db
username: root
password: dem
3. 创建pojo层
POJO的格式是用于数据的临时传递,它只能装载数据,作为数据存储的载体,而不具有业务逻辑处理的能力。
属性类型和名称应与数据库的数据相对应
package com.example.domain;
public class Book {
private Integer id;
private String type;
private String name;
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", type='" + type + '\'' +
", name='" + name + '\'' +
", description='" + description + '\'' +
'}';
}
}
4. 编写dao
注解版
用 @Mapper 注解标识,我们使用#{id}来标识参数。@Mapper 注解把 mapper 这个 DAO 交给 Spring 管理,不再写 mapper 映射文件。
@Mapper
public interface BookDao {
@Select("select * from tbl_book where id = #{id}")
public Book getById(Integer id);
}
xml配置文件版
5. 编写service
需要在实现类中使用 @Service 注解,才能被 SpringBoot 扫描,在 Controller 中使用 @Autowired 注入
在 service 目录中新建 Book类
@Service
public class BookService {
@Autowired
private BookDao bookDao;
public Book getById(Integer id){
return bookDao.getById(id);
}
}
6. 编写Controller
使用Restful 风格,直接返回数据。
@RestController
public class UserController {
@Autowired
private BookService;
@GetMapping("/getById")
public User getUser(@RequestParam("id") Integer id){
return BookService.getById(id);
}
}