Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ignore missing entities when lazy loading is enabled with new Feature.WRITE_MISSING_ENTITIES_AS_NULL #126

Merged
merged 1 commit into from
Jan 25, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,14 @@ public enum Feature {
*
* @since 2.8.2
*/
REPLACE_PERSISTENT_COLLECTIONS(false)
REPLACE_PERSISTENT_COLLECTIONS(false),

/**
* Using {@link #FORCE_LAZY_LOADING} may result in
* `javax.persistence.EntityNotFoundException`. This flag configures Jackson to
* ignore the error and serialize a `null`.
*/
WRITE_MISSING_ENTITIES_AS_NULL(false)
;

final boolean _defaultState;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import java.lang.reflect.Method;
import java.util.HashMap;

import javax.persistence.EntityNotFoundException;

import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JavaType;
Expand Down Expand Up @@ -43,6 +45,7 @@ public class HibernateProxySerializer

protected final boolean _forceLazyLoading;
protected final boolean _serializeIdentifier;
protected final boolean _nullMissingEntities;
protected final Mapping _mapping;

/**
Expand All @@ -59,29 +62,34 @@ public class HibernateProxySerializer

public HibernateProxySerializer(boolean forceLazyLoading)
{
this(forceLazyLoading, false, null, null);
this(forceLazyLoading, false, false, null, null);
}

public HibernateProxySerializer(boolean forceLazyLoading, boolean serializeIdentifier) {
this(forceLazyLoading, serializeIdentifier, null, null);
this(forceLazyLoading, serializeIdentifier, false, null, null);
}

public HibernateProxySerializer(boolean forceLazyLoading, boolean serializeIdentifier, Mapping mapping) {
this(forceLazyLoading, serializeIdentifier, mapping, null);
this(forceLazyLoading, serializeIdentifier, false, mapping, null);
}

public HibernateProxySerializer(boolean forceLazyLoading, boolean serializeIdentifier, boolean nullMissingEntities, Mapping mapping) {
this(forceLazyLoading, serializeIdentifier, nullMissingEntities, mapping, null);
}

public HibernateProxySerializer(boolean forceLazyLoading, boolean serializeIdentifier, Mapping mapping,
public HibernateProxySerializer(boolean forceLazyLoading, boolean serializeIdentifier, boolean nullMissingEntities, Mapping mapping,
BeanProperty property) {
_forceLazyLoading = forceLazyLoading;
_serializeIdentifier = serializeIdentifier;
_nullMissingEntities = nullMissingEntities;
_mapping = mapping;
_dynamicSerializers = PropertySerializerMap.emptyForProperties();
_property = property;
}

@Override
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
return new HibernateProxySerializer(this._forceLazyLoading, _serializeIdentifier,
return new HibernateProxySerializer(this._forceLazyLoading, _serializeIdentifier, _nullMissingEntities,
_mapping, property);
}

Expand Down Expand Up @@ -199,7 +207,15 @@ protected Object findProxied(HibernateProxy proxy)
}
return null;
}
return init.getImplementation();
try {
return init.getImplementation();
} catch (EntityNotFoundException e) {
if (_nullMissingEntities) {
return null;
} else {
throw e;
}
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ public class HibernateSerializers extends Serializers.Base
{
protected final boolean _forceLoading;
protected final boolean _serializeIdentifiers;
protected final boolean _nullMissingEntities;
protected final Mapping _mapping;

public HibernateSerializers(int features) {
Expand All @@ -23,6 +24,7 @@ public HibernateSerializers(Mapping mapping, int features)
{
_forceLoading = Feature.FORCE_LAZY_LOADING.enabledIn(features);
_serializeIdentifiers = Feature.SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS.enabledIn(features);
_nullMissingEntities = Feature.WRITE_MISSING_ENTITIES_AS_NULL.enabledIn(features);
_mapping = mapping;
}

Expand All @@ -32,7 +34,7 @@ public JsonSerializer<?> findSerializer(SerializationConfig config,
{
Class<?> raw = type.getRawClass();
if (HibernateProxy.class.isAssignableFrom(raw)) {
return new HibernateProxySerializer(_forceLoading, _serializeIdentifiers, _mapping);
return new HibernateProxySerializer(_forceLoading, _serializeIdentifiers, _nullMissingEntities, _mapping);
}
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,23 @@ protected BaseTest() { }

protected ObjectMapper mapperWithModule(boolean forceLazyLoading)
{
return new ObjectMapper().registerModule(hibernateModule(forceLazyLoading));
return new ObjectMapper().registerModule(hibernateModule(forceLazyLoading, false));
}

protected Hibernate4Module hibernateModule(boolean forceLazyLoading)
protected ObjectMapper mapperWithModule(boolean forceLazyLoading, boolean nullMissingEntities)
{
return new ObjectMapper().registerModule(hibernateModule(forceLazyLoading, nullMissingEntities));
}

protected Hibernate4Module hibernateModule(boolean forceLazyLoading) {
return hibernateModule(forceLazyLoading, false);
}

protected Hibernate4Module hibernateModule(boolean forceLazyLoading, boolean nullMissingEntities)
{
Hibernate4Module mod = new Hibernate4Module();
mod.configure(Hibernate4Module.Feature.FORCE_LAZY_LOADING, forceLazyLoading);
mod.configure(Hibernate4Module.Feature.WRITE_MISSING_ENTITIES_AS_NULL, nullMissingEntities);
return mod;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package com.fasterxml.jackson.datatype.hibernate4;

import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.hibernate.Hibernate;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate4.data.Customer;

// [Issue#125]
public class MissingEntitiesAsNullTest extends BaseTest {
public void testMissingProductWhenMissing() throws Exception {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistenceUnit");

try {
EntityManager em = emf.createEntityManager();

// false -> no forcing of lazy loading
ObjectMapper mapper = mapperWithModule(true);

Customer customer = em.find(Customer.class, 103);
assertFalse(Hibernate.isInitialized(customer.getPayments()));
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(customer);
assertNull(customer.getMissingProductCode());
assertNotNull(json);

Map<?, ?> stuff = mapper.readValue(json, Map.class);

assertNull(stuff.get("missingProductCode"));
assertNull(stuff.get("missingProduct"));

} finally {
emf.close();
}
}

public void testProductWithValidForeignKey() throws Exception {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistenceUnit");

try {
EntityManager em = emf.createEntityManager();

// false -> no forcing of lazy loading
ObjectMapper mapper = mapperWithModule(true);

Customer customer = em.find(Customer.class, 500);
assertFalse(Hibernate.isInitialized(customer.getPayments()));
assertNotNull(customer.getMissingProductCode());
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(customer);
assertNotNull(json);

Map<?, ?> stuff = mapper.readValue(json, Map.class);

assertNotNull(stuff.get("missingProductCode"));
assertNotNull(stuff.get("missingProduct"));

} finally {
emf.close();
}
}

// caused by javax.persistence.EntityNotFoundException: Unable to find
// com.fasterxml.jackson.datatype.hibernate4.data.Product with id X10_1678
public void testExceptionWithInvalidForeignKey() throws Exception {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistenceUnit");

try {
EntityManager em = emf.createEntityManager();

// false -> no forcing of lazy loading
ObjectMapper mapper = mapperWithModule(true);

Customer customer = em.find(Customer.class, 501);
assertFalse(Hibernate.isInitialized(customer.getPayments()));

// javax.persistence.EntityNotFoundException thrown here
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(customer);
// JUnit 3.8
fail("Expected EntityNotFoundException exception");

} catch (JsonMappingException e) {
assertEquals("Unable to find com.fasterxml.jackson.datatype.hibernate4.data.Product with id X10_1678", e.getCause().getMessage());
} finally {
emf.close();
}
}

public void testWriteAsNullWithInvalidForeignKey() throws Exception {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistenceUnit");

try {
EntityManager em = emf.createEntityManager();

// false -> no forcing of lazy loading
ObjectMapper mapper = mapperWithModule(true, true);

Customer customer = em.find(Customer.class, 501);
assertFalse(Hibernate.isInitialized(customer.getPayments()));
// javax.persistence.EntityNotFoundException thrown here
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(customer);
assertNotNull(json);

Map<?, ?> stuff = mapper.readValue(json, Map.class);

assertNotNull(stuff.get("missingProductCode"));
assertNull(stuff.get("missingProduct"));

} finally {
emf.close();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ public class Customer implements java.io.Serializable
private String postalCode;
private String country;
private Double creditLimit;
private String missingProductCode;
private Product missingProduct;
private Set<Payment> payments = new HashSet<Payment>();
private Set<Order> orders = new HashSet<Order>();

Expand Down Expand Up @@ -195,4 +197,24 @@ public Set<Payment> getPayments() {
public void setPayments(Set<Payment> payments) {
this.payments = payments;
}

@Column(name="missingProductCode")
public String getMissingProductCode() {
return missingProductCode;
}

public void setMissingProductCode(String missingProductCode) {
this.missingProductCode = missingProductCode;
}

@ManyToOne(cascade = {}, fetch = FetchType.LAZY, optional = true)
@JoinColumn(name = "missingProductCode", nullable = true, insertable = false, updatable = false)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public Product getMissingProduct() {
return missingProduct;
}

public void setMissingProduct(Product missingProduct) {
this.missingProduct = missingProduct;
}
}
4 changes: 4 additions & 0 deletions hibernate4/src/test/resources/classicmodels.sql
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ CREATE TABLE `classicmodels`.`Customer` (
`country` varchar(50) NOT NULL,
`salesRepEmployeeNumber` int(11) DEFAULT NULL,
`creditLimit` double DEFAULT NULL,
`missingProductCode` varchar(50) NULL,
PRIMARY KEY (`customerNumber`)
) DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `classicmodels`.`Customer` (`customerNumber`,`customerName`,`contactLastName`,`contactFirstName`,`phone`,`addressLine1`,`addressLine2`,`city`,`state`,`postalCode`,`country`,`salesRepEmployeeNumber`,`creditLimit`) VALUES
Expand Down Expand Up @@ -165,6 +166,9 @@ INSERT INTO `classicmodels`.`Customer` (`customerNumber`,`customerName`,`contact
(489,'Double Decker Gift Stores, Ltd','Hardy','Thomas ','(171) 555-7555','120 Hanover Sq.',NULL,'London',NULL,'WA1 1DP','UK',1501,43300),
(495,'Diecast Collectables','Franco','Valarie','6175552555','6251 Ingle Ln.',NULL,'Boston','MA','51003','USA',1188,85100),
(496,'Kellys Gift Shop','Snowden','Tony','+64 9 5555500','Arenales 1938 3A',NULL,'Auckland ',NULL,'','New Zealand',1612,110000);
INSERT INTO `classicmodels`.`Customer` (`customerNumber`,`customerName`,`contactLastName`,`contactFirstName`,`phone`,`addressLine1`,`addressLine2`,`city`,`state`,`postalCode`,`country`,`salesRepEmployeeNumber`,`creditLimit`, `missingProductCode`) VALUES
(500,'Customer with valid product','Schmitt','Carine ','40.32.2555','54, rue Royale',NULL,'Nantes',NULL,'44000','France',1370,21000, 'S10_1678'),
(501,'Customer with invalid product','Schmitt','Carine ','40.32.2555','54, rue Royale',NULL,'Nantes',NULL,'44000','France',1370,21000, 'X10_1678'),

DROP TABLE IF EXISTS `classicmodels`.`Employee`;
CREATE TABLE `classicmodels`.`Employee` (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,14 @@ public enum Feature {
*
* @since 2.8.2
*/
REPLACE_PERSISTENT_COLLECTIONS(false)
REPLACE_PERSISTENT_COLLECTIONS(false),

/**
* Using {@link #FORCE_LAZY_LOADING} may result in
* `javax.persistence.EntityNotFoundException`. This flag configures Jackson to
* ignore the error and serialize a `null`.
*/
WRITE_MISSING_ENTITIES_AS_NULL(false)
;

final boolean _defaultState;
Expand Down
Loading