I wonder if it's posible to map Enum VARIABLE and DB. I want to save in database the yellow values (variables of enum)
The enum is used in this class:
#Getter
#Setter
#Table(name = "TIPOS_MOVIMIENTO")
#Entity
public class TipoMovimiento {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column
#Enumerated(EnumType.STRING)
private TipoMov tipo;
public String getTipo() {
return tipo.getTipoNombre();
}
#OneToMany(mappedBy = "tipoMov")
private List<Movimiento> movimientos;
My DTO class:
#Getter
public class TipoMovimientoDto implements DtoEntity {
private TipoMov tipo;
}
I've tried DTO with
#Convert(converter = TipoMovEnumConverter.class)
private TipoMov tipo;
But it doesn't works
Write an AttributeConverter for your enum which will convert your enum data into it's value when store in database.
#Converter(autoApply = true)
public class TipoMovConverter implements AttributeConverter<TipoMov, String> {
#Override
public Integer convertToDatabaseColumn(TipoMov attribute) {
return attribute.getTipoNombre();
}
#Override
public TipoMov convertToEntityAttribute(String value) {
return value == null ? null : TipoMov.findByValue(value);
}
}
Note: Here findByValue is a static method to get enum from value string
0
I got it!!! I never thought this would work.
#Getter
public class TipoMovimientoDto implements DtoEntity {
private TipoMov tipo;
}
I just changed in the code above (Dto):
private TipoMov tipo;
to
private String tipo;
I can't explain how Enum from Entity could have been converted to DTO, using String instead Enum... But that worked!
In case you have the same problem... you need to use Attribute Converter (you can see it in the answer of #User - Upvote don't say Thanks)
Is still necessary to use it in Entity class, above of the enum variable:
#Convert(converter = TipoMovEnumConverter.class)
But not necessary in DTO. Just use String instead Enum in DTO!
Related
I have object of following class:
#Jacksonized
#Builder
#Getter
public class Request {
private String id;
private String city_id;
private String country_id;
private List<String> product_id;
}
This class doesn't have setters, but does have #Builder. I don't want to build a new object. I need to replace following List with another List:
private List<String> product_id;
How can I change condition of the current object?
Should I use ReflectionUtils or is there something else better?
Hi have a strange error.
I have always used the instanceof for see the specific object of an abstract class,
But not run and I don't understand why.
I work for a Java project created with spring boot (1.5.16.RELEASE), is a maven project, with JAVA8 and for my MySql db use querydsl-jpa.
I have an abstractClass for define the user for login.A single user can have only one role, and I have create an AbstractUser class:
#Entity
#Audited
#Data
#DiscriminatorColumn(name="dType", discriminatorType = DiscriminatorType.STRING)
public abstract class AbstractUser extends AbstractDomainAudit{
private static final long serialVersionUID = 7060362023055663647L;
#Column(updatable=false, insertable=false)
private String dType;
#JsonIgnore
private String password;
#JsonIgnore
#Transient
private String newPassword;
#JsonIgnore
#Transient
private String confirmNewPassword;
#Column(nullable=false,unique=true, updatable=false)
private String userName;
private boolean able;
private String name;
#Email
private String email;
}
One of my extender classes is the follow:
#Entity
#Audited
#Data
#DiscriminatorValue(value = "Admin")
public class Administrators extends AbstractUser implements Serializable{
/**
*
*/
private static final long serialVersionUID = 7061564146290031007L;
}
But when in my controller, I try to define the instanceof, not run:
#GetMapping(value="/{id}", params="form")
public String updateForm(#PathVariable(value="id") final Long id, final Model uiModel) {
AbstractUser user = userService.findById(id);
if(user instanceof Administrators) {
Administrators u = (Administrators) user;
uiModel.addAttribute(USER, u);
}else if (user instanceof Commercial){
Commercial ut = (Commercial) user;
uiModel.addAttribute(USER, ut);
}
return UPDATE_PAGE;
}
My condition is ignored.
And I don't understand why. Can anyone help me?
JPA-annotated Classes might be proxied at runtime. Try logging your instance's class
user.getClass().getCanonicalName()
Have a look here for example: JPA, inheritance and instanceof
I have created a BaseEntity class which will have all the common fields of the other entities like created_date, created_by, updated_by etc., I also kept primary key id in there. I am using extends and using the fields from base entity class. The main problem is id field is of type Long in some entities and type of String in some other entities, so how can I manage the id field?
Base Entity Class:
#Getter
#Setter
#MappedSuperclass
public abstract class BaseEntity implements Serializable {
private static final long serialVersionUID = 3779027956207925319L;
protected Long id;
private String createdBy;
private Date createdDate;
private String lastUpdatedBy;
private Date lastUpdatedDate;
private Boolean isActive;
public abstract Long getId();
public abstract void setId(Long id);
#Override
public String toString() {
return String.format(
"BaseEntity [createdBy=%s, createdDate=%s, lastUpdatedBy=%s, lastUpdatedDate=%s, isActive=%s]",
createdBy, createdDate, lastUpdatedBy, lastUpdatedDate, isActive);
}
}
Have a generic base entity, where generic type defines the type of your id column;
#Getter
#Setter
#MappedSuperclass
public abstract class BaseEntity<T> implements Serializable {
protected T id;
// fields, constructors, methods etc
}
When you have an entity where id is of type Long, extend with that type;
#Entity
public class TableWithLongId extends BaseEntity<Long> {
// fields, constructors, methods etc
}
or when you need a String type id;
#Entity
public class TableWithStringId extends BaseEntity<String> {
// fields, constructors, methods etc
}
Modify your getter and setter, use parsing in them so that they get long data and give String data, or vice versa accordingly.
I have the following Entity containing a field of Enum type:
#Entity
#Table(name = "INPUT_DATA")
public class InputDataEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name = "INPUT_DATA_SEQ", allocationSize = 1, sequenceName = "INPUT_DATA_SEQ")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "INPUT_DATA_SEQ")
private Long id;
#Column(name = "FIELD1", nullable = false)
private String field1;
#Column(name = "FIELD2", nullable = false)
#Convert(converter = Type.Converter.class)
private Type field2;
// getters and setters
}
The Enum type looks like:
public enum Type {
ENUM_ITEM_1("item1"),
// more items
ENUM_ITEM_N("itemN");
private String code;
private Type(String code) {
this.code = code;
}
public static Type fromString(String name) {
switch (name) {
case "item1":
return ENUM_ITEM_1;
// more cases
case "itemN":
return ENUM_ITEM_N;
default:
throw new IllegalArgumentException("Wrong value for Type");
}
}
#Override
public String toString() {
return code;
}
#javax.persistence.Converter
public static class Converter implements AttributeConverter<Type, String> {
#Override
public String convertToDatabaseColumn(Type attribute) {
return attribute.toString();
}
#Override
public Type convertToEntityAttribute(String s) {
return Type.fromString(s);
}
}
}
The problem is that hibernate doesn't recognize my Converter when I want to fetch data from the database.
I've also tried:
#Embedded and #Embeddable but with no luck.
#Enumerated(EnumType.STRING) but again with no luck.
My question is:
how to make hibernate to recognize my converter when converting the appropriate field?
Many thanks in advance.
I eventually ended up by implementing a StringValuedEnum interface and its relevant reflector and type class by implementing EnhancedUserType, ParameterizedType as it was described here.
This helped me to properly store into and retrieve from DB data corresponding to user defined enum types, although the questions with converters remains still open. If someday a proper answer will be given, that will be very appreciated.
I'd like to post-process my embeddable class to convert it to another type
#Embeddable
public class Identity {
private Long id;
private String alias;
}
#Embeddable
public class virtualIdentities {
private Long id;
private List<String> aliases; //AttributeConverter applied from a ","-joined string
}
#Entity
public class Parent {
private Identity identity; //Works flawlessly
private VirtualIdentities vIdentities; //Works flawlessly but...
private List<Identity> vIdentities; //<- That is what I'd like to achieve!!
}
So I am looking for a mechanism (standard JPA preferrably) that allows me to map someway a VirtualIdentities embeddable instance as a List<Identity>
If only I could do AttributeConverter<List<Identity>,VirtualIdentities> ...