Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • c24025433/healthcare
1 result
Show changes
Commits on Source (78)
Showing
with 822 additions and 47 deletions
File added
File added
File added
......@@ -24,6 +24,7 @@ repositories {
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-security'
......
/*
Navicat Premium Data Transfer
Source Server : wyl
Source Server Type : MySQL
Source Server Version : 80031
Source Host : localhost:3306
Source Schema : health_care
Target Server Type : MySQL
Target Server Version : 80031
File Encoding : 65001
Date: 26/11/2024 14:50:12
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for common_admin
-- ----------------------------
DROP TABLE IF EXISTS `common_admin`;
CREATE TABLE `common_admin` (
`id` int NOT NULL AUTO_INCREMENT,
`email` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`type` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`roleId` int NULL DEFAULT NULL,
`phone` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`status` int NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of common_admin
-- ----------------------------
INSERT INTO `common_admin` VALUES (1, '264978365@qq.com', '$2a$10$5UzuKUxgR8H0RzLYrP.BUu8.76yKwMD4XkvJIu/xxB7AAHWfphFQm', 'commonAdmin', 1, '22222', 'jjy', 1);
INSERT INTO `common_admin` VALUES (2, '26497@qq.com', '$2a$10$4uTgtSP1B6TLvKUicCuA0.lGwDKfNxtF2vJTXqX4WfekNa5C9Ny4u', 'commonAdmin', 1, '111', 'test', 1);
-- ----------------------------
-- Table structure for device
-- ----------------------------
DROP TABLE IF EXISTS `device`;
CREATE TABLE `device` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`type` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`freetime` datetime NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of device
-- ----------------------------
-- ----------------------------
-- Table structure for hospital
-- ----------------------------
DROP TABLE IF EXISTS `hospital`;
CREATE TABLE `hospital` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`amountPatient` int NULL DEFAULT NULL,
`maxAmount` int NULL DEFAULT NULL,
`type` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`address` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`phone` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`status` int NULL DEFAULT NULL,
`roleId` int NULL DEFAULT NULL,
`email` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of hospital
-- ----------------------------
INSERT INTO `hospital` VALUES (1, 'jjy', 100, 300, 'hospital', 'Cardiffe', '22222', 0, 3, '264978365@qq.com');
INSERT INTO `hospital` VALUES (2, 'park00000', 5, 10, 'hospital', 'cardiff', '1234', 0, 3, '2649783657@qq.com');
INSERT INTO `hospital` VALUES (3, 'test', 0, 0, 'hospital', 'cardiff', '123', 0, 3, '264@qq.com');
INSERT INTO `hospital` VALUES (4, 'ttttttt', 0, 0, 'hospital', 'cardiff', '123', 0, 3, '26492@qq.com');
-- ----------------------------
-- Table structure for hospital_device
-- ----------------------------
DROP TABLE IF EXISTS `hospital_device`;
CREATE TABLE `hospital_device` (
`hospitalId` int NULL DEFAULT NULL,
`deviceId` int NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of hospital_device
-- ----------------------------
-- ----------------------------
-- Table structure for patient
-- ----------------------------
DROP TABLE IF EXISTS `patient`;
CREATE TABLE `patient` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`roleId` int NULL DEFAULT NULL,
`status` int NULL DEFAULT NULL,
`hospitalId` int NULL DEFAULT NULL,
`type` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`age` int NULL DEFAULT NULL,
`phone` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`email` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of patient
-- ----------------------------
INSERT INTO `patient` VALUES (1, 'jyy', '$2a$10$obgmyiqAuhIkBjuw3bROr.LkCh.Nb70e4dL8lwKjSsPxS8gSpQxSC', 2, 0, 0, 'patient', 0, NULL, NULL);
-- ----------------------------
-- Table structure for patient_hospital
-- ----------------------------
DROP TABLE IF EXISTS `patient_hospital`;
CREATE TABLE `patient_hospital` (
`hosptialId` int NULL DEFAULT NULL,
`patientId` int NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of patient_hospital
-- ----------------------------
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`roleId` int NULL DEFAULT NULL,
`type` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES (0, 'SUPER');
INSERT INTO `role` VALUES (1, 'ADMIN');
INSERT INTO `role` VALUES (2, 'PATIENT');
INSERT INTO `role` VALUES (3, 'HOSPITAL');
-- ----------------------------
-- Table structure for super_admin
-- ----------------------------
DROP TABLE IF EXISTS `super_admin`;
CREATE TABLE `super_admin` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`password` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`roleId` int NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of super_admin
-- ----------------------------
INSERT INTO `super_admin` VALUES (1, '2649783657@qq.com', '$2a$10$5UzuKUxgR8H0RzLYrP.BUu8.76yKwMD4XkvJIu/xxB7AAHWfphFQm', 0);
-- ----------------------------
-- Procedure structure for reset_primary_keys
-- ----------------------------
DROP PROCEDURE IF EXISTS `reset_primary_keys`;
delimiter ;;
CREATE PROCEDURE `reset_primary_keys`()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE current_id INT DEFAULT 0;
DECLARE cur CURSOR FOR
SELECT id FROM common_admin ORDER BY id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur;
-- 重新更新每一条记录的 ID
read_loop: LOOP
FETCH cur INTO current_id;
IF done THEN
LEAVE read_loop;
END IF;
-- 根据新的排序修改 ID
UPDATE common_admin SET id = current_id - 1 WHERE id = current_id;
END LOOP;
CLOSE cur;
END
;;
delimiter ;
SET FOREIGN_KEY_CHECKS = 1;
......@@ -2,18 +2,20 @@ package com.cardiff.client_project.config;
import com.cardiff.client_project.utils.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* Customize fail filters
*/
public class MyAuthenticationFailHandler implements AuthenticationFailureHandler {
@Component
public class AuthenticationFailHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException{
// Configuration response
......
package com.cardiff.client_project.config;
import com.cardiff.client_project.constant.ResponseCode;
import com.cardiff.client_project.controller.CodeController;
import com.cardiff.client_project.utils.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import java.io.IOException;
......@@ -18,18 +15,18 @@ import java.io.IOException;
/**
* Customize success filters
*/
@Configuration
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Component
public class AuthenticationSuccessHandler implements org.springframework.security.web.authentication.AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException{
System.out.println(authentication);
String authorities = authentication.getAuthorities().toString();
System.out.println("authorities: " + authorities);
// Configuration response
response.setContentType("application/json;charset=UTF-8");
ObjectMapper objectMapper = new ObjectMapper();
String jsonResponse = objectMapper.writeValueAsString(Result.success(authorities));
String jsonResponse = objectMapper.writeValueAsString(Result.success(authorities+","+authentication.getName()));
response.getWriter().write(jsonResponse);
}
}
package com.cardiff.client_project.config;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.sendRedirect("/fault.html");
}
}
package com.cardiff.client_project.config;
import com.cardiff.client_project.constant.ResponseCode;
import com.cardiff.client_project.utils.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.sendRedirect("/fault.html");
}
}
package com.cardiff.client_project.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@Component
public class WebMvcConfiguration implements WebMvcConfigurer {
/**
* Set a static resource mapping
* @param registry
*/
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/*.html").addResourceLocations("classpath:/static/html/");
registry.addResourceHandler("/*.html")
.addResourceLocations("classpath:/static/html/");
}
}
package com.cardiff.client_project.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
@Configuration
@Component
public class WebSecurityConfig{
//exception handler
@Autowired
//Unauthenticated exception filter
private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
@Autowired
//Insufficient permission exception processor
private AccessDeniedHandler customAccessDeniedHandler;
/**
* Coded filter
* @return
......@@ -23,6 +31,16 @@ public class WebSecurityConfig{
return new BCryptPasswordEncoder();
}
/**
* Delete the default ROLE_ prefix
* @return
*/
@Bean
public GrantedAuthorityDefaults grantedAuthorityDefaults(){
return new GrantedAuthorityDefaults("");
}
/**
* Set filter chain
* @param http
......@@ -35,13 +53,27 @@ public class WebSecurityConfig{
http .csrf(csrf-> csrf.disable())
.authorizeHttpRequests(requests -> requests
.requestMatchers("/device.html").hasRole("ADMIN")
//.requestMatchers("/superAdminView.html").hasRole("SUPER")
.requestMatchers("/commonUser.html").authenticated()
.anyRequest().permitAll()
)
//Custom permission exception handler
.exceptionHandling(exceptions -> exceptions
.authenticationEntryPoint(customAuthenticationEntryPoint)
.accessDeniedHandler(customAccessDeniedHandler)
)
.logout(log -> log
.logoutUrl("/logout") // Set a logoff request URL
.logoutSuccessUrl("/login.html") // Redirection after successful logout URL
.invalidateHttpSession(true) // Invalid session on logout
.clearAuthentication(true) // Clear authentication information
.deleteCookies("JSESSIONID") // delete Cookie
)
.formLogin(form -> form
.loginPage("/login")
.successHandler(new MyAuthenticationSuccessHandler())
.failureHandler(new MyAuthenticationFailHandler())
.successHandler(new AuthenticationSuccessHandler())
.failureHandler(new AuthenticationFailHandler())
.permitAll());
return http.build();
......
package com.cardiff.client_project.constant;
//Permission dictionary
public class Authority {
public final static int SUPER = 0;
public final static int ADMIN = 1;
public final static int PATIENT = 2;
public final static int HOSPITAL = 3;
}
package com.cardiff.client_project.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import java.security.Principal;
@Controller
public class CodeController {
@GetMapping("/code")
public ModelAndView verificationCode(Principal principal){
String string = principal.toString();
System.out.println(string.contains("SUPER"));
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("superAdmin.html");
return modelAndView;
}
}
package com.cardiff.client_project.controller;
import com.cardiff.client_project.service.SuperAdminService;
import com.cardiff.client_project.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ViewController {
@Autowired
private SuperAdminService superAdminService;
@GetMapping("/loadLeft")
public String loadLeftView() {
return "leftView";
}
@GetMapping("/defaultLoadMain")
public String loadMainView_1(Model model) {
Result result = superAdminService.selectAllAdmin();
// Add data to the model
model.addAttribute("tableData", result.getData());
return "mainSupAdminView";
}
@GetMapping("/hospitalLoadMain")
public String loadMainView_2(Model model) {
//System.out.println("loadMainView_2");
Result result = superAdminService.selectAllHospital();
// Add data to the model
System.out.println("result"+result.getData());
model.addAttribute("tableData", result.getData());
// System.out.println("result"+result.getData());
return "mainHospitalView";
}
}
package com.cardiff.client_project.controller.admin;
import com.cardiff.client_project.pojo.dto.SelectDTO;
import com.cardiff.client_project.pojo.dto.SignUserDTO;
import com.cardiff.client_project.service.SuperAdminService;
import com.cardiff.client_project.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/superAdmin")
public class SuperAdminController {
@Autowired
private SuperAdminService superAdminService;
/**
* User registration
* @param signDTO
* @return
*/
@PostMapping("/sign")
public Result signIn(@RequestBody SignUserDTO signDTO){
System.out.println(signDTO);
Result result= superAdminService.insertUserInform(signDTO);
System.out.println(result);
return result;
}
/**
*delete hospital information by id
* @param ids
* @return
*/
@DeleteMapping("/deleteHospitalById")
public Result deleteHospitalById(@RequestBody List<Integer> ids){
Result result= superAdminService.deleteById(ids,"hospital");
return result;
}
@DeleteMapping("/deleteAdminById")
public Result deleteAdminById(@RequestBody List<Integer> ids){
Result result= superAdminService.deleteById(ids,"commonAdmin");
return result;
}
/**
* fuzzy query
* @param
* @return
*/
@PostMapping("/select")
public Result selectByItem(@RequestBody SelectDTO selectDTO){
System.out.println(selectDTO);
Result result= superAdminService.selectByItem(selectDTO);
return result;
}
/**
* Update data
* @param selectDTO
* @return
*/
@PutMapping("/update")
public Result updateById(@RequestBody SelectDTO selectDTO){
System.out.println("update"+selectDTO);
Result result= superAdminService.update(selectDTO);
return result;
}
}
package com.cardiff.client_project.mapper;
import com.cardiff.client_project.pojo.entity.Patient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class PatientMapper {
@Autowired
JdbcTemplate jdbcTemplate;
/**
* update patient data
* @param patient
* @return
*/
public int update(Patient patient) {
String sql = "UPDATE patient SET name = ?,phone = ?, age=?, email=?, status = ?,hospitalId =? WHERE id = ?";
int update = jdbcTemplate.update(sql, preparedStatement -> {
preparedStatement.setString(1, patient.getName());
preparedStatement.setString(2, patient.getPhone());
preparedStatement.setInt(3, patient.getAge());
preparedStatement.setString(4, patient.getEmail());
preparedStatement.setInt(5, patient.getStatus());
preparedStatement.setInt(6, patient.getHospitalId());
preparedStatement.setInt(7, patient.getId());
});
return update;
}
}
package com.cardiff.client_project.mapper;
import com.cardiff.client_project.constant.Authority;
import com.cardiff.client_project.constant.ResponseCode;
import com.cardiff.client_project.pojo.dto.SelectDTO;
import com.cardiff.client_project.pojo.entity.CommonAdmin;
import com.cardiff.client_project.pojo.entity.Hospital;
import com.cardiff.client_project.pojo.entity.Patient;
import com.cardiff.client_project.pojo.entity.SuperUser;
import com.cardiff.client_project.pojo.vo.AdminVO;
import com.cardiff.client_project.pojo.vo.HospitalVO;
import com.cardiff.client_project.pojo.vo.SelectVO;
import com.cardiff.client_project.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Repository
public class SuperAdminMapper {
@Autowired
JdbcTemplate jdbcTemplate;
JdbcTemplate jdbcTemplate;;
/**
* ser registration
* @param commonAdmin
*/
public Result insertUserInform(CommonAdmin commonAdmin) {
//Check whether the account exists(If the user name and email address are the same, the account is confirmed to exist)
String sql = "SELECT count(id) FROM common_admin where name = ? and email = ?";
Integer count= jdbcTemplate.queryForObject(sql, new Object[]{commonAdmin.getName(), commonAdmin.getEmail()}, Integer.class);
System.out.println(count);
if(count>0){
return Result.error(ResponseCode.ACCOUNT_EXISTS_ERROR);
}
//insert data
SimpleJdbcInsert insert = new SimpleJdbcInsert(jdbcTemplate)
.withTableName("common_admin")
.usingGeneratedKeyColumns("id");
Map<String, Object> parameters = new HashMap<>();
parameters.put("name",commonAdmin.getName());
parameters.put("password",commonAdmin.getPassword());
parameters.put("email",commonAdmin.getEmail());
parameters.put("phone",commonAdmin.getPhone());
parameters.put("type",commonAdmin.getType());
parameters.put("status",commonAdmin.getStatus());
parameters.put("roleId",commonAdmin.getRoleId());
Number number = insert.executeAndReturnKey(parameters);
if(number.longValue() > 0){
return Result.success(ResponseCode.SUCCESS);
}else {
return Result.error(ResponseCode.ERROR);
}
}
/**
* Batch deletion based on id
* @param ids
* @return
*/
public int[] deleteByIdAndType(List<Integer> ids,String type) {
String sql = "";
String sql_1="";
String sql_2="";
if(type.equals("hospital")){
sql = "DELETE FROM hospital WHERE id=?";
sql_1="ALTER TABLE hospital DROP COLUMN id;";
sql_2="ALTER TABLE hospital ADD COLUMN id INT NOT NULL PRIMARY KEY AUTO_INCREMENT FIRST;";
}
if(type.equals("commonAdmin")){
sql = "DELETE FROM common_admin WHERE id=?";
sql_1="ALTER TABLE common_admin DROP COLUMN id;";
sql_2="ALTER TABLE common_admin ADD COLUMN id INT NOT NULL PRIMARY KEY AUTO_INCREMENT FIRST;";
}
List<Object[]> idList = new ArrayList<>();
// Build parameter list
for (Integer id : ids) {
idList.add(new Object[]{id});
}
// Batch delete
int[] item = jdbcTemplate.batchUpdate(sql, idList);
jdbcTemplate.update(sql_1);
jdbcTemplate.update(sql_2);
return item;
}
/**
* select admin
* @return
*/
public List<AdminVO> selectAllAdmin() {
// Parameterized queries avoid SQL injection
String sql = "SELECT * FROM common_admin ORDER BY status DESC";
List<AdminVO> query = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(AdminVO.class));
return query;
}
/**
* select hospital
* @return
*/
public List<Hospital> selectAllHospital(){
// Parameterized queries avoid SQL injection
String sql = "SELECT * FROM hospital ORDER BY status DESC";
List<Hospital> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Hospital.class));
System.out.println(query);
return query;
}
/**
* update data
* @param o
*/
public List update(Object o) {
if(o instanceof CommonAdmin){
CommonAdmin commonAdmin=(CommonAdmin)o;
StringBuilder sql = new StringBuilder("UPDATE common_admin SET ");
List<Object> params = new ArrayList<>();
if (commonAdmin.getName() != null && !commonAdmin.getName().isEmpty()) {
sql.append("name = ?, ");
params.add(commonAdmin.getName());
}
if (commonAdmin.getEmail() != null && !commonAdmin.getEmail().isEmpty()) {
sql.append("email = ?, ");
params.add(commonAdmin.getEmail());
}
if (commonAdmin.getPhone() != null && !commonAdmin.getPhone().isEmpty()) {
sql.append("phone = ?, ");
params.add(commonAdmin.getPhone());
}
if (Integer.valueOf(commonAdmin.getStatus())!=null) {
sql.append("status = ?, ");
params.add(commonAdmin.getStatus());
}
// Remove the last comma and space
sql.setLength(sql.length() - 2);
// Add the WHERE clause
sql.append(" WHERE id = ?");
params.add(commonAdmin.getId());
jdbcTemplate.update(sql.toString(), params.toArray());
List<AdminVO> adminVOS = selectAllAdmin();
return adminVOS;
}
if(o instanceof Hospital){
Hospital hospital = (Hospital) o;
System.out.println("hospital"+hospital);
StringBuilder sql = new StringBuilder("UPDATE hospital SET ");
List<Object> params = new ArrayList<>();
if (hospital.getEmail() != null && !hospital.getEmail().isEmpty()) {
sql.append("email = ?, ");
params.add(hospital.getEmail());
}
if (hospital.getName() != null && !hospital.getName().isEmpty()) {
sql.append("name = ?, ");
params.add(hospital.getName());
}
if (hospital.getPhone() != null && !hospital.getPhone().isEmpty()) {
sql.append("phone = ?, ");
params.add(hospital.getPhone());
}
if (Integer.valueOf(hospital.getStatus()) != null) {
sql.append("status = ?, ");
params.add(hospital.getStatus());
}
if (hospital.getAddress() != null && !hospital.getAddress().isEmpty()) {
sql.append("address = ?, ");
params.add(hospital.getAddress());
}
if ((Integer.valueOf(hospital.getMaxAmount()) != null)){
sql.append("maxAmount = ?, ");
params.add(hospital.getMaxAmount());
}
if (Integer.valueOf(hospital.getAmountPatient()) != null) {
sql.append("amountPatient = ?, ");
params.add(hospital.getAmountPatient());
}
sql.setLength(sql.length() - 2);
sql.append(" WHERE id = ?");
params.add(hospital.getId());
jdbcTemplate.update(sql.toString(), params.toArray());
List<Hospital> hospitals = selectAllHospital();
return hospitals;
}
return null;
}
/**
* fuzzy query
* @param selectDTO
* @return
*/
public List<SelectVO> selectByItem(SelectDTO selectDTO) {
System.out.println("test:"+selectDTO);
// Get query type
String type = selectDTO.getType();
// Build the basic SQL and parameter list
StringBuilder sql = new StringBuilder("SELECT * FROM");
if(type.contains("commonAdmin")){
sql.append(" common_admin ");
}
if(type.contains("hospital")){
sql.append(" hospital ");
}
//Dynamic table name stitching
sql.append(" WHERE 1=1 ");
List<Object> params = new ArrayList<>();
//Dynamic concatenation of query conditions
if (selectDTO.getName() != null && selectDTO.getName()!="") {
sql.append(" AND name LIKE ?");
params.add("%" + selectDTO.getName() + "%");
}
if (selectDTO.getPhone() != null && selectDTO.getPhone()!="") {
sql.append(" AND phone LIKE ?");
params.add("%" + selectDTO.getPhone() + "%");
}
if (selectDTO.getAddress() != null && selectDTO.getAddress()!="") {
sql.append(" AND address LIKE ?");
params.add("%" + selectDTO.getAddress() + "%");
}
if (Integer.valueOf(selectDTO.getStatus())!=null) {
sql.append(" AND status = ?, ");
params.add(selectDTO.getStatus());
}
sql.setLength(sql.length() - 2);
System.out.println("sql: "+sql.toString());
List<SelectVO> query = jdbcTemplate.query(sql.toString(), params.toArray(), new BeanPropertyRowMapper<>(SelectVO.class));
System.out.println("quert"+query);
return query;
//String type=selectVo.getType();
// String first="select * from ";
// String second = " where ";
// if(selectVo.getName()!=null){
// second+="name like '%"+selectVo.getName()+"%'";
// }
// if(selectVo.getPhone()!=null){
// second+="phone like '%"+selectVo.getPhone()+"%'";
// }
// if(selectVo.getAddress()!=null){
// second+="address like '%"+selectVo.getAddress()+"'";
// }
//
//
// List<SelectDTO> query=new ArrayList<>();
// if("commonAdmin".equals(type)){
// String sql=first+"common_admin"+second;
// System.out.println(sql);
// query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(SelectDTO.class));
// }
// if("hospital".equals(type)){
// String sql=first+"hospital"+second;
// System.out.println(sql);
// query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(SelectDTO.class));
// }
// System.out.println(query);
}
/**
* Query data by name
* @param username
* @return
*/
public SuperUser getInforByName(String username){
String sql="select * from super_admin where name=?";
public Object getInforByName(String username){
SuperUser superUser = jdbcTemplate.queryForObject(sql, new Object[]{username}, new BeanPropertyRowMapper<SuperUser>(SuperUser.class));
return superUser;
try {
// 1. 查询 super_admin 表
String sql = "select * from super_admin where name=?";
return jdbcTemplate.queryForObject(sql, new Object[]{username}, new BeanPropertyRowMapper<>(SuperUser.class));
} catch (Exception s) {
try {
// 2. 查询 hospital 表
String sql = "select * from hospital where email=?";
return jdbcTemplate.queryForObject(sql, new Object[]{username}, new BeanPropertyRowMapper<>(Hospital.class));
} catch (Exception h) {
try {
// 3. 查询 common_admin 表
String sql = "select * from common_admin where email=?";
return jdbcTemplate.queryForObject(sql, new Object[]{username}, new BeanPropertyRowMapper<>(CommonAdmin.class));
} catch (Exception c) {
try {
// 4. 查询 patient 表
String sql = "select * from patient where email=?";
return jdbcTemplate.queryForObject(sql, new Object[]{username}, new BeanPropertyRowMapper<>(Patient.class));
} catch (Exception p) {}
}
}
}
// 如果所有查询都为空,返回 null
return null;
}
/**
......@@ -37,4 +341,44 @@ public class SuperAdminMapper {
String type= jdbcTemplate.queryForObject(sql, new Object[]{roleId}, String.class);
return type;
}
/**
* insert hospital
* @param hospital
*/
public Result insertHospitalInform(Hospital hospital) {
//Check whether the account exists(If the user name and email address are the same, the account is confirmed to exist)
String sql = "SELECT count(id) FROM hospital where name = ? and email = ?";
Integer count= jdbcTemplate.queryForObject(sql, new Object[]{hospital.getName(), hospital.getEmail()}, Integer.class);
System.out.println(count);
if(count>0){
return Result.error(ResponseCode.ACCOUNT_EXISTS_ERROR);
}
//insert data
SimpleJdbcInsert insert = new SimpleJdbcInsert(jdbcTemplate)
.withTableName("hospital")
.usingGeneratedKeyColumns("id");
Map<String, Object> parameters = new HashMap<>();
parameters.put("name",hospital.getName());
parameters.put("password",hospital.getPassword());
parameters.put("email",hospital.getEmail());
parameters.put("phone",hospital.getPhone());
parameters.put("type",hospital.getType());
parameters.put("roleId", Authority.HOSPITAL);
parameters.put("address",hospital.getAddress());
parameters.put("amountPatient",hospital.getAmountPatient());
parameters.put("maxAmount",hospital.getMaxAmount());
parameters.put("patientId",hospital.getPatientId());
parameters.put("deviceId",hospital.getDeviceId());
parameters.put("status",hospital.getStatus());
Number number = insert.executeAndReturnKey(parameters);
if(number.longValue() > 0){
return Result.success(ResponseCode.SUCCESS);
}else {
return Result.error(ResponseCode.ERROR);
}
}
}
package com.cardiff.client_project.pojo.dto;
import lombok.Data;
import lombok.ToString;
import java.util.Date;
@Data
@ToString
public class SelectDTO {
private int id;
private String name;
private String email;
private String phone;
private String address;
private String type;
private String role;
private int maxAmount;
private int amountPatient;
private int status;
private Date freetime;
private int roleId;
}