Hibernate refactoring

master
Markus Kreth 7 years ago
parent be04384cc4
commit 0bacd8996e
  1. 73
      src/main/java/de/kreth/clubhelperbackend/google/GoogleBaseAdapter.java
  2. 6
      src/main/java/de/kreth/clubhelperbackend/google/calendar/CalendarAdapter.java
  3. 10
      src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/dao/ClubEventDaoImpl.java
  4. 13
      src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/data/Adress.java
  5. 35
      src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/data/ClubeventHasPerson.java
  6. 69
      src/main/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/data/ClubeventPersonId.java
  7. 8
      src/main/resources/schema/version0.sql
  8. 40
      src/test/java/de/kreth/vaadin/clubhelper/HibernateHolder.java
  9. 75
      src/test/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/business/EventBusinessTest.java
  10. 47
      src/test/java/de/kreth/vaadin/clubhelper/vaadinclubhelper/dao/AbstractDatabaseTest.java

@ -9,6 +9,7 @@ import java.nio.charset.Charset;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Objects;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -33,11 +34,9 @@ public abstract class GoogleBaseAdapter {
/** Application name. */ /** Application name. */
protected static final String APPLICATION_NAME = "ClubHelperVaadin"; protected static final String APPLICATION_NAME = "ClubHelperVaadin";
/** Directory to store user credentials for this application. */ /** Directory to store user credentials for this application. */
protected static final File DATA_STORE_DIR = new File( protected static final File DATA_STORE_DIR = new File(System.getProperty("catalina.base"), ".credentials");
System.getProperty("catalina.base"), ".credentials");
/** Global instance of the JSON factory. */ /** Global instance of the JSON factory. */
protected static final JsonFactory JSON_FACTORY = JacksonFactory protected static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
.getDefaultInstance();
/** /**
* Global instance of the scopes required by this quickstart. * Global instance of the scopes required by this quickstart.
* *
@ -47,8 +46,7 @@ public abstract class GoogleBaseAdapter {
private static Credential credential; private static Credential credential;
protected final Logger log = LoggerFactory protected final Logger log = LoggerFactory.getLogger(getClass());
.getLogger(getClass());
/** Global instance of the {@link FileDataStoreFactory}. */ /** Global instance of the {@link FileDataStoreFactory}. */
protected final FileDataStoreFactory DATA_STORE_FACTORY; protected final FileDataStoreFactory DATA_STORE_FACTORY;
/** Global instance of the HTTP transport. */ /** Global instance of the HTTP transport. */
@ -68,20 +66,18 @@ public abstract class GoogleBaseAdapter {
protected void checkRefreshToken(String serverName) throws IOException { protected void checkRefreshToken(String serverName) throws IOException {
synchronized (SCOPES) { synchronized (SCOPES) {
if (credential == null) { if (credential == null) {
credential = authorize(serverName); credential = Objects.requireNonNull(authorize(serverName));
} }
} }
if ((credential.getExpiresInSeconds() != null if ((credential.getExpiresInSeconds() != null && credential.getExpiresInSeconds() < 3600)) {
&& credential.getExpiresInSeconds() < 3600)) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Security needs refresh, trying."); log.debug("Security needs refresh, trying.");
} }
boolean result = credential.refreshToken(); boolean result = credential.refreshToken();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Token refresh " log.debug("Token refresh {}", (result ? "successfull." : "failed."));
+ (result ? "successfull." : "failed."));
} }
} }
} }
@ -90,11 +86,10 @@ public abstract class GoogleBaseAdapter {
if (credential == null) { if (credential == null) {
throw new IllegalStateException("credential is null, checkRefreshToken need to be called before."); throw new IllegalStateException("credential is null, checkRefreshToken need to be called before.");
} }
return new com.google.api.services.calendar.Calendar.Builder( return new com.google.api.services.calendar.Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential);
HTTP_TRANSPORT, JSON_FACTORY, credential);
} }
public final boolean refreshToken() throws IOException { public final boolean refreshToken() throws IOException {
return credential.refreshToken(); return credential.refreshToken();
} }
@ -107,61 +102,53 @@ public abstract class GoogleBaseAdapter {
* @return an authorized Credential object. * @return an authorized Credential object.
* @throws IOException * @throws IOException
*/ */
private Credential authorize(String serverName) private Credential authorize(String serverName) throws IOException {
throws IOException { if (credential != null
if (credential != null && (credential.getExpiresInSeconds() != null && (credential.getExpiresInSeconds() != null && credential.getExpiresInSeconds() < 3600)) {
&& credential.getExpiresInSeconds() < 3600)) {
credential.refreshToken(); credential.refreshToken();
return credential; return credential;
} }
// Load client secrets. // Load client secrets.
InputStream in = getClass().getResourceAsStream("/client_secret.json"); InputStream in = getClass().getResourceAsStream("/client_secret.json");
if (in == null) { if (in == null) {
File inHome = new File(System.getProperty("user.home"), File inHome = new File(System.getProperty("user.home"), "client_secret.json");
"client_secret.json");
if (inHome.exists()) { if (inHome.exists()) {
if (log.isInfoEnabled()) { if (log.isInfoEnabled()) {
log.info( log.info("Google secret not found as Resource, using user Home file.");
"Google secret not found as Resource, using user Home file.");
} }
in = new FileInputStream(inHome); in = new FileInputStream(inHome);
} else { } else {
log.error( log.error("Failed to load client_secret.json. Download from google console.");
"Failed to load client_secret.json. Download from google console.");
return null; return null;
} }
} }
GoogleClientSecrets clientSecrets = GoogleClientSecrets GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
.load(JSON_FACTORY, new InputStreamReader(in, Charset.defaultCharset())); new InputStreamReader(in, Charset.defaultCharset()));
if (log.isTraceEnabled()) { if (log.isTraceEnabled()) {
log.trace("client secret json resource loaded."); log.trace("client secret json resource loaded.");
} }
// Build flow and trigger user authorization request. // Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES) clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).setAccessType("offline")
.setDataStoreFactory(DATA_STORE_FACTORY) .setApprovalPrompt("force").build();
.setAccessType("offline").setApprovalPrompt("force")
.build();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Configuring google LocalServerReceiver on " + serverName log.debug("Configuring google LocalServerReceiver on {}: {}", serverName, GOOGLE_SECRET_PORT);
+ ":" + GOOGLE_SECRET_PORT);
} }
LocalServerReceiver localServerReceiver = new LocalServerReceiver.Builder() LocalServerReceiver localServerReceiver = new LocalServerReceiver.Builder().setHost(serverName)
.setHost(serverName).setPort(GOOGLE_SECRET_PORT).build(); .setPort(GOOGLE_SECRET_PORT).build();
Credential credential = new AuthorizationCodeInstalledApp(flow, Credential auth = new AuthorizationCodeInstalledApp(flow, localServerReceiver).authorize("user");
localServerReceiver).authorize("user");
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug( log.debug("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
"Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
} }
credential.setExpiresInSeconds(Long.valueOf(691200L)); auth.setExpiresInSeconds(Long.valueOf(691200L));
return credential; return auth;
} }
} }

