camel-test01/camel-jdbc-yml/DatabaseInitializer.java

101 lines
3.9 KiB
Java

package com.example.util;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.ResultSet;
public class DatabaseInitializer implements Processor {
private static final Logger LOG = LoggerFactory.getLogger(DatabaseInitializer.class);
private DataSource dataSource;
public DatabaseInitializer(){
}
public DatabaseInitializer(DataSource dataSource) {
this.dataSource = dataSource;
}
// setter方法用于属性注入
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public void process(Exchange exchange) throws Exception {
LOG.info("初始化数据库...");
initializeDatabase();
insertInitialData();
LOG.info("数据库初始化完成");
}
private void initializeDatabase() {
try (Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(SqlQueries.CREATE_USERS_TABLE)) {
statement.execute();
LOG.info("用户表创建成功或已存在");
} catch (SQLException e) {
LOG.error("初始化数据库时出错", e);
throw new RuntimeException("初始化数据库时出错", e);
}
}
private void insertInitialData() {
try (Connection connection = dataSource.getConnection()) {
// 检查admin用户是否已存在
if (!userExists(connection, "admin")) {
insertUser(connection, "admin", "admin", "管理员", "admin@example.com", "13800000000", true);
LOG.info("已创建管理员用户: admin/admin");
}
// 检查普通用户是否已存在
if (!userExists(connection, "user")) {
insertUser(connection, "user", "user", "普通用户", "user@example.com", "13900000000", true);
LOG.info("已创建普通用户: user/user");
}
} catch (SQLException e) {
LOG.error("插入初始数据时出错", e);
throw new RuntimeException("插入初始数据时出错", e);
}
}
private boolean userExists(Connection connection, String username) throws SQLException {
String query = "SELECT COUNT(*) FROM users WHERE username = ?";
try (PreparedStatement ps = connection.prepareStatement(query)) {
ps.setString(1, username);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getInt(1) > 0;
}
}
}
return false;
}
private void insertUser(Connection connection, String username, String password,
String fullName, String email, String phone, boolean active) throws SQLException {
String query = "INSERT INTO users (username, password, full_name, email, phone, create_time, update_time, active) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis());
try (PreparedStatement ps = connection.prepareStatement(query)) {
ps.setString(1, username);
ps.setString(2, password); // 实际应用中应该对密码进行加密处理
ps.setString(3, fullName);
ps.setString(4, email);
ps.setString(5, phone);
ps.setTimestamp(6, now);
ps.setTimestamp(7, now);
ps.setBoolean(8, active);
ps.executeUpdate();
}
}
}