From 0bacd8996e52720bb1a486e58fb4ff9666d3d44f Mon Sep 17 00:00:00 2001 From: Markus Kreth Date: Wed, 2 Jan 2019 17:56:31 +0100 Subject: [PATCH] Hibernate refactoring --- .../google/GoogleBaseAdapter.java | 73 ++++++++---------- .../google/calendar/CalendarAdapter.java | 6 +- .../dao/ClubEventDaoImpl.java | 10 +-- .../vaadinclubhelper/data/Adress.java | 13 +++- .../data/ClubeventHasPerson.java | 35 +++++---- .../data/ClubeventPersonId.java | 69 +++++++++++++++++ src/main/resources/schema/version0.sql | 8 +- .../vaadin/clubhelper/HibernateHolder.java | 40 +++++++++- .../business/EventBusinessTest.java | 75 +++++++++++++++---- .../dao/AbstractDatabaseTest.java | 47 +++++++++--- 10 files changed, 273 insertions(+), 103 deletions(-) create mode 100644 src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/data/ClubeventPersonId.java diff --git a/src/main/java/de/kreth/clubhelperbackend/google/GoogleBaseAdapter.java b/src/main/java/de/kreth/clubhelperbackend/google/GoogleBaseAdapter.java index 66045ba..2b4082c 100644 --- a/src/main/java/de/kreth/clubhelperbackend/google/GoogleBaseAdapter.java +++ b/src/main/java/de/kreth/clubhelperbackend/google/GoogleBaseAdapter.java @@ -9,6 +9,7 @@ import java.nio.charset.Charset; import java.security.GeneralSecurityException; import java.util.Arrays; import java.util.List; +import java.util.Objects; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,11 +34,9 @@ public abstract class GoogleBaseAdapter { /** Application name. */ protected static final String APPLICATION_NAME = "ClubHelperVaadin"; /** Directory to store user credentials for this application. */ - protected static final File DATA_STORE_DIR = new File( - System.getProperty("catalina.base"), ".credentials"); + protected static final File DATA_STORE_DIR = new File(System.getProperty("catalina.base"), ".credentials"); /** Global instance of the JSON factory. */ - protected static final JsonFactory JSON_FACTORY = JacksonFactory - .getDefaultInstance(); + protected static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); /** * Global instance of the scopes required by this quickstart. * @@ -47,8 +46,7 @@ public abstract class GoogleBaseAdapter { private static Credential credential; - protected final Logger log = LoggerFactory - .getLogger(getClass()); + protected final Logger log = LoggerFactory.getLogger(getClass()); /** Global instance of the {@link FileDataStoreFactory}. */ protected final FileDataStoreFactory DATA_STORE_FACTORY; /** Global instance of the HTTP transport. */ @@ -68,20 +66,18 @@ public abstract class GoogleBaseAdapter { protected void checkRefreshToken(String serverName) throws IOException { synchronized (SCOPES) { if (credential == null) { - credential = authorize(serverName); + credential = Objects.requireNonNull(authorize(serverName)); } } - - if ((credential.getExpiresInSeconds() != null - && credential.getExpiresInSeconds() < 3600)) { + + if ((credential.getExpiresInSeconds() != null && credential.getExpiresInSeconds() < 3600)) { if (log.isDebugEnabled()) { log.debug("Security needs refresh, trying."); } boolean result = credential.refreshToken(); if (log.isDebugEnabled()) { - log.debug("Token refresh " - + (result ? "successfull." : "failed.")); + log.debug("Token refresh {}", (result ? "successfull." : "failed.")); } } } @@ -90,11 +86,10 @@ public abstract class GoogleBaseAdapter { if (credential == null) { throw new IllegalStateException("credential is null, checkRefreshToken need to be called before."); } - - return new com.google.api.services.calendar.Calendar.Builder( - HTTP_TRANSPORT, JSON_FACTORY, credential); + + return new com.google.api.services.calendar.Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential); } - + public final boolean refreshToken() throws IOException { return credential.refreshToken(); } @@ -107,61 +102,53 @@ public abstract class GoogleBaseAdapter { * @return an authorized Credential object. * @throws IOException */ - private Credential authorize(String serverName) - throws IOException { - if (credential != null && (credential.getExpiresInSeconds() != null - && credential.getExpiresInSeconds() < 3600)) { + private Credential authorize(String serverName) throws IOException { + if (credential != null + && (credential.getExpiresInSeconds() != null && credential.getExpiresInSeconds() < 3600)) { credential.refreshToken(); return credential; } + // Load client secrets. InputStream in = getClass().getResourceAsStream("/client_secret.json"); if (in == null) { - File inHome = new File(System.getProperty("user.home"), - "client_secret.json"); + File inHome = new File(System.getProperty("user.home"), "client_secret.json"); if (inHome.exists()) { if (log.isInfoEnabled()) { - log.info( - "Google secret not found as Resource, using user Home file."); + log.info("Google secret not found as Resource, using user Home file."); } in = new FileInputStream(inHome); } else { - log.error( - "Failed to load client_secret.json. Download from google console."); + log.error("Failed to load client_secret.json. Download from google console."); return null; } } - GoogleClientSecrets clientSecrets = GoogleClientSecrets - .load(JSON_FACTORY, new InputStreamReader(in, Charset.defaultCharset())); + GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, + new InputStreamReader(in, Charset.defaultCharset())); if (log.isTraceEnabled()) { log.trace("client secret json resource loaded."); } // Build flow and trigger user authorization request. - GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( - HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES) - .setDataStoreFactory(DATA_STORE_FACTORY) - .setAccessType("offline").setApprovalPrompt("force") - .build(); + GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, + clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).setAccessType("offline") + .setApprovalPrompt("force").build(); if (log.isDebugEnabled()) { - log.debug("Configuring google LocalServerReceiver on " + serverName - + ":" + GOOGLE_SECRET_PORT); + log.debug("Configuring google LocalServerReceiver on {}: {}", serverName, GOOGLE_SECRET_PORT); } - LocalServerReceiver localServerReceiver = new LocalServerReceiver.Builder() - .setHost(serverName).setPort(GOOGLE_SECRET_PORT).build(); + LocalServerReceiver localServerReceiver = new LocalServerReceiver.Builder().setHost(serverName) + .setPort(GOOGLE_SECRET_PORT).build(); - Credential credential = new AuthorizationCodeInstalledApp(flow, - localServerReceiver).authorize("user"); + Credential auth = new AuthorizationCodeInstalledApp(flow, localServerReceiver).authorize("user"); if (log.isDebugEnabled()) { - log.debug( - "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath()); + log.debug("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath()); } - credential.setExpiresInSeconds(Long.valueOf(691200L)); + auth.setExpiresInSeconds(Long.valueOf(691200L)); - return credential; + return auth; } } \ No newline at end of file diff --git a/src/main/java/de/kreth/clubhelperbackend/google/calendar/CalendarAdapter.java b/src/main/java/de/kreth/clubhelperbackend/google/calendar/CalendarAdapter.java index 60ba42f..961d628 100644 --- a/src/main/java/de/kreth/clubhelperbackend/google/calendar/CalendarAdapter.java +++ b/src/main/java/de/kreth/clubhelperbackend/google/calendar/CalendarAdapter.java @@ -1,3 +1,4 @@ + package de.kreth.clubhelperbackend.google.calendar; import java.io.IOException; @@ -50,8 +51,9 @@ public class CalendarAdapter extends GoogleBaseAdapter { } } } catch (InterruptedException e) { - if (log.isWarnEnabled()) { - log.warn("Lock interrupted", e); + log.warn("Lock interrupted", e); + if (service == null) { + throw new IOException("Unable to create Service", e); } } if (service == null) { diff --git a/src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/dao/ClubEventDaoImpl.java b/src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/dao/ClubEventDaoImpl.java index c246709..d8e5d42 100644 --- a/src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/dao/ClubEventDaoImpl.java +++ b/src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/dao/ClubEventDaoImpl.java @@ -16,6 +16,7 @@ import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.ClubEvent; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Person; @Repository +@Transactional public class ClubEventDaoImpl extends AbstractDaoImpl implements ClubEventDao { public ClubEventDaoImpl() { @@ -33,7 +34,6 @@ public class ClubEventDaoImpl extends AbstractDaoImpl implements Club } @Override - @Transactional public void addPersons(ClubEvent event, Collection updated) { List added = new ArrayList<>(updated); @@ -45,11 +45,11 @@ public class ClubEventDaoImpl extends AbstractDaoImpl implements Club event.setPersons(persons2); } - Query insertQuery = em - .createNativeQuery("INSERT INTO clubevent_has_person (clubevent_id, person_id) VALUES (?, ?)"); + Query insertQuery = em.createNativeQuery( + "INSERT INTO clubevent_has_person (clubevent_id, person_id) VALUES (:eventId,:personId)"); for (Person p : added) { - insertQuery.setParameter(1, event.getId()); - insertQuery.setParameter(2, p.getId()); + insertQuery.setParameter("eventId", event.getId()); + insertQuery.setParameter("personId", p.getId()); insertQuery.executeUpdate(); } diff --git a/src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/data/Adress.java b/src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/data/Adress.java index 5cfab39..6fbc9e0 100644 --- a/src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/data/Adress.java +++ b/src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/data/Adress.java @@ -1,17 +1,22 @@ package de.kreth.vaadin.clubhelper.vaadinclubhelper.data; import java.io.Serializable; -import javax.persistence.*; +import javax.persistence.Entity; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.Table; /** * The persistent class for the adress database table. * */ @Entity -@Table(name="adress") +@Table(name = "adress") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) -@NamedQuery(name="Adress.findAll", query="SELECT a FROM Adress a") +@NamedQuery(name = "Adress.findAll", query = "SELECT a FROM Adress a") public class Adress extends BaseEntity implements Serializable { private static final long serialVersionUID = 8216273166570667412L; @@ -24,7 +29,7 @@ public class Adress extends BaseEntity implements Serializable { private String plz; - //bi-directional many-to-one association to Person + // bi-directional many-to-one association to Person @ManyToOne private Person person; diff --git a/src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/data/ClubeventHasPerson.java b/src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/data/ClubeventHasPerson.java index ace4e76..2745d87 100644 --- a/src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/data/ClubeventHasPerson.java +++ b/src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/data/ClubeventHasPerson.java @@ -1,25 +1,31 @@ package de.kreth.vaadin.clubhelper.vaadinclubhelper.data; +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; +import javax.persistence.Table; + +@Entity +@Table(name = "clubevent_has_person") public class ClubeventHasPerson { - private String clubEventId; - private int personId; + @EmbeddedId + private ClubeventPersonId clubeventPersonId = new ClubeventPersonId(); private String comment; public String getClubEventId() { - return clubEventId; + return clubeventPersonId.getClubEventId(); } public void setClubEventId(String clubEventId) { - this.clubEventId = clubEventId; + this.clubeventPersonId.setClubEventId(clubEventId); } public int getPersonId() { - return personId; + return clubeventPersonId.getPersonId(); } public void setPersonId(int personId) { - this.personId = personId; + this.clubeventPersonId.setPersonId(personId); } public String getComment() { @@ -32,15 +38,15 @@ public class ClubeventHasPerson { @Override public String toString() { - return "ClubeventHasPerson [clubEventId=" + clubEventId + ", personId=" + personId + "]"; + return "ClubeventHasPerson [" + clubeventPersonId + ", comment=" + comment + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((clubEventId == null) ? 0 : clubEventId.hashCode()); - result = prime * result + personId; + result = prime * result + ((clubeventPersonId == null) ? 0 : clubeventPersonId.hashCode()); + result = prime * result + ((comment == null) ? 0 : comment.hashCode()); return result; } @@ -53,12 +59,15 @@ public class ClubeventHasPerson { if (getClass() != obj.getClass()) return false; ClubeventHasPerson other = (ClubeventHasPerson) obj; - if (clubEventId == null) { - if (other.clubEventId != null) + if (clubeventPersonId == null) { + if (other.clubeventPersonId != null) return false; - } else if (!clubEventId.equals(other.clubEventId)) + } else if (!clubeventPersonId.equals(other.clubeventPersonId)) return false; - if (personId != other.personId) + if (comment == null) { + if (other.comment != null) + return false; + } else if (!comment.equals(other.comment)) return false; return true; } diff --git a/src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/data/ClubeventPersonId.java b/src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/data/ClubeventPersonId.java new file mode 100644 index 0000000..9c59f82 --- /dev/null +++ b/src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/data/ClubeventPersonId.java @@ -0,0 +1,69 @@ +package de.kreth.vaadin.clubhelper.vaadinclubhelper.data; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Embeddable; + +@Embeddable +public class ClubeventPersonId implements Serializable { + + private static final long serialVersionUID = -7964369346971364916L; + + @Column(name = "clubevent_id") + private String clubEventId; + + @Column(name = "person_id") + private int personId; + + public String getClubEventId() { + return clubEventId; + } + + public void setClubEventId(String clubEventId) { + this.clubEventId = clubEventId; + } + + public int getPersonId() { + return personId; + } + + public void setPersonId(int personId) { + this.personId = personId; + } + + @Override + public String toString() { + return "ID [clubEventId=" + clubEventId + ", personId=" + personId + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((clubEventId == null) ? 0 : clubEventId.hashCode()); + result = prime * result + personId; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ClubeventPersonId other = (ClubeventPersonId) obj; + if (clubEventId == null) { + if (other.clubEventId != null) + return false; + } else if (!clubEventId.equals(other.clubEventId)) { + return false; + } + if (personId != other.personId) + return false; + return true; + } + +} \ No newline at end of file diff --git a/src/main/resources/schema/version0.sql b/src/main/resources/schema/version0.sql index 1f3dff1..56de309 100644 --- a/src/main/resources/schema/version0.sql +++ b/src/main/resources/schema/version0.sql @@ -1,4 +1,4 @@ -CREATE TABLE `clubhelper`.`ClubEvent` ( +CREATE TABLE `ClubEvent` ( `id` VARCHAR(250) NOT NULL, `location` VARCHAR(255) NULL, `iCalUID` VARCHAR(150) NULL, @@ -9,7 +9,7 @@ CREATE TABLE `clubhelper`.`ClubEvent` ( `end` DATETIME NULL, `allDay` SMALLINT(1) NULL, PRIMARY KEY (`id`)); -CREATE TABLE IF NOT EXISTS `clubhelper`.`clubevent_has_person` ( +CREATE TABLE IF NOT EXISTS `clubevent_has_person` ( `clubevent_id` VARCHAR(250) NOT NULL, `person_id` INT(11) NOT NULL, `comment` VARCHAR(250) NOT NULL DEFAULT '', @@ -18,11 +18,11 @@ CREATE TABLE IF NOT EXISTS `clubhelper`.`clubevent_has_person` ( INDEX `fk_clubevent_has_person_clubevent1_idx` (`clubevent_id` ASC) VISIBLE, CONSTRAINT `fk_clubevent_has_person_clubevent1` FOREIGN KEY (`clubevent_id`) - REFERENCES `clubhelper`.`clubevent` (`id`) + REFERENCES `clubevent` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_clubevent_has_person_person1` FOREIGN KEY (`person_id`) - REFERENCES `clubhelper`.`person` (`id`) + REFERENCES `person` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION); \ No newline at end of file diff --git a/src/test/java/de/kreth/vaadin/clubhelper/HibernateHolder.java b/src/test/java/de/kreth/vaadin/clubhelper/HibernateHolder.java index 87f502c..7674db1 100644 --- a/src/test/java/de/kreth/vaadin/clubhelper/HibernateHolder.java +++ b/src/test/java/de/kreth/vaadin/clubhelper/HibernateHolder.java @@ -1,9 +1,12 @@ package de.kreth.vaadin.clubhelper; +import java.io.File; + import org.hibernate.cfg.Configuration; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Adress; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Attendance; +import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.ClubeventHasPerson; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Contact; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.DeletedEntry; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.GroupDef; @@ -17,9 +20,9 @@ import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Version; public enum HibernateHolder { INSTANCE; - final Configuration configuration = createConfig(); + private final Configuration configuration = createConfig(); - org.hibernate.cfg.Configuration createConfig() { + private org.hibernate.cfg.Configuration createConfig() { Configuration configuration = new Configuration(); configuration.addAnnotatedClass(Adress.class); configuration.addAnnotatedClass(Attendance.class); @@ -33,12 +36,41 @@ public enum HibernateHolder { configuration.addAnnotatedClass(StartpassStartrechte.class); configuration.addAnnotatedClass(Version.class); configuration.addInputStream(getClass().getResourceAsStream("/schema/ClubEvent.hbm.xml")); + configuration.addAnnotatedClass(ClubeventHasPerson.class); + +// mysqlTest(configuration); + h2Memory(configuration); + + return configuration; + } + public void h2File(Configuration configuration) { + File f = new File("./database"); + System.out.println("Databasepath: " + f.getAbsolutePath()); configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); configuration.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); - configuration.setProperty("hibernate.connection.url", "jdbc:h2:mem:test"); + configuration.setProperty("hibernate.connection.url", "jdbc:h2:file:" + f.getAbsolutePath()); + configuration.setProperty("hibernate.hbm2ddl.auto", "create"); + } + + public void mysqlTest(Configuration configuration) { + configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); +// configuration.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver"); + configuration.setProperty("hibernate.connection.url", + "jdbc:mysql://localhost/test?useUnicode=yes&characterEncoding=utf8&serverTimezone=Europe/Berlin"); + configuration.setProperty("hibernate.connection.username", "markus"); + configuration.setProperty("hibernate.connection.password", "0773"); + configuration.setProperty("hibernate.hbm2ddl.auto", "update"); + configuration.setProperty("spring.jpa.hibernate.ddl-auto", "update"); + } + + public void h2Memory(Configuration configuration) { + + configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); + configuration.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); + + configuration.setProperty("hibernate.connection.url", "jdbc:h2:mem:test;DB_CLOSE_ON_EXIT=FALSE"); configuration.setProperty("hibernate.hbm2ddl.auto", "create"); - return configuration; } public static Configuration configuration() { diff --git a/src/test/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/business/EventBusinessTest.java b/src/test/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/business/EventBusinessTest.java index 7203ef7..1f6b70c 100644 --- a/src/test/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/business/EventBusinessTest.java +++ b/src/test/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/business/EventBusinessTest.java @@ -1,17 +1,22 @@ package de.kreth.vaadin.clubhelper.vaadinclubhelper.business; +import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.security.GeneralSecurityException; +import java.time.LocalDate; +import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.function.Consumer; import javax.persistence.EntityManager; +import javax.persistence.TypedQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -24,9 +29,11 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import de.kreth.clubhelperbackend.google.calendar.CalendarAdapter; import de.kreth.vaadin.clubhelper.HibernateHolder; import de.kreth.vaadin.clubhelper.vaadinclubhelper.dao.AbstractDatabaseTest; +import de.kreth.vaadin.clubhelper.vaadinclubhelper.dao.AbstractDatabaseTest.DB_TYPE; import de.kreth.vaadin.clubhelper.vaadinclubhelper.dao.ClubEventDao; import de.kreth.vaadin.clubhelper.vaadinclubhelper.dao.ClubEventDaoImpl; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.ClubEvent; +import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.ClubeventHasPerson; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Person; @ExtendWith(SpringExtension.class) @@ -36,7 +43,6 @@ class EventBusinessTest { private List persons; private ClubEvent event; - private DatabaseHelper helper; @Autowired private EventBusiness business; @@ -44,17 +50,26 @@ class EventBusinessTest { @Autowired private EntityManager entityManager; + private TypedQuery all; +// +// @Autowired +// private InnerConfig innerConfig; + @Configuration public static class InnerConfig { - @Bean - public EntityManager getEntityManager() throws Exception { + private SessionFactory sessionFactory; + + public InnerConfig() { org.hibernate.cfg.Configuration configuration = HibernateHolder.configuration(); - SessionFactory sessionFactory = configuration.buildSessionFactory(); - return sessionFactory.openSession(); + sessionFactory = configuration.buildSessionFactory(); + } + @Bean + public EntityManager getEntityManager() { + return sessionFactory.openSession(); } @Bean @@ -76,22 +91,42 @@ class EventBusinessTest { @BeforeEach void setUp() throws Exception { - helper = new DatabaseHelper(entityManager); - helper.cleanH2Database(); - insertTestData(); business.setSelected(event); + + all = entityManager.createQuery("from ClubeventHasPerson", ClubeventHasPerson.class); + } + + @AfterEach + void shutdown() { + entityManager.clear(); + ((Session) entityManager).doWork(conn -> AbstractDatabaseTest.cleanDatabase(conn, DB_TYPE.H2)); +// entityManager.flush(); } private void insertTestData() { - persons = helper.insertPersons(3); - event = helper.creteEvent(); - helper.transactional((session) -> session.save(event)); + persons = new ArrayList<>(); + + entityManager.getTransaction().begin(); + for (int i = 0; i < 3; i++) { + + Person p = new Person(); + p.setPrename("prename_" + i); + p.setSurname("surname_" + i); + p.setBirth(LocalDate.now()); + entityManager.persist(p); + persons.add(p); + } + event = AbstractDatabaseTest.creteEvent(); + assertNull(event.getPersons()); + entityManager.persist(event); + entityManager.getTransaction().commit(); } @Test void testDataCorrectlyCreated() { - assertEquals(0, helper.loadEventPersons().size()); + + assertEquals(0, all.getResultList().size()); List stored = entityManager.createNamedQuery(Person.QUERY_FINDALL, Person.class).getResultList(); assertEquals(3, stored.size()); @@ -105,10 +140,18 @@ class EventBusinessTest { @Test @Disabled void testAddPersonsToEvent() { - helper.transactional(() -> business.changePersons(new HashSet<>(persons.subList(0, 1)))); - helper.transactional(() -> business.changePersons(new HashSet<>(persons.subList(0, 2)))); + assertEquals(0, all.getResultList().size()); + + entityManager.getTransaction().begin(); + business.changePersons(new HashSet<>(persons.subList(0, 1))); + entityManager.getTransaction().commit(); + + entityManager.getTransaction().begin(); + business.changePersons(new HashSet<>(persons.subList(0, 2))); + entityManager.getTransaction().commit(); - assertEquals(2, helper.loadEventPersons().size()); + List result = all.getResultList(); + assertEquals(2, result.size()); } class DatabaseHelper extends AbstractDatabaseTest { @@ -117,7 +160,7 @@ class EventBusinessTest { } public DatabaseHelper(Session session) { - AbstractDatabaseTest.session = session; + this.session = session; } @Override diff --git a/src/test/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/dao/AbstractDatabaseTest.java b/src/test/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/dao/AbstractDatabaseTest.java index 26c19be..09eb318 100644 --- a/src/test/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/dao/AbstractDatabaseTest.java +++ b/src/test/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/dao/AbstractDatabaseTest.java @@ -21,6 +21,7 @@ import javax.persistence.EntityTransaction; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; @@ -35,7 +36,7 @@ public abstract class AbstractDatabaseTest { private static final AtomicInteger eventIdSequence = new AtomicInteger(); protected static SessionFactory sessionFactory; - protected static Session session; + protected Session session; @BeforeAll public static void setUpDatabase() throws Exception { @@ -44,7 +45,6 @@ public abstract class AbstractDatabaseTest { Configuration configuration = HibernateHolder.configuration(); sessionFactory = configuration.buildSessionFactory(); - session = sessionFactory.openSession(); } @@ -61,11 +61,24 @@ public abstract class AbstractDatabaseTest { final String enableReferentialIntegrety; } - @BeforeEach + @AfterEach public void cleanH2Database() { + if (session.getTransaction().isActive()) { + session.flush(); + } + session.doWork(conn -> { AbstractDatabaseTest.cleanDatabase(conn, DB_TYPE.H2); }); + + } + + @BeforeEach + void createSession() { + if (session != null) { + session.close(); + } + session = sessionFactory.openSession(); } public static void cleanDatabase(Connection connection, DB_TYPE type) throws SQLException { @@ -134,17 +147,11 @@ public abstract class AbstractDatabaseTest { public List insertPersons(int count) { - final List inserted = new ArrayList<>(); + final List inserted = createPersons(count); transactional(() -> { - for (int i = 0; i < count; i++) { - - Person p = new Person(); - p.setPrename("prename_" + i); - p.setSurname("surname_" + i); - p.setBirth(LocalDate.now()); + for (Person p : inserted) { session.save(p); - inserted.add(p); } }); for (Person p : inserted) { @@ -153,7 +160,23 @@ public abstract class AbstractDatabaseTest { return inserted; } - public ClubEvent creteEvent() { + public static List createPersons(int count) { + + final List inserted = new ArrayList<>(); + + for (int i = 0; i < count; i++) { + + Person p = new Person(); + p.setId(i + 1); + p.setPrename("prename_" + i); + p.setSurname("surname_" + i); + p.setBirth(LocalDate.now()); + inserted.add(p); + } + return inserted; + } + + public static ClubEvent creteEvent() { ClubEvent ev = ClubEventBuilder.builder().withId("id_" + eventIdSequence.getAndIncrement()).withAllDay(true) .withCaption("caption").withDescription("description") .withStart(ZonedDateTime.of(2018, 8, 13, 0, 0, 0, 0, ZoneId.systemDefault()))