Skip to content

Commit

Permalink
Merge c08b811 into 2675360
Browse files Browse the repository at this point in the history
  • Loading branch information
vvondra committed Feb 9, 2017
2 parents 2675360 + c08b811 commit 8c37ec6
Show file tree
Hide file tree
Showing 14 changed files with 83 additions and 39 deletions.
1 change: 1 addition & 0 deletions docs/source/about/release-notes.rst
Expand Up @@ -9,6 +9,7 @@ Release Notes
v1.1.0: Unreleased
==================

* Upgraded to Hibernate ORM 5.2.7, introducing a series of deprecations and API changes in preparation for Hibernate ORM 6 `#1871 <https://github.com/dropwizard/dropwizard/pull/1871>`
* Add runtime certificate reload via admin task `#1799 <https://github.com/dropwizard/dropwizard/pull/1799>`_
* Invalid enum request parameters result in 400 response with possible choices `#1734 <https://github.com/dropwizard/dropwizard/pull/1734>`_
* Enum request parameters are deserialized in the same fuzzy manner, as the request body `#1734 <https://github.com/dropwizard/dropwizard/pull/1734>`_
Expand Down
8 changes: 2 additions & 6 deletions dropwizard-bom/pom.xml
Expand Up @@ -104,12 +104,8 @@
<dependency>
<groupId>org.jadira.usertype</groupId>
<artifactId>usertype.core</artifactId>
<version>5.0.0.GA</version>
<version>6.0.1.GA</version>
<exclusions>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
Expand All @@ -123,7 +119,7 @@
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.1.0.Final</version>
<version>5.2.7.Final</version>
<exclusions>
<exclusion>
<groupId>org.jboss.logging</groupId>
Expand Down
Expand Up @@ -4,9 +4,9 @@
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;

