0

Имеется private внутренний класс с двумя методами для работы с базой данных. Появилась идея определить стандартные запросы к базе в аннотации.

Определение аннотации:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface QueryAnnotation {
    String select();
}

Внутренний класс:

@QueryAnnotation(
            select = "SELECT * FROM train"
    )
    private class TrainJDBCRunner {
        public TrainJDBCRunner() {
        }
        private ArrayList<Train> readData() throws SQLException {
            Connection cn = null;
            ArrayList<Train> listTrains = null;
            try {
                DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                cn = ConnectionDB.getConnection();
                Statement st = null;
                try {
                    st = cn.createStatement();
                    listTrains = getTrains(st);
                } finally {
                    if (st != null) { // для 2-го блока try
                        st.close();
                    } else {
                        System.err.println("Statement не создан");
                    }
                }
            } catch (SQLException e) { // для 1-го блока try
                System.err.println("DB connection error: " + e);
            } finally {
                if (cn != null) {
                    try {
                        cn.close();
                    } catch (SQLException e) {
                        System.err.println("Сonnection close error: " + e);
                    }
                }
            }
            return listTrains;
        }

        private ArrayList<Train> getTrains(Statement st) throws SQLException {
            ResultSet rs = null;
            ArrayList<Train> list = null;
            try {
                 Class<Train> f = Train.class;
                 QueryAnnotation queryAnnotation =(QueryAnnotation)f.getAnnotation(QueryAnnotation.class);
           System.out.println(f.isAnnotationPresent(QueryAnnotation.class));//<-- false
            rs = st.executeQuery(queryAnnotation.select());//<-- NullPointerExceptions
                list = new ArrayList<>();
                while (rs.next()) {
                    int id_tr = rs.getInt(1);
                    String tr_number = rs.getString(2);
                    String dep = rs.getString(3);
                    String arr = rs.getString(4);
                    int fre = rs.getInt(5);
                    int pur = rs.getInt(6);
                    list.add(new Train(id_tr, tr_number, dep, arr, fre, pur));
                }
                if (list.isEmpty()) {
                    System.out.println("Not found");
                }
            } finally { // для 3-го блока try
                if (rs != null) { // был ли создан ResultSet
                    rs.close();
                } else {
                    Class<Train> f = Train.class;
                    QueryAnnotation queryAnnotation = (QueryAnnotation) f.getAnnotation(QueryAnnotation.class);
                    System.out.println(f.isAnnotationPresent(QueryAnnotation.class));
                    System.err.println("ошибка во время чтения из БД");//
                }
            }
            return list;
        }
    }

Вопрос заключается в следующем: после выполнения этой строчки QueryAnnotation queryAnnotation = (QueryAnnotation) f.getAnnotation(QueryAnnotation.class); ничего не возвращается. В чем может быть проблема?

1 ответ 1

3

Пока писал сам вопрос нашел решение проблемы. Вся фишка была в этой строчке:

Class<Train> f = Train.class;

а нужно было:

Class<Train.TrainJDBCRunner> f = Train.TrainJDBCRunner.class;

т.к. TrainJDBCRunner inner class, а Train внешний.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.