Hibernate refactoring

master
Markus Kreth 7 years ago
parent be04384cc4
commit 0bacd8996e
  1. 67
      src/main/java/de/kreth/clubhelperbackend/google/GoogleBaseAdapter.java
  2. 4
      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. 43
      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.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."));
}
}
}
@ -91,8 +87,7 @@ public abstract class GoogleBaseAdapter {
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 {
@ -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;
}
}

@ -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);
if (service == null) {
throw new IOException("Unable to create Service", e);
}
}
if (service == null) {

@ -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<ClubEvent> implements ClubEventDao {
public ClubEventDaoImpl() {
@ -33,7 +34,6 @@ public class ClubEventDaoImpl extends AbstractDaoImpl<ClubEvent> implements Club
}
@Override
@Transactional
public void addPersons(ClubEvent event, Collection<Person> updated) {
List<Person> added = new ArrayList<>(updated);
@ -45,11 +45,11 @@ public class ClubEventDaoImpl extends AbstractDaoImpl<ClubEvent> 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();
}

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

@ -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 (!clubeventPersonId.equals(other.clubeventPersonId))
return false;
} else if (!clubEventId.equals(other.clubEventId))
if (comment == null) {
if (other.comment != null)
return false;
if (personId != other.personId)
} else if (!comment.equals(other.comment))
return false;
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,
`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);

@ -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() {

@ -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<Person> persons;
private ClubEvent event;
private DatabaseHelper helper;
@Autowired
private EventBusiness business;
@ -44,17 +50,26 @@ class EventBusinessTest {
@Autowired
private EntityManager entityManager;
private TypedQuery<ClubeventHasPerson> 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<Person> 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<ClubeventHasPerson> 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

@ -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,26 +147,36 @@ public abstract class AbstractDatabaseTest {
public List<Person> insertPersons(int count) {
final List<Person> inserted = new ArrayList<>();
final List<Person> inserted = createPersons(count);
transactional(() -> {
for (Person p : inserted) {
session.save(p);
}
});
for (Person p : inserted) {
assertTrue(p.getId() > 0, "not saved: " + p);
}
return inserted;
}
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());
session.save(p);
inserted.add(p);
}
});
for (Person p : inserted) {
assertTrue(p.getId() > 0, "not saved: " + p);
}
return inserted;
}
public ClubEvent creteEvent() {
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()))

Loading…
Cancel
Save