Generics in Hierarchical Model Issue - java

I have following hierarchy of classes:
public interface Table<V> {
Map<String, Object> getNamedParams(SearchQuery<V> query);
}
public class TopicTable implements Table<Topic> {
#Override
public Map<String, Object> getNamedParams(TopicSearchQuery query) {
// TODO to be implemented
return null;
}
}
#Data
public abstract class SearchQuery<E> {
private Integer pageSize;
private Integer pageNumber;
}
public class TopicSearchQuery extends SearchQuery<Topic> {
private String orgId;
private Boolean isShared;
private String name;
private String description;
}
My IDE is complaining that the method getNamedParams from interface Table is not properly implemented in class TopicTable. I know it has something to do with inheritance and my usage of generics.
What I am trying to accomplish: tie entity, search query and table together, so that table operates only with proper entities and search queries. I want this to be cohesive and robust. Any idea on how I can achieve it best, so that the design is not cluttered or cumbersome, ideally, with no explicit casting.
Thanks in advance.

This method signature:
getNamedParams(TopicSearchQuery query)
Does not override the method. It would have to be:
getNamedParams(SearchQuery<Topic> query)
You can't change the type of the parameter to be any more specific (because this would violate Liskov substitutability) or less specific (because Java doesn't allow it when overriding) than required by the interface.
If you want to be able to require a more specific parameter type, add another type variable:
public interface Table<V, SQ extends SearchQuery<V>> {
Map<String, Object> getNamedParams(SQ query);
}
Then you can declare your implementing class to use that type:
public class TopicTable implements Table<Topic, TopicSearchQuery> {
#Override
public Map<String, Object> getNamedParams(TopicSearchQuery query)

Related

Remove usage of generic wildcard type

In my project I use classes representing Json Schemas, in particular:
public interface JsonSchema {
String getId();
JsonTypedSchema<? extends FieldValue> getTypedSchema(Map<String, JsonSchema> schemas);
}
#Value
public class ReferenceToAJsonSchema implements JsonSchema {
#JsonProperty("$id")
String id;
#JsonProperty("$ref")
String reference;
#Override
public JsonTypedSchema<? extends FieldValue> getTypedSchema(Map<String, JsonSchema> schemas) {
return schemas.get(reference).getTypedSchema(schemas);
}
}
public interface JsonTypedSchema<T extends FieldValue> extends JsonSchema {
String getType();
#Override
default JsonTypedSchema<? extends FieldValue> getTypedSchema(Map<String, JsonSchema> schemas) {
return this;
}
}
getTypedSchema should give me the "effective" type of the schema by following references recursively (schemas is a map of all schemas indexed by their $id).
Sonar gives me a Remove usage of generic wildcard type Critical issue, but I fail to see how to fix it...
Do you see any alternative?
P.S. : There are questions close to mine, but mine is more specific, so I was simply wondering if in my case, there were any alternative

Generic use of not yet existing enum in interface or abstract class

I'm about to create multiple search-DTO-Class to build and transfer search query parameters. Which parameters are available is dependent of the database table of an object.
Due to that, it is not possible to have only one Enum for every DTO-class, resulting in each DTO-class having their own Enum of searchable parameters.
The actual collection of search parameters will be an EnumMap (intizialized, but empty). I want to have a getter, put and removeParameter method in each search-DTO-Class.
Those three methods equal in logic in every DTO-Class but their return type differs (Map). So my question is:
Is it possible to declare those three function generic?
I have though about an interface which is to be implemented by any search-DTO-Class. But then I'd need to work with wildcards which does not meet the purpose of individual Enums.
Example code:
public class LocationSearchParametersDTO
{
public enum LOCATION_PARAMETER
{
ID("id");
private String queryParam;
private LOCATION_PARAMETER(String queryParam){ this.queryParam=queryParam; }
public String getQueryParam(){ return queryParam; }
}
private final Map<LOCATION_PARAMETER, String> searchParameters = new EnumMap<>(LOCATION_PARAMETER.class);
public Map<LOCATION_PARAMETER, String> getParameters(){ return Collections.unmodifiableMap(searchParameters); }
public void put(LOCATION_PARAMETER param, String value){ searchParameters.put(param, value); }
public void removeParameter(LOCATION_PARAMETER param){ searchParameters.remove(param); }
}
The tricky thing is that you need enums.
If you would have LOCATION_PARAMETER classes you could have them extend BaseParameter and then return something like
public Map<? extends BaseParameter, String> searchParameters(){}
Your idea of having the enums extend a common interface and have it as a return type would work, so I think you have to go with interface if you need to return enums.
EDIT:
Or you could have it unbounded and return your enums:
public Map<?, String> searchParameters(){}

Is placing all setters of derived class to util class a good design?

I read some codes like this:
public class Base {
protected Map<String, Object> attrMap = new HashMap<>();
public Map<String, Object> getAttrMap() {
return this.attrMap;
}
}
public class DerivedA extends Base{}
public class DerivedB extends Base{}
public class Util {
public void setDerivedAAttrX(Base base, Object object) {
base.getAttrMap().put("DERIVEDA_X", object);
}
public void setDerivedAAttrY(Base base, Object object) {
base.getAttrMap().put("DERIVEDA_Y", object);
}
public void setDerivedBAttrX(Base base, Object object) {
base.getAttrMap().put("DERIVEDB_X", object);
}
public void setDerivedAttrZ(Base base, Object object) {
base.getAttrMap().put("DERIVED_Z", object);
}
}
I asked the implementor of those codes why design like this, here is his answer:
We can't let those setters in Base, because it's set derived attributes.
If we move those setters to corresponding derived class, it's hard to handle setDerivedAttrZ.(Note that it can set attribute Z for both DerivedA and DerivedB)we may have a Base reference and we will set attribute Z. We know it's DerivedA or DerivedB indeed, but don't know it's which one exactly. So we can't cast it to derived class and call derived setters.
Since place these setters in Base or derived class both have some shortcomings, he comes to a Util class to handle those setters.
So my question, is it a good design for that case?
I think it is bad design. The basic of object-oriented programming is to call methods on objects, and not helper functions to which objects and method parameters are passed.
Guess. This reeks of several classes having miscellaneous capabilities, some shared.
And untyped at that.
An improvement would be to use an interface with capability and use that as key.
public class Base {
private Map<Class<?>, Object> attrMap = new HashMap<>();
protected <T> void add(Class<T> clazz, T object);
/** #return null when not available. */
public <T> T lookup(Class<T> clazz) {
Object object = attrMap.get(clazz);
return clazz.cast(object);
}
}
For the lookup one could use Optional<T> instead of a null result.
About the original:
The string constants and aggregation might be too much boiler code, circumstantial coding.

Is it possible to write a generic enum converter for JPA?

I wanted to write a Converter for JPA that stores any enum as UPPERCASE. Some enums we encounter do not follow yet the convention to use only Uppercase letters so until they are refactored I still store the future value.
What I got so far:
package student;
public enum StudentState {
Started,
Mentoring,
Repeating,
STUPID,
GENIUS;
}
I want "Started" to be stored as "STARTED" and so on.
package student;
import jpa.EnumUppercaseConverter;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
#Entity
#Table(name = "STUDENTS")
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "ID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long mId;
#Column(name = "LAST_NAME", length = 35)
private String mLastName;
#Column(name = "FIRST_NAME", nullable = false, length = 35)
private String mFirstName;
#Column(name = "BIRTH_DATE", nullable = false)
#Temporal(TemporalType.DATE)
private Date mBirthDate;
#Column(name = "STUDENT_STATE")
#Enumerated(EnumType.STRING)
#Convert(converter = EnumUppercaseConverter.class)
private StudentState studentState;
}
the converter currently looks like this:
package jpa;
import javax.persistence.AttributeConverter;
import java.util.EnumSet;
public class EnumUppercaseConverter<E extends Enum<E>> implements AttributeConverter<E, String> {
private Class<E> enumClass;
#Override
public String convertToDatabaseColumn(E e) {
return e.name().toUpperCase();
}
#Override
public E convertToEntityAttribute(String s) {
// which enum is it?
for (E en : EnumSet.allOf(enumClass)) {
if (en.name().equalsIgnoreCase(s)) {
return en;
}
}
return null;
}
}
what will not work is that I do not know what enumClass will be at runtime. And I could not figure out a way to pass this information to the converter in the #Converter annotation.
So is there a way to add parameters to the converter or cheat a bit? Or is there another way?
I'm using EclipseLink 2.4.2
Thanks!
Based on #scottb solution I made this, tested against hibernate 4.3: (no hibernate classes, should run on JPA just fine)
Interface enum must implement:
public interface PersistableEnum<T> {
public T getValue();
}
Base abstract converter:
#Converter
public abstract class AbstractEnumConverter<T extends Enum<T> & PersistableEnum<E>, E> implements AttributeConverter<T, E> {
private final Class<T> clazz;
public AbstractEnumConverter(Class<T> clazz) {
this.clazz = clazz;
}
#Override
public E convertToDatabaseColumn(T attribute) {
return attribute != null ? attribute.getValue() : null;
}
#Override
public T convertToEntityAttribute(E dbData) {
T[] enums = clazz.getEnumConstants();
for (T e : enums) {
if (e.getValue().equals(dbData)) {
return e;
}
}
throw new UnsupportedOperationException();
}
}
You must create a converter class for each enum, I find it easier to create static class inside the enum: (jpa/hibernate could just provide the interface for the enum, oh well...)
public enum IndOrientation implements PersistableEnum<String> {
LANDSCAPE("L"), PORTRAIT("P");
private final String value;
#Override
public String getValue() {
return value;
}
private IndOrientation(String value) {
this.value= value;
}
public static class Converter extends AbstractEnumConverter<IndOrientation, String> {
public Converter() {
super(IndOrientation.class);
}
}
}
And mapping example with annotation:
...
#Convert(converter = IndOrientation.Converter.class)
private IndOrientation indOrientation;
...
With some changes you can create a IntegerEnum interface and generify for that.
What you need to do is write a generic base class and then extend that for each enum type you want to persist. Then use the extended type in the #Converter annotation:
public abstract class GenericEnumUppercaseConverter<E extends Enum<E>> implements AttributeConverter<E, String> {
...
}
public FooConverter
extends GenericEnumUppercaseConverter<Foo>
implements AttributeConverter<Foo, String> // See Bug HHH-8854
{
public FooConverter() {
super(Foo.class);
}
}
where Foo is the enum you want to handle.
The alternative would be to define a custom annotation, patch the JPA provider to recognize this annotation. That way, you could examine the field type as you build the mapping information and feed the necessary enum type into a purely generic converter.
Related:
https://hibernate.atlassian.net/browse/HHH-8854
This answer has been modified to take advantage of default interface methods in Java 8.
The number of components of the facility (enumerated below) remains at four, but the amount of required boilerplate is much less. The erstwhile AbstractEnumConverter class has been replaced by an interface named JpaEnumConverter which now extends the JPA AttributeConverter interface. Moreover, each placeholder JPA #Converter class now only requires the implementation of a single abstract method that returns the Class<E> object for the enum (for even less boilerplate).
This solution is similar to others and also makes use of the JPA Converter facility introduced in JPA 2.1. As generic types in Java 8 are not reified, there does not appear to be an easy way to avoid writing a separate placeholder class for each Java enum that you want to be able to convert to/from a database format.
You can however reduce the process of writing an enum converter class to pure boilerplate. The components of this solution are:
Encodable interface; the contract for an enum class that grants access to a String token for each enum constant. This is written only once and is implemented by all enum classes that are to be persisted via JPA. This interface also contains a static factory method for getting back the enum constant for its matching token.
JpaEnumConverter interface; provides the common code for translating tokens to/from enum constants. This is also only written once and is implemented by all the placeholder #Converter classes in the project.
Each Java enum class in the project implements the Encodable interface.
Each JPA placeholder #Converter class implements the JpaEnumConverter interface.
The Encodable interface is simple and contains a static factory method, forToken(), for obtaining enum constants:
public interface Encodable{
String token();
public static <E extends Enum<E> & Encodable> E forToken(Class<E> cls, String tok) {
final String t = tok.trim();
return Stream.of(cls.getEnumConstants())
.filter(e -> e.token().equalsIgnoreCase(t))
.findAny()
.orElseThrow(() -> new IllegalArgumentException("Unknown token '" +
tok + "' for enum " + cls.getName()));
}
}
The JpaEnumConverter interface is a generic interface that is also simple. It extends the JPA 2.1 AttributeConverter interface and implements its methods for translating back and forth between entity and database. These are then inherited by each of the JPA #Converter classes. The only abstract method that each placeholder class must implement, is the one that returns the Class<E> object for the enum.
public interface JpaEnumConverter<E extends Enum<E> & Encodable>
extends AttributeConverter<E, String> {
public abstract Class<E> getEnumClass();
#Override
public default String convertToDatabaseColumn(E attribute) {
return (attribute == null)
? null
: attribute.token();
}
#Override
public default E convertToEntityAttribute(String dbData) {
return (dbData == null)
? null
: Encodeable.forToken(getEnumClass(), dbData);
}
}
An example of a concrete enum class that could now be persisted to a database with the JPA 2.1 Converter facility is shown below (note that it implements Encodable, and that the token for each enum constant is defined as a private field):
public enum GenderCode implements Encodable{
MALE ("M"),
FEMALE ("F"),
OTHER ("O");
final String e_token;
GenderCode(String v) {
this.e_token = v;
}
#Override
public String token() { // the only abstract method of Encodable
return this.e_token;
}
}
The boilerplate for every placeholder JPA 2.1 #Converter class would now look like the code below. Note that every such converter will need to implement JpaEnumConverter and provide the implementation for getEnumClass() ... and that's all! The implementations for the JPA AttributeConverter interface methods are inherited.
#Converter
public class GenderCodeConverter
implements JpaEnumConverter<GenderCode> {
#Override
public Class<GenderCode> getEnumClass() { // sole abstract method
return GenderCode.class;
}
}
These placeholder #Converter classes can be readily nested as static member classes of their associated enum classes.
The above solutions are really fine. My small additions here.
I also added the following to enforce when implementing the interface writing a converter class. When you forget jpa starts using default mechanisms which are really fuzzy solutions (especially when mapping to some number value, which I always do).
The interface class looks like this:
public interface PersistedEnum<E extends Enum<E> & PersistedEnum<E>> {
int getCode();
Class<? extends PersistedEnumConverter<E>> getConverterClass();
}
With the PersistedEnumConverter similar to previous posts. However when the implementing this interface you have to deal with the getConverterClass implementation, which is, besides being an enforcement to provide the specific converter class, completely useless.
Here is an example implementation:
public enum Status implements PersistedEnum<Status> {
...
#javax.persistence.Converter(autoApply = true)
static class Converter extends PersistedEnumConverter<Status> {
public Converter() {
super(Status.class);
}
}
#Override
public Class<? extends PersistedEnumConverter<Status>> getConverterClass() {
return Converter.class;
}
...
}
And what I do in the database is always make a companion table per enum with a row per enum value
create table e_status
(
id int
constraint pk_status primary key,
label varchar(100)
);
insert into e_status
values (0, 'Status1');
insert into e_status
values (1, 'Status2');
insert into e_status
values (5, 'Status3');
and put a fk constraint from wherever the enum type is used. Like this the usage of correct enum values is always guaranteed. I especially put values 0, 1 and 5 here to show how flexible it is, and still solid.
create table using_table
(
...
status int not null
constraint using_table_status_fk references e_status,
...
);
I found a way to do this without using java.lang.Class, default methods or reflection. I did this by using a Function that is passed to the Convertor in the constructor from the enum, using method reference. Also, the Convertos from the enum should be private, no need for them outside.
Interface that Enums should implement in order to be persisted
public interface PersistableEnum<T> {
/** A mapping from an enum value to a type T (usually a String, Integer etc).*/
T getCode();
}
The abstract converter will use a Function in order to cover convertToEntityAttribute transformation
#Converter
public abstract class AbstractEnumConverter<E extends Enum<E> & PersistableEnum<T>, T> implements AttributeConverter<E, T> {
private Function<T, E> fromCodeToEnum;
protected AbstractEnumConverter(Function<T, E> fromCodeToEnum) {
this.fromCodeToEnum = fromCodeToEnum;
}
#Override
public T convertToDatabaseColumn(E persistableEnum) {
return persistableEnum == null ? null : persistableEnum.getCode();
}
#Override
public E convertToEntityAttribute(T code) {
return code == null ? null : fromCodeToEnum.apply(code);
}
}
The enum will implement the interface (I am using lombok for the getter) and create the converted by using a constructor
that receives a Function, I pass the ofCode using method reference. I prefer this instead of working with java.lang.Class or using reflection, I have more freedom in the enums.
#Getter
public enum CarType implements PersistableEnum<String> {
DACIA("dacia"),
FORD("ford"),
BMW("bmw");
public static CarType ofCode(String code) {
return Arrays.stream(values())
.filter(carType -> carType.code.equalsIgnoreCase(code))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Invalid car type code."));
}
private final String code;
CarType(String code) {
this.code = code;
}
#Converter(autoApply = true)
private static class CarTypeConverter extends AbstractEnumConverter<CarType, String> {
protected CarTypeConverter () {
super(CarType::ofCode);
}
}
}
4.In the entity you just have to use the enum type and it will save it's String code.
#Column(name = "CAR_TYPE")
private CarType workflowType;
If you don't mind reflection, this works. Credit to another SO answer inline.
abstract class EnumTypeConverter<EnumType,ValueType> implements AttributeConverter<EnumType, ValueType> {
private EnumType[] values
#Override
ValueType convertToDatabaseColumn(EnumType enumInstance) {
return enumInstance ? enumInstance.getProperty(getValueColumnName()) : null
}
#Override
EnumType convertToEntityAttribute(ValueType dbData) {
if(dbData == null){
return null
}
EnumType[] values = getValues()
EnumType rtn = values.find {
it.getProperty(getValueColumnName()).equals(dbData)
}
if(!rtn) {
throw new IllegalArgumentException("Unknown ${values.first().class.name} value: ${dbData}")
}
rtn
}
private EnumType[] getValues() {
if(values == null){
Class cls = getTypeParameterType(getClass(), EnumTypeConverter.class, 0)
Method m = cls.getMethod("values")
values = m.invoke(null) as EnumType[]
}
values
}
abstract String getValueColumnName()
// https://stackoverflow.com/a/59205754/3307720
private static Class<?> getTypeParameterType(Class<?> subClass, Class<?> superClass, int typeParameterIndex) {
return getTypeVariableType(subClass, superClass.getTypeParameters()[typeParameterIndex])
}
private static Class<?> getTypeVariableType(Class<?> subClass, TypeVariable<?> typeVariable) {
Map<TypeVariable<?>, Type> subMap = new HashMap<>()
Class<?> superClass
while ((superClass = subClass.getSuperclass()) != null) {
Map<TypeVariable<?>, Type> superMap = new HashMap<>()
Type superGeneric = subClass.getGenericSuperclass()
if (superGeneric instanceof ParameterizedType) {
TypeVariable<?>[] typeParams = superClass.getTypeParameters()
Type[] actualTypeArgs = ((ParameterizedType) superGeneric).getActualTypeArguments()
for (int i = 0; i < typeParams.length; i++) {
Type actualType = actualTypeArgs[i]
if (actualType instanceof TypeVariable) {
actualType = subMap.get(actualType)
}
if (typeVariable == typeParams[i]) return (Class<?>) actualType
superMap.put(typeParams[i], actualType)
}
}
subClass = superClass
subMap = superMap
}
return null
}
}
Then in the entity class:
enum Type {
ATYPE("A"), ANOTHER_TYPE("B")
final String name
private Type(String nm) {
name = nm
}
}
...
#Column
Type type
...
#Converter(autoApply = true)
static class TypeConverter extends EnumTypeConverter<Type,String> {
String getValueColumnName(){
"name"
}
}
This is written in groovy, so you'll need some adjustments for Java.

Java/Hibernate using interfaces over the entities

I am using annoted Hibernate, and I'm wondering whether the following is possible.
I have to set up a series of interfaces representing the objects that can be persisted, and an interface for the main database class containing several operations for persisting these objects (... an API for the database).
Below that, I have to implement these interfaces, and persist them with Hibernate.
So I'll have, for example:
public interface Data {
public String getSomeString();
public void setSomeString(String someString);
}
#Entity
public class HbnData implements Data, Serializable {
#Column(name = "some_string")
private String someString;
public String getSomeString() {
return this.someString;
}
public void setSomeString(String someString) {
this.someString = someString;
}
}
Now, this works fine, sort of.
The trouble comes when I want nested entities.
The interface of what I'd want is easy enough:
public interface HasData {
public Data getSomeData();
public void setSomeData(Data someData);
}
But when I implement the class, I can follow the interface, as below, and get an error from Hibernate saying it doesn't know the class "Data".
#Entity
public class HbnHasData implements HasData, Serializable {
#OneToOne(cascade = CascadeType.ALL)
private Data someData;
public Data getSomeData() {
return this.someData;
}
public void setSomeData(Data someData) {
this.someData = someData;
}
}
The simple change would be to change the type from "Data" to "HbnData", but that would obviously break the interface implementation, and thus make the abstraction impossible.
Can anyone explain to me how to implement this in a way that it will work with Hibernate?
Maybe OneToOne.targetEntity?:
#OneToOne(targetEntity = HbnData.class, cascade = CascadeType.ALL)
private Data someData;
The interface that I usually use is Data Access Object, or DAO. Using Java generics, I can write it just once; Hibernate makes it possible to write the implementation just once, too:
package persistence;
import java.io.Serializable;
import java.util.List;
public interface GenericDao<T, K extends Serializable>
{
T find(K id);
List<T> find();
List<T> find(T example);
List<T> find(String queryName, String [] paramNames, Object [] bindValues);
K save(T instance);
void update(T instance);
void delete(T instance);
}

Categories

Resources