用SSM实现图书管理系统中的图书分类管理代码怎么写
时间: 2023-12-14 21:39:40 浏览: 124
基于SSM的图书管理系统源码
首先,我们需要创建一个 BookCategory 实体类,表示图书分类:
```java
public class BookCategory {
private Integer id;
private String name;
// getter and setter methods
}
```
接下来,我们需要创建一个 BookCategoryMapper 接口,用于数据库操作:
```java
public interface BookCategoryMapper {
List<BookCategory> findAll();
BookCategory findById(Integer id);
void save(BookCategory category);
void update(BookCategory category);
void delete(Integer id);
}
```
然后,我们需要在配置文件中进行相关配置,包括数据源、事务管理器、MyBatis 的映射文件等。
接下来,我们可以编写 BookCategoryServiceImpl 实现类,实现图书分类的增删改查等功能:
```java
@Service
@Transactional
public class BookCategoryServiceImpl implements BookCategoryService {
@Autowired
private BookCategoryMapper bookCategoryMapper;
@Override
public List<BookCategory> findAll() {
return bookCategoryMapper.findAll();
}
@Override
public BookCategory findById(Integer id) {
return bookCategoryMapper.findById(id);
}
@Override
public void save(BookCategory category) {
bookCategoryMapper.save(category);
}
@Override
public void update(BookCategory category) {
bookCategoryMapper.update(category);
}
@Override
public void delete(Integer id) {
bookCategoryMapper.delete(id);
}
}
```
最后,我们可以在 Controller 中调用 BookCategoryService 的相关方法,实现图书分类的管理功能。例如:
```java
@Controller
public class BookCategoryController {
@Autowired
private BookCategoryService bookCategoryService;
@RequestMapping("/category/list")
public String list(Model model) {
List<BookCategory> categories = bookCategoryService.findAll();
model.addAttribute("categories", categories);
return "category/list";
}
@GetMapping("/category/add")
public String add(Model model) {
model.addAttribute("category", new BookCategory());
return "category/edit";
}
@GetMapping("/category/edit/{id}")
public String edit(@PathVariable Integer id, Model model) {
BookCategory category = bookCategoryService.findById(id);
model.addAttribute("category", category);
return "category/edit";
}
@PostMapping("/category/save")
public String save(@ModelAttribute BookCategory category) {
if (category.getId() == null) {
bookCategoryService.save(category);
} else {
bookCategoryService.update(category);
}
return "redirect:/category/list";
}
@GetMapping("/category/delete/{id}")
public String delete(@PathVariable Integer id) {
bookCategoryService.delete(id);
return "redirect:/category/list";
}
}
```
上述代码中,我们实现了图书分类的列表展示、添加、编辑、删除等功能。其中,list 方法用于返回分类列表视图,add 和 edit 方法分别用于返回添加和编辑分类的视图,save 方法用于保存或更新分类信息,delete 方法用于删除分类。
阅读全文