import java.io.Serializable;
import java.util.List;
Expand Down
Expand Up @@ -44,7 +44,7 @@ protected Result check() throws Exception {
try (Session session = sessionFactory.openSession()) {
final Transaction txn = session.beginTransaction();
try {
session.createSQLQuery(validationQuery).list();
session.createNativeQuery(validationQuery).list();
txn.commit();
} catch (Exception e) {
if (txn.getStatus().canRollback()) {
Expand Down
Expand Up @@ -114,7 +114,7 @@ public void onFinish() {
protected void configureSession() {
session.setDefaultReadOnly(unitOfWork.readOnly());
session.setCacheMode(unitOfWork.cacheMode());
session.setFlushMode(unitOfWork.flushMode());
session.setHibernateFlushMode(unitOfWork.flushMode());
}

private void beginTransaction() {
Expand Down
Expand Up @@ -3,9 +3,9 @@
import com.google.common.collect.ImmutableList;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;
import org.junit.Before;
Expand Down
@@ -1,22 +1,18 @@
package io.dropwizard.hibernate;

import io.dropwizard.jersey.errors.ErrorMessage;
import org.hibernate.exception.DataException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import io.dropwizard.jersey.errors.ErrorMessage;

@Provider
public class DataExceptionMapper implements ExceptionMapper<DataException> {

private static final Logger LOGGER = LoggerFactory.getLogger(DataException.class);

@Override
public Response toResponse(DataException e) {
LOGGER.error("Hibernate error", e);
String message = e.getCause().getMessage().contains("EMAIL") ? "Wrong email" : "Wrong input";

return Response.status(Response.Status.BAD_REQUEST)
Expand Down
Expand Up @@ -16,6 +16,7 @@
import org.glassfish.jersey.test.TestProperties;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.After;
Expand Down Expand Up @@ -117,19 +118,22 @@ protected Application configure() {
ImmutableList.of(Person.class));

try (Session session = sessionFactory.openSession()) {
session.createSQLQuery("DROP TABLE people IF EXISTS").executeUpdate();
session.createSQLQuery(
Transaction transaction = session.beginTransaction();
session.createNativeQuery("DROP TABLE people IF EXISTS").executeUpdate();
session.createNativeQuery(
"CREATE TABLE people (name varchar(100) primary key, email varchar(16), birthday timestamp with time zone)")
.executeUpdate();
session.createSQLQuery(
session.createNativeQuery(
"INSERT INTO people VALUES ('Coda', 'coda@example.com', '1979-01-02 00:22:00+0:00')")
.executeUpdate();
transaction.commit();
}

final DropwizardResourceConfig config = DropwizardResourceConfig.forTesting(new MetricRegistry());
config.register(new UnitOfWorkApplicationListener("hr-db", sessionFactory));
config.register(new PersonResource(new PersonDAO(sessionFactory)));
config.register(new JacksonMessageBodyProvider(Jackson.newObjectMapper()));
config.register(new PersistenceExceptionMapper());
config.register(new DataExceptionMapper());
config.register(new EmptyOptionalExceptionMapper());

Expand Down
Expand Up @@ -17,6 +17,7 @@
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException;
import org.junit.After;
import org.junit.Test;
Expand Down Expand Up @@ -70,23 +71,26 @@ public void run(TestConfiguration configuration, Environment environment) throws

environment.jersey().register(new UnitOfWorkApplicationListener("hr-db", sessionFactory));
environment.jersey().register(new DogResource(new DogDAO(sessionFactory)));
environment.jersey().register(new PersistenceExceptionMapper());
environment.jersey().register(new ConstraintViolationExceptionMapper());
}

private void initDatabase(SessionFactory sessionFactory) {
try (Session session = sessionFactory.openSession()) {
session.createSQLQuery(
Transaction transaction = session.beginTransaction();
session.createNativeQuery(
"CREATE TABLE people (name varchar(100) primary key, email varchar(16), birthday timestamp with time zone)")
.executeUpdate();
session.createSQLQuery(
session.createNativeQuery(
"INSERT INTO people VALUES ('Coda', 'coda@example.com', '1979-01-02 00:22:00+0:00')")
.executeUpdate();
session.createSQLQuery(
session.createNativeQuery(
"CREATE TABLE dogs (name varchar(100) primary key, owner varchar(100), CONSTRAINT fk_owner FOREIGN KEY (owner) REFERENCES people(name))")
.executeUpdate();
session.createSQLQuery(
session.createNativeQuery(
"INSERT INTO dogs VALUES ('Raf', 'Coda')")
.executeUpdate();
transaction.commit();
}
}
}
Expand All @@ -109,7 +113,7 @@ Optional<Dog> findByName(String name) {
}

Dog create(Dog dog) throws HibernateException {
currentSession().setFlushMode(FlushMode.COMMIT);
currentSession().setHibernateFlushMode(FlushMode.COMMIT);
currentSession().save(requireNonNull(dog));
return dog;
}
Expand Down
@@ -0,0 +1,37 @@
package io.dropwizard.hibernate;

import org.hibernate.exception.DataException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.PersistenceException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.Providers;

@Provider
public class PersistenceExceptionMapper implements ExceptionMapper<PersistenceException> {

private static final Logger LOGGER = LoggerFactory.getLogger(DataException.class);

@Context
private Providers providers;

@Override
public Response toResponse(PersistenceException e) {
LOGGER.error("Hibernate error", e);

Throwable t = e.getCause();

// PersistenceException wraps the real exception, so we look for the real exception mapper for it
// Cast is necessary since the return type is ExceptionMapper<? extends Throwable> and Java
// does not allow calling toResponse on the method with a Throwable
@SuppressWarnings("unchecked")
final ExceptionMapper<Throwable> exceptionMapper = (ExceptionMapper<Throwable>) providers.getExceptionMapper(t.getClass());

return exceptionMapper.toResponse(t);

}
}
Expand Up @@ -105,9 +105,10 @@ public void buildsAWorkingSessionFactory() throws Exception {
build();

try (Session session = sessionFactory.openSession()) {
session.createSQLQuery("DROP TABLE people IF EXISTS").executeUpdate();
session.createSQLQuery("CREATE TABLE people (name varchar(100) primary key, email varchar(100), birthday timestamp(0))").executeUpdate();
session.createSQLQuery("INSERT INTO people VALUES ('Coda', 'coda@example.com', '1979-01-02 00:22:00')").executeUpdate();
session.beginTransaction();
session.createNativeQuery("DROP TABLE people IF EXISTS").executeUpdate();
session.createNativeQuery("CREATE TABLE people (name varchar(100) primary key, email varchar(100), birthday timestamp(0))").executeUpdate();
session.createNativeQuery("INSERT INTO people VALUES ('Coda', 'coda@example.com', '1979-01-02 00:22:00')").executeUpdate();

final Person entity = session.get(Person.class, "Coda");

Expand Down
Expand Up @@ -2,10 +2,10 @@

import com.codahale.metrics.health.HealthCheck;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.NativeQuery;
import org.junit.Test;
import org.mockito.InOrder;

Expand Down Expand Up @@ -44,16 +44,16 @@ public void isHealthyIfNoExceptionIsThrown() throws Exception {
final Transaction transaction = mock(Transaction.class);
when(session.beginTransaction()).thenReturn(transaction);

final SQLQuery query = mock(SQLQuery.class);
when(session.createSQLQuery(anyString())).thenReturn(query);
final NativeQuery query = mock(NativeQuery.class);
when(session.createNativeQuery(anyString())).thenReturn(query);

assertThat(healthCheck.execute())
.isEqualTo(HealthCheck.Result.healthy());

final InOrder inOrder = inOrder(factory, session, transaction, query);
inOrder.verify(factory).openSession();
inOrder.verify(session).beginTransaction();
inOrder.verify(session).createSQLQuery("SELECT 1");
inOrder.verify(session).createNativeQuery("SELECT 1");
inOrder.verify(query).list();
inOrder.verify(transaction).commit();
inOrder.verify(session).close();
Expand All @@ -68,8 +68,8 @@ public void isUnhealthyIfAnExceptionIsThrown() throws Exception {
when(session.beginTransaction()).thenReturn(transaction);
when(transaction.getStatus()).thenReturn(ACTIVE);

final SQLQuery query = mock(SQLQuery.class);
when(session.createSQLQuery(anyString())).thenReturn(query);
final NativeQuery query = mock(NativeQuery.class);
when(session.createNativeQuery(anyString())).thenReturn(query);
when(query.list()).thenThrow(new HibernateException("OH NOE"));

assertThat(healthCheck.execute().isHealthy())
Expand All @@ -78,7 +78,7 @@ public void isUnhealthyIfAnExceptionIsThrown() throws Exception {
final InOrder inOrder = inOrder(factory, session, transaction, query);
inOrder.verify(factory).openSession();
inOrder.verify(session).beginTransaction();
inOrder.verify(session).createSQLQuery("SELECT 1");
inOrder.verify(session).createNativeQuery("SELECT 1");
inOrder.verify(query).list();
inOrder.verify(transaction).rollback();
inOrder.verify(session).close();
Expand Down
Expand Up @@ -125,7 +125,7 @@ public void configuresTheSessionsFlushMode() throws Exception {

execute();

verify(session).setFlushMode(FlushMode.ALWAYS);
verify(session).setHibernateFlushMode(FlushMode.ALWAYS);
}

@Test
Expand Down
Expand Up @@ -9,6 +9,7 @@
import io.dropwizard.setup.Environment;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
Expand Down Expand Up @@ -51,10 +52,12 @@ public void setUp() throws Exception {
sessionFactory = new SessionFactoryFactory()
.build(bundle, environment, dataSourceFactory, ImmutableList.of());
try (Session session = sessionFactory.openSession()) {
session.createSQLQuery("create table user_sessions (token varchar(64) primary key, username varchar(16))")
Transaction transaction = session.beginTransaction();
session.createNativeQuery("create table user_sessions (token varchar(64) primary key, username varchar(16))")
.executeUpdate();
session.createSQLQuery("insert into user_sessions values ('67ab89d', 'jeff_28')")
session.createNativeQuery("insert into user_sessions values ('67ab89d', 'jeff_28')")
.executeUpdate();
transaction.commit();
}
}

Expand Down Expand Up @@ -125,7 +128,7 @@ public SessionDao(SessionFactory sessionFactory) {

public boolean isExist(String token) {
return sessionFactory.getCurrentSession()
.createSQLQuery("select username from user_sessions where token=:token")
.createNativeQuery("select username from user_sessions where token=:token")
.setParameter("token", token)
.list()
.size() > 0;
Expand Down Expand Up @@ -170,8 +173,10 @@ public CustomAspect(Map<String, SessionFactory> sessionFactories) {
@Override
protected void configureSession() {
super.configureSession();
getSession().createSQLQuery("insert into user_sessions values ('gr6f9y0', 'jeff_29')")
Transaction transaction = getSession().beginTransaction();
getSession().createNativeQuery("insert into user_sessions values ('gr6f9y0', 'jeff_29')")
.executeUpdate();
transaction.commit();
}
}
}

0 comments on commit 8c37ec6

Please sign in to comment.