55import org .slf4j .LoggerFactory ;
66import org .springframework .beans .factory .annotation .Autowired ;
77import org .springframework .beans .factory .annotation .Qualifier ;
8+ import org .springframework .beans .factory .annotation .Value ;
89import org .springframework .context .annotation .Profile ;
910import org .springframework .samples .petclinic .model .PatientRecord ;
1011import org .springframework .stereotype .Service ;
1516import org .springframework .transaction .support .DefaultTransactionDefinition ;
1617import org .springframework .jdbc .core .JdbcTemplate ;
1718
19+ import jakarta .annotation .PostConstruct ;
1820import java .time .LocalDateTime ;
1921import java .time .ZoneId ;
2022import java .util .ArrayList ;
@@ -34,6 +36,9 @@ public class PatientRecordDataService {
3436 private final JdbcTemplate mysqlJdbcTemplate ;
3537 private final PlatformTransactionManager mysqlTransactionManager ;
3638
39+ @ Value ("${app.patient.records.auto-init:false}" )
40+ private boolean autoInitEnabled ;
41+
3742 // List of veterinary treatment types
3843 private static final List <String > TREATMENT_TYPES = List .of (
3944 "Annual Wellness Exam" , "Vaccination (Rabies)" , "Vaccination (DHPP)" , "Vaccination (FVRCP)" ,
@@ -55,6 +60,35 @@ public PatientRecordDataService(PatientRecordRepository repository,
5560 this .mysqlTransactionManager = mysqlTransactionManager ;
5661 }
5762
63+ @ PostConstruct
64+ public void initializeSchema () {
65+ if (autoInitEnabled ) {
66+ logger .info ("Auto-initialization enabled - creating patient_records table if it doesn't exist" );
67+ try {
68+ String createTableSql =
69+ "CREATE TABLE IF NOT EXISTS patient_records (" +
70+ "id INT AUTO_INCREMENT PRIMARY KEY," +
71+ "treatment_type VARCHAR(255) NOT NULL," +
72+ "patient_weight INT NOT NULL," +
73+ "visit_date TIMESTAMP NOT NULL," +
74+ "treatment_completed BOOLEAN NOT NULL," +
75+ "medical_notes TEXT," +
76+ "INDEX idx_treatment_type (treatment_type)," +
77+ "INDEX idx_visit_date (visit_date)," +
78+ "INDEX idx_treatment_completed (treatment_completed)" +
79+ ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci" ;
80+
81+ mysqlJdbcTemplate .execute (createTableSql );
82+ logger .info ("Patient records table initialized successfully" );
83+ } catch (Exception e ) {
84+ logger .error ("Failed to initialize patient records schema" , e );
85+ throw new RuntimeException ("Failed to initialize patient records schema: " + e .getMessage (), e );
86+ }
87+ } else {
88+ logger .info ("Auto-initialization disabled - patient_records table must be created manually" );
89+ }
90+ }
91+
5892 @ Transactional ("mysqlTransactionManager" )
5993 public void cleanupPatientRecords () {
6094 logger .info ("Received request to clean up all patient records." );
0 commit comments