Skip to content

Hibernate 3#16

Open
agarkovand wants to merge 17 commits intoReleasefrom
Hibernate-3
Open

Hibernate 3#16
agarkovand wants to merge 17 commits intoReleasefrom
Hibernate-3

Conversation

@agarkovand
Copy link
Copy Markdown
Owner

Tasks according to Assignment

return new QPredicate();
}

public <T> QPredicate add(T object, Function<T, Predicate> function) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

подумай как бы выглядел QPredicate если бы тебе нужно было добавить проверку на коллекцию isEmpty (если будут такие параметры в фильтре - то придется добавить)

public class AbstractDaoTest {

protected SessionFactory sessionFactory;
protected Session session;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 сессия на 1 метод, а не на все методы - она же хранит состояние

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

так она у меня открывается и закрывается для каждого метода - BeforeEach, AfterEach

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

да, все ок будет работать, если инициализировать в BeforeEach, AfterEach!

saveFootbalClub(session, FC_NAMES[1], Warszawa);
saveFootbalClub(session, FC_NAMES[2], Kharkov);
saveFootbalClub(session, FC_NAMES[3], Kiev);
saveFootbalClub(session, FC_NAMES[4], Minsk);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а почему не список используешь?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

список вместо массива? Массив вроде более лаконично выглядит, из листа пришлось бы вызывать метод гет(0), гет(1) и т.д.

}

@Override
public List<FootballClub> findByCountryAndRegion(Session session, Country country, String region) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

уже лучше!
Но все еще нужно передавать один объект фильтр с полями, по которым будешь фильтровать. Обычно такие фильтры имеют свойства разрастаться (увеличивается кол-во полей). В таком вариант как здесь - уже 3 параметра. И уже увеличивать до 4-5 выглядит не очень.

}

@Override
public List<FootballClub> findByCountryAndRegion(Session session, Country country, String region) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

здесь то же самое - нужно параметры представить в виде одного объекта фильтра

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это сделаю попозже

sessionFactory.close();
}

protected static Stream<FootballClubDao> footballClubDaoSource() {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

абстрактные классы не могут иметь ссылка на какие-то конкретные реализации - поэтому этот метод отображает неправильное проектирование

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Этот метод вроде как утилитный - поэтому я его вынес в родителя, могу конечно обратно в наследника перенести

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

даже если утилитный - он все еще находится в абстрактном классе, который не должен хранить информации про какие-то реализации, которые будут тестироваться. Это все равно, что в интерфейсе List хранить ссылки на ArrayList/LinkedList

City.class)
.setParameter("city", "Kielce")
.list();
actual = nativeQueryResult.get(0);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

одни и те же ссылки не переиспользуют в тестах для разных значений - чтобы избегать flaky (хотя и в обычном коде лучше этого избегать тоже)


public static void initDataBase(SessionFactory sessionFactory) {
@Cleanup Session session = sessionFactory.openSession();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не забывай открывать транзакцию перед сохранением

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут с транзакцией я похоже накосячил? Почему тогда работало? Хибернейт и без транзакции все сохранил?
Как тогда? Добавить следующей строкой
session.beginTransaction();
а после сохранения всех тестовых данных закрыть транзакцию?
session.getTransaction().commit();
Или надо как-то обернуть в try-catch-finally?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Может работать - может не работать. Hibernate все еще есть по умолчанию механизм очень похожий на auto-commit mode. Но он может не сработать во многих ситуациях (я в видео показывал). Поэтому лучше всегда явно открывать и закрывать транзакции.

В текущей реализации будет работать - все ок. Но проще вообще session передавать и вызывать этот метод перед каждым методом, а не sessionFactory, чтобы не коммитать транзакцию.

public static FootballClub[] SWIETOKRZYSKIE_FC;
public static String[] SWIETOKRZYSKIE_FC_NAMES;
public static FootballClub[] BELARUS_FC;
public static String[] BELARUS_FC_NAMES;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лучше используй коллекции, а не массивы

@agarkovand agarkovand linked an issue Mar 5, 2024 that may be closed by this pull request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Hibernate-3 Assignment

2 participants