@ -1,3 +1,4 @@
package de.kreth.clubhelperbackend.google.calendar; package de.kreth.clubhelperbackend.google.calendar;
import java.io.IOException; import java.io.IOException;
@ -50,8 +51,9 @@ public class CalendarAdapter extends GoogleBaseAdapter {
} }
} }
} catch (InterruptedException e) { } 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) { if (service == null) {

@ -16,6 +16,7 @@ import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.ClubEvent;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Person; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Person;
@Repository @Repository
@Transactional
public class ClubEventDaoImpl extends AbstractDaoImpl<ClubEvent> implements ClubEventDao { public class ClubEventDaoImpl extends AbstractDaoImpl<ClubEvent> implements ClubEventDao {
public ClubEventDaoImpl() { public ClubEventDaoImpl() {
@ -33,7 +34,6 @@ public class ClubEventDaoImpl extends AbstractDaoImpl<ClubEvent> implements Club
} }
@Override @Override
@Transactional
public void addPersons(ClubEvent event, Collection<Person> updated) { public void addPersons(ClubEvent event, Collection<Person> updated) {
List<Person> added = new ArrayList<>(updated); List<Person> added = new ArrayList<>(updated);
@ -45,11 +45,11 @@ public class ClubEventDaoImpl extends AbstractDaoImpl<ClubEvent> implements Club
event.setPersons(persons2); event.setPersons(persons2);
} }
Query insertQuery = em Query insertQuery = em.createNativeQuery(
.createNativeQuery("INSERT INTO clubevent_has_person (clubevent_id, person_id) VALUES (?, ?)"); "INSERT INTO clubevent_has_person (clubevent_id, person_id) VALUES (:eventId,:personId)");
for (Person p : added) { for (Person p : added) {
insertQuery.setParameter(1, event.getId()); insertQuery.setParameter("eventId", event.getId());
insertQuery.setParameter(2, p.getId()); insertQuery.setParameter("personId", p.getId());
insertQuery.executeUpdate(); insertQuery.executeUpdate();
} }

@ -1,17 +1,22 @@
package de.kreth.vaadin.clubhelper.vaadinclubhelper.data; package de.kreth.vaadin.clubhelper.vaadinclubhelper.data;
import java.io.Serializable; 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. * The persistent class for the adress database table.
* *
*/ */
@Entity @Entity
@Table(name="adress") @Table(name = "adress")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE) @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 { public class Adress extends BaseEntity implements Serializable {
private static final long serialVersionUID = 8216273166570667412L; private static final long serialVersionUID = 8216273166570667412L;
@ -24,7 +29,7 @@ public class Adress extends BaseEntity implements Serializable {
private String plz; private String plz;
//bi-directional many-to-one association to Person // bi-directional many-to-one association to Person
@ManyToOne @ManyToOne
private Person person; private Person person;

@ -1,25 +1,31 @@
package de.kreth.vaadin.clubhelper.vaadinclubhelper.data; 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 { public class ClubeventHasPerson {
private String clubEventId; @EmbeddedId
private int personId; private ClubeventPersonId clubeventPersonId = new ClubeventPersonId();
private String comment; private String comment;
public String getClubEventId() { public String getClubEventId() {
return clubEventId; return clubeventPersonId.getClubEventId();
} }
public void setClubEventId(String clubEventId) { public void setClubEventId(String clubEventId) {
this.clubEventId = clubEventId; this.clubeventPersonId.setClubEventId(clubEventId);
} }
public int getPersonId() { public int getPersonId() {
return personId; return clubeventPersonId.getPersonId();
} }
public void setPersonId(int personId) { public void setPersonId(int personId) {
this.personId = personId; this.clubeventPersonId.setPersonId(personId);
} }
public String getComment() { public String getComment() {
@ -32,15 +38,15 @@ public class ClubeventHasPerson {
@Override @Override
public String toString() { public String toString() {
return "ClubeventHasPerson [clubEventId=" + clubEventId + ", personId=" + personId + "]"; return "ClubeventHasPerson [" + clubeventPersonId + ", comment=" + comment + "]";
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + ((clubEventId == null) ? 0 : clubEventId.hashCode()); result = prime * result + ((clubeventPersonId == null) ? 0 : clubeventPersonId.hashCode());
result = prime * result + personId; result = prime * result + ((comment == null) ? 0 : comment.hashCode());
return result; return result;
} }
@ -53,12 +59,15 @@ public class ClubeventHasPerson {
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
ClubeventHasPerson other = (ClubeventHasPerson) obj; ClubeventHasPerson other = (ClubeventHasPerson) obj;
if (clubEventId == null) { if (clubeventPersonId == null) {
if (other.clubEventId != null) if (other.clubeventPersonId != null)
return false; return false;
} else if (!clubEventId.equals(other.clubEventId)) } else if (!clubeventPersonId.equals(other.clubeventPersonId))
return false; return false;
if (personId != other.personId) if (comment == null) {
if (other.comment != null)
return false;
} else if (!comment.equals(other.comment))
return false; return false;
return true; return true;
} }

@ -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;
}
}

@ -1,4 +1,4 @@
CREATE TABLE `clubhelper`.`ClubEvent` ( CREATE TABLE `ClubEvent` (
`id` VARCHAR(250) NOT NULL, `id` VARCHAR(250) NOT NULL,
`location` VARCHAR(255) NULL, `location` VARCHAR(255) NULL,
`iCalUID` VARCHAR(150) NULL, `iCalUID` VARCHAR(150) NULL,
@ -9,7 +9,7 @@ CREATE TABLE `clubhelper`.`ClubEvent` (
`end` DATETIME NULL, `end` DATETIME NULL,
`allDay` SMALLINT(1) NULL, `allDay` SMALLINT(1) NULL,
PRIMARY KEY (`id`)); 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, `clubevent_id` VARCHAR(250) NOT NULL,
`person_id` INT(11) NOT NULL, `person_id` INT(11) NOT NULL,
`comment` VARCHAR(250) NOT NULL DEFAULT '', `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, INDEX `fk_clubevent_has_person_clubevent1_idx` (`clubevent_id` ASC) VISIBLE,
CONSTRAINT `fk_clubevent_has_person_clubevent1` CONSTRAINT `fk_clubevent_has_person_clubevent1`
FOREIGN KEY (`clubevent_id`) FOREIGN KEY (`clubevent_id`)
REFERENCES `clubhelper`.`clubevent` (`id`) REFERENCES `clubevent` (`id`)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION, ON UPDATE NO ACTION,
CONSTRAINT `fk_clubevent_has_person_person1` CONSTRAINT `fk_clubevent_has_person_person1`
FOREIGN KEY (`person_id`) FOREIGN KEY (`person_id`)
REFERENCES `clubhelper`.`person` (`id`) REFERENCES `person` (`id`)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION); ON UPDATE NO ACTION);

@ -1,9 +1,12 @@
package de.kreth.vaadin.clubhelper; package de.kreth.vaadin.clubhelper;
import java.io.File;
import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Configuration;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Adress; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Adress;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Attendance; 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.Contact;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.DeletedEntry; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.DeletedEntry;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.GroupDef; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.GroupDef;
@ -17,9 +20,9 @@ import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Version;
public enum HibernateHolder { public enum HibernateHolder {
INSTANCE; 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 configuration = new Configuration();
configuration.addAnnotatedClass(Adress.class); configuration.addAnnotatedClass(Adress.class);
configuration.addAnnotatedClass(Attendance.class); configuration.addAnnotatedClass(Attendance.class);
@ -33,12 +36,41 @@ public enum HibernateHolder {
configuration.addAnnotatedClass(StartpassStartrechte.class); configuration.addAnnotatedClass(StartpassStartrechte.class);
configuration.addAnnotatedClass(Version.class); configuration.addAnnotatedClass(Version.class);
configuration.addInputStream(getClass().getResourceAsStream("/schema/ClubEvent.hbm.xml")); 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.dialect", "org.hibernate.dialect.H2Dialect");
configuration.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); 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"); configuration.setProperty("hibernate.hbm2ddl.auto", "create");
return configuration;
} }
public static Configuration configuration() { public static Configuration configuration() {

@ -1,17 +1,22 @@
package de.kreth.vaadin.clubhelper.vaadinclubhelper.business; package de.kreth.vaadin.clubhelper.vaadinclubhelper.business;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException; import java.io.IOException;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test; 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.clubhelperbackend.google.calendar.CalendarAdapter;
import de.kreth.vaadin.clubhelper.HibernateHolder; import de.kreth.vaadin.clubhelper.HibernateHolder;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.dao.AbstractDatabaseTest; 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.ClubEventDao;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.dao.ClubEventDaoImpl; import de.kreth.vaadin.clubhelper.vaadinclubhelper.dao.ClubEventDaoImpl;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.ClubEvent; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.ClubEvent;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.ClubeventHasPerson;
import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Person; import de.kreth.vaadin.clubhelper.vaadinclubhelper.data.Person;
@ExtendWith(SpringExtension.class) @ExtendWith(SpringExtension.class)
@ -36,7 +43,6 @@ class EventBusinessTest {
private List<Person> persons; private List<Person> persons;
private ClubEvent event; private ClubEvent event;
private DatabaseHelper helper;
@Autowired @Autowired
private EventBusiness business; private EventBusiness business;
@ -44,17 +50,26 @@ class EventBusinessTest {
@Autowired @Autowired
private EntityManager entityManager; private EntityManager entityManager;
private TypedQuery<ClubeventHasPerson> all;
//
// @Autowired
// private InnerConfig innerConfig;
@Configuration @Configuration
public static class InnerConfig { public static class InnerConfig {
@Bean private SessionFactory sessionFactory;
public EntityManager getEntityManager() throws Exception {
public InnerConfig() {
org.hibernate.cfg.Configuration configuration = HibernateHolder.configuration(); org.hibernate.cfg.Configuration configuration = HibernateHolder.configuration();
SessionFactory sessionFactory = configuration.buildSessionFactory(); sessionFactory = configuration.buildSessionFactory();
return sessionFactory.openSession(); }
@Bean
public EntityManager getEntityManager() {
return sessionFactory.openSession();
} }
@Bean @Bean
@ -76,22 +91,42 @@ class EventBusinessTest {
@BeforeEach @BeforeEach
void setUp() throws Exception { void setUp() throws Exception {
helper = new DatabaseHelper(entityManager);
helper.cleanH2Database();
insertTestData(); insertTestData();
business.setSelected(event); 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() { private void insertTestData() {
persons = helper.insertPersons(3); persons = new ArrayList<>();
event = helper.creteEvent();
helper.transactional((session) -> session.save(event)); 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 @Test
void testDataCorrectlyCreated() { void testDataCorrectlyCreated() {
assertEquals(0, helper.loadEventPersons().size());
assertEquals(0, all.getResultList().size());
List<Person> stored = entityManager.createNamedQuery(Person.QUERY_FINDALL, Person.class).getResultList(); List<Person> stored = entityManager.createNamedQuery(Person.QUERY_FINDALL, Person.class).getResultList();
assertEquals(3, stored.size()); assertEquals(3, stored.size());
@ -105,10 +140,18 @@ class EventBusinessTest {
@Test @Test
@Disabled @Disabled
void testAddPersonsToEvent() { void testAddPersonsToEvent() {
helper.transactional(() -> business.changePersons(new HashSet<>(persons.subList(0, 1)))); assertEquals(0, all.getResultList().size());
helper.transactional(() -> business.changePersons(new HashSet<>(persons.subList(0, 2))));
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<ClubeventHasPerson> result = all.getResultList();
assertEquals(2, result.size());
} }
class DatabaseHelper extends AbstractDatabaseTest { class DatabaseHelper extends AbstractDatabaseTest {
@ -117,7 +160,7 @@ class EventBusinessTest {
} }
public DatabaseHelper(Session session) { public DatabaseHelper(Session session) {
AbstractDatabaseTest.session = session; this.session = session;
} }
@Override @Override

@ -21,6 +21,7 @@ import javax.persistence.EntityTransaction;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Configuration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
@ -35,7 +36,7 @@ public abstract class AbstractDatabaseTest {
private static final AtomicInteger eventIdSequence = new AtomicInteger(); private static final AtomicInteger eventIdSequence = new AtomicInteger();
protected static SessionFactory sessionFactory; protected static SessionFactory sessionFactory;
protected static Session session; protected Session session;
@BeforeAll @BeforeAll
public static void setUpDatabase() throws Exception { public static void setUpDatabase() throws Exception {
@ -44,7 +45,6 @@ public abstract class AbstractDatabaseTest {
Configuration configuration = HibernateHolder.configuration(); Configuration configuration = HibernateHolder.configuration();
sessionFactory = configuration.buildSessionFactory(); sessionFactory = configuration.buildSessionFactory();
session = sessionFactory.openSession();
} }
@ -61,11 +61,24 @@ public abstract class AbstractDatabaseTest {
final String enableReferentialIntegrety; final String enableReferentialIntegrety;
} }
@BeforeEach @AfterEach
public void cleanH2Database() { public void cleanH2Database() {
if (session.getTransaction().isActive()) {
session.flush();
}
session.doWork(conn -> { session.doWork(conn -> {
AbstractDatabaseTest.cleanDatabase(conn, DB_TYPE.H2); 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 { public static void cleanDatabase(Connection connection, DB_TYPE type) throws SQLException {
@ -134,17 +147,11 @@ public abstract class AbstractDatabaseTest {
public List<Person> insertPersons(int count) { public List<Person> insertPersons(int count) {
final List<Person> inserted = new ArrayList<>(); final List<Person> inserted = createPersons(count);
transactional(() -> { transactional(() -> {
for (int i = 0; i < count; i++) { for (Person p : inserted) {
Person p = new Person();
p.setPrename("prename_" + i);
p.setSurname("surname_" + i);
p.setBirth(LocalDate.now());
session.save(p); session.save(p);
inserted.add(p);
} }
}); });
for (Person p : inserted) { for (Person p : inserted) {
@ -153,7 +160,23 @@ public abstract class AbstractDatabaseTest {
return inserted; return inserted;
} }
public ClubEvent creteEvent() { public static List<Person> createPersons(int count) {
final List<Person> 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) ClubEvent ev = ClubEventBuilder.builder().withId("id_" + eventIdSequence.getAndIncrement()).withAllDay(true)
.withCaption("caption").withDescription("description") .withCaption("caption").withDescription("description")
.withStart(ZonedDateTime.of(2018, 8, 13, 0, 0, 0, 0, ZoneId.systemDefault())) .withStart(ZonedDateTime.of(2018, 8, 13, 0, 0, 0, 0, ZoneId.systemDefault()))

Loading…
Cancel
Save