创建一个基于SSM(Spring + Spring MVC + MyBatis)框架的药品商超管理系统是一个涉及多个步骤的过程。以下是一个详细的开发指南,包括项目结构、数据库设计、配置文件、Mapper接口、Service层、Controller层和前端页面的示例。
1. 需求分析
明确系统的主要功能需求,例如:
- 用户注册与登录
- 药品信息管理(增删改查)
- 库存管理
- 销售订单管理
- 供应商管理
- 报表统计
- 管理员管理功能
2. 技术选型
确定使用的技术栈:
- 后端:Spring, Spring MVC, MyBatis
- 前端:HTML, CSS, JavaScript (可选框架如Vue.js或React.js)
- 数据库:MySQL
- 服务器:Tomcat
3. 数据库设计
设计数据库模型,比如用户表、药品表、库存表、订单表等。这里以用户表、药品表和订单表为例:
user
表
CREATE TABLE `user` (`id` INT AUTO_INCREMENT PRIMARY KEY,`username` VARCHAR(50) NOT NULL UNIQUE,`password` VARCHAR(100) NOT NULL,`email` VARCHAR(100),`phone` VARCHAR(20),`role` VARCHAR(50) DEFAULT 'user',`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP
);
medicine
表
CREATE TABLE `medicine` (`id` INT AUTO_INCREMENT PRIMARY KEY,`name` VARCHAR(255) NOT NULL,`description` TEXT,`category` VARCHAR(100),`unit_price` DECIMAL(10, 2),`stock_quantity` INT,`supplier_id` INT,`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,FOREIGN KEY (`supplier_id`) REFERENCES `supplier`(`id`)
);
order
表
CREATE TABLE `order` (`id` INT AUTO_INCREMENT PRIMARY KEY,`user_id` INT NOT NULL,`total_amount` DECIMAL(10, 2),`status` VARCHAR(50),`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,FOREIGN KEY (`user_id`) REFERENCES `user`(`id`)
);
order_detail
表
CREATE TABLE `order_detail` (`id` INT AUTO_INCREMENT PRIMARY KEY,`order_id` INT NOT NULL,`medicine_id` INT NOT NULL,`quantity` INT,`unit_price` DECIMAL(10, 2),FOREIGN KEY (`order_id`) REFERENCES `order`(`id`),FOREIGN KEY (`medicine_id`) REFERENCES `medicine`(`id`)
);
4. 创建项目结构
使用IDE(如IntelliJ IDEA或Eclipse)创建一个新的Maven项目,并添加必要的依赖项到pom.xml
文件中。
5. 配置Spring和MyBatis
在src/main/resources
目录下创建配置文件,如applicationContext.xml
和mybatis-config.xml
,用于配置Spring和MyBatis。
applicationContext.xml
示例
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/pharmacy?useSSL=false&serverTimezone=UTC"/><property name="username" value="root"/><property name="password" value="password"/>
</bean><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.pharmacy.mapper"/>
</bean>
6. 编写Mapper接口
定义MyBatis的Mapper接口来操作数据库。例如,为用户表和药品表创建UserMapper.java
和MedicineMapper.java
:
UserMapper.java
package com.pharmacy.mapper;import com.pharmacy.entity.User;
import org.apache.ibatis.annotations.*;@Mapper
public interface UserMapper {@Select("SELECT * FROM user WHERE username = #{username}")User findByUsername(@Param("username") String username);@Insert("INSERT INTO user(username, password, email, phone, role) VALUES(#{username}, #{password}, #{email}, #{phone}, #{role})")int insert(User user);
}
MedicineMapper.java
package com.pharmacy.mapper;import com.pharmacy.entity.Medicine;
import org.apache.ibatis.annotations.*;@Mapper
public interface MedicineMapper {@Select("SELECT * FROM medicine")List<Medicine> findAll();@Select("SELECT * FROM medicine WHERE id = #{id}")Medicine findById(@Param("id") int id);@Insert("INSERT INTO medicine(name, description, category, unit_price, stock_quantity, supplier_id) VALUES(#{name}, #{description}, #{category}, #{unit_price}, #{stock_quantity}, #{supplier_id})")int insert(Medicine medicine);@Update("UPDATE medicine SET name=#{name}, description=#{description}, category=#{category}, unit_price=#{unit_price}, stock_quantity=#{stock_quantity}, supplier_id=#{supplier_id} WHERE id=#{id}")int update(Medicine medicine);@Delete("DELETE FROM medicine WHERE id=#{id}")int delete(@Param("id") int id);
}
7. 实现Service层
编写服务层来处理业务逻辑。例如,创建一个UserService.java
和MedicineService.java
:
UserService.java
package com.pharmacy.service;import com.pharmacy.entity.User;
import com.pharmacy.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class UserService {@Autowiredprivate UserMapper userMapper;public User login(String username, String password) {User user = userMapper.findByUsername(username);if (user != null && user.getPassword().equals(password)) {return user;}return null;}public void register(User user) {userMapper.insert(user);}
}
MedicineService.java
package com.pharmacy.service;import com.pharmacy.entity.Medicine;
import com.pharmacy.mapper.MedicineMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class MedicineService {@Autowiredprivate MedicineMapper medicineMapper;public List<Medicine> getAllMedicines() {return medicineMapper.findAll();}public Medicine getMedicineById(int id) {return medicineMapper.findById(id);}public void addMedicine(Medicine medicine) {medicineMapper.insert(medicine);}public void updateMedicine(Medicine medicine) {medicineMapper.update(medicine);}public void deleteMedicine(int id) {medicineMapper.delete(id);}
}
8. 控制器层
使用Spring MVC编写控制器来处理HTTP请求。例如,创建一个UserController.java
和MedicineController.java
:
UserController.java
package com.pharmacy.controller;import com.pharmacy.entity.User;
import com.pharmacy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;@Controller
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;@PostMapping("/login")public String login(@RequestParam("username") String username, @RequestParam("password") String password) {User user = userService.login(username, password);if (user != null) {// 登录成功后的处理return "redirect:/home";} else {// 登录失败后的处理return "login";}}@PostMapping("/register")public String register(@ModelAttribute User user) {userService.register(user);return "redirect:/login";}
}
MedicineController.java
package com.pharmacy.controller;import com.pharmacy.entity.Medicine;
import com.pharmacy.service.MedicineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;import java.util.List;@Controller
@RequestMapping("/medicine")
public class MedicineController {@Autowiredprivate MedicineService medicineService;@GetMapping("/list")public String listMedicines(Model model) {List<Medicine> medicines = medicineService.getAllMedicines();model.addAttribute("medicines", medicines);return "medicineList";}@GetMapping("/view/{id}")public String viewMedicine(@PathVariable("id") int id, Model model) {Medicine medicine = medicineService.getMedicineById(id);model.addAttribute("medicine", medicine);return "medicineView";}@GetMapping("/add")public String showAddForm(Model model) {model.addAttribute("medicine", new Medicine());return "medicineAdd";}@PostMapping("/add")public String addMedicine(@ModelAttribute Medicine medicine) {medicineService.addMedicine(medicine);return "redirect:/medicine/list";}@GetMapping("/edit/{id}")public String showEditForm(@PathVariable("id") int id, Model model) {Medicine medicine = medicineService.getMedicineById(id);model.addAttribute("medicine", medicine);return "medicineEdit";}@PostMapping("/edit/{id}")public String editMedicine(@PathVariable("id") int id, @ModelAttribute Medicine medicine) {medicine.setId(id);medicineService.updateMedicine(medicine);return "redirect:/medicine/list";}@GetMapping("/delete/{id}")public String deleteMedicine(@PathVariable("id") int id) {medicineService.deleteMedicine(id);return "redirect:/medicine/list";}
}
9. 前端页面
根据需要设计前端页面,可以使用Thymeleaf作为模板引擎。例如,创建一个简单的登录页面login.html
和药品列表页面medicineList.html
:
login.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>Login Page</title>
</head>
<body>
<form th:action="@{/user/login}" method="post"><label>Username:</label><input type="text" name="username"/><br/><label>Password:</label><input type="password" name="password"/><br/><button type="submit">Login</button>
</form>
</body>
</html>
medicineList.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>Medicine List</title>
</head>
<body>
<h1>Medicine List</h1>
<table border="1"><tr><th>ID</th><th>Name</th><th>Description</th><th>Category</th><th>Unit Price</th><th>Stock Quantity</th><th>Actions</th></tr><tr th:each="medicine : ${medicines}"><td th:text="${medicine.id}"></td><td th:text="${medicine.name}"></td><td th:text="${medicine.description}"></td><td th:text="${medicine.category}"></td><td th:text="${medicine.unit_price}"></td><td th:text="${medicine.stock_quantity}"></td><td><a th:href="@{/medicine/view/{id}(id=${medicine.id})}">View</a><a th:href="@{/medicine/edit/{id}(id=${medicine.id})}">Edit</a><a th:href="@{/medicine/delete/{id}(id=${medicine.id})}">Delete</a></td></tr>
</table>
<a href="/medicine/add">Add New Medicine</a>
</body>
</html>
10. 测试与部署
完成所有编码后,进行单元测试确保各部分工作正常。之后,可以将应用部署到Tomcat服务器上。