I have an entity like below:
#Entity
#Table(name = "orders")
#Data
#Builder
#NoArgsConstructor
#AllArgsConstructor
public class Order {
#Convert(converter = UserInfoJsonConverter.class)
private UserInfo userInfo;
#Convert(converter = IndUserInfoJsonConverter.class)
private IndUserInfo indUserInfo;
#Convert(converter = DuplicateInfoJsonConverter.class)
private DuplicateInfo duplicateInfo;
#Convert(converter = PartnershipJsonConverter.class)
private PartnershipInfo partnerShipInfo;
#Convert(converter = SecretJsonConverter.class)
private SecretInfo secretInfo;
....
And as you see I have 5 fields as JSON string in DB. And also I have 5 JsonConverter implementations like below:
#Slf4j
#Converter(autoApply = true)
public class IndUserInfoJsonConverter implements AttributeConverter<IndUserInfo, String> {
private final ObjectMapper objectMapper = new ObjectMapper();
#Override
public String convertToDatabaseColumn(IndUserInfo attribute) {
try {
objectMapper.registerModule(new JavaTimeModule());
return objectMapper.writeValueAsString(attribute);
} catch (JsonProcessingException ex) {
log.error("Could not write view {} to json", attribute, ex);
throw new InternalServerErrorException("Could not write the object details into string", ex);
}
}
#Override
public IndUserInfo convertToEntityAttribute(String dbData) {
try {
objectMapper.registerModule(new JavaTimeModule());
return dbData == null ? null : objectMapper.readValue(dbData, IndUserInfo.class);
} catch (JsonProcessingException ex) {
log.error("Could not write view {} to json", dbData, ex);
throw new InternalServerErrorException("Could not convert input string into object", ex);
}
}
}
And my question is how can I generalize these implementations? I mean how can I get rid of code repeat? Because the only difference is IndUserInfo in here.
Since converters don't have access to the model type, you can't use this approach in a generic way. You could use a UserType which can inject the model type, but then you could also use the hibernate-types project for this purpose.
As of Hibernate 6, you don't need any of this, as it comes with JSON support out of the box. You just have to annotate the persistent attribute with #JdbcTypeCode(SqlTypes.JSON)
Related
I need to receive a request from a webhook from a third party API.
Post content is an urlenconded in following format:
event=invoice.created&data%5Bid%5D=value1&data%5Bstatus%5D=pending&data%5Baccount_id%5D=value2
The problem is serialize this params data[id] with these square brackets. I'm getting an error in spring boot:
Invalid property 'data[account_id]' of bean class [br.com.bettha.domain.dto.IuguWebhookDto]: Property referenced in indexed property path 'data[account_id]' is neither an array nor a List nor a Map; returned value was [IuguDataDto(id=null, account_id=null, status=null, subscription_id=null)]
My controller:
#PostMapping(value = "/subscription-invoice", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
#ApiOperation(
value="Create a subscription invoice from Iugu's webhook",
response= Invoice.class,
notes="This Operation creates a subscription invoice from Iugu's webhook")
#PreAuthorize("#oauth2.hasScope('read')")
public ResponseEntity<Invoice> createSubscriptionInvoice(IuguWebhookDto iuguWebhookDto) {
try {
Invoice invoice = paymentService.createSubscriptionInvoiceFromIugusWebhook(iuguWebhookDto);
return new ResponseEntity<>(invoice, HttpStatus.CREATED);
} catch (EntityNotFoundException e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage(), e);
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage(), e);
}
}
IuguWebhookDto.java:
#Getter
#Setter
#NoArgsConstructor
#ToString
public class IuguWebhookDto implements Serializable {
private static final long serialVersionUID = -5557936429069206933L;
private String event;
private IuguDataDto data;
IuguDataDto.java:
#Getter
#Setter
#NoArgsConstructor
#ToString
public class IuguDataDto implements Serializable {
private static final long serialVersionUID = -5557936429069206933L;
private String id;
private String account_id;
private String status;
private String subscription_id;
How can I receive these request params as an object in Spring Boot?
I have the same problem using Iugu Webhooks API. To solve, i just stringify the raw data sent by Iugu, remove the unwanted characters, and then parse again the object to get the variables that i want.
var dataReceived = JSON.stringify(req.body).replace('data[id]','id').replace('data[status]','status').replace('data[account_id]','account_id');
var finalData = JSON.parse(dataReceived);
return res.status(200).send(finalData.id);
I'm using spring and hibernate to persist #Entity classes into a mysql database.
For one attribute, I want to persist the object as a String or Json field, rather than creating an additional table and using #OneToOne reference mappings or similar.
Take the following just as an example:
#Entity
public class Customer {
//#JsonObject
private List<Address> address;
}
public class Address {
private String street, number, city, zip, country;
}
Question: how could I tell hibernate to automatically save that address as string/json? And of course, when reading the string/json should be remapped into an Address object.
You can store jsons into mySQL tables:
CREATE TABLE `book` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(200) NOT NULL,
`tags` json DEFAULT NULL,
PRIMARY KEY (`id`)
)
Insert query:
INSERT INTO `book` (`title`, `tags`)
VALUES (
'ECMAScript 2015: A SitePoint Anthology',
'["JavaScript", "ES2015", "JSON"]'
);
In hibernate, you should create class (like "com.test.MyJsonType") that must implement org.hibernate.usertype. UserType interface where the nullSafeGet method should deserialize JSON to java object (using Jackson), the nullSafeSet serialize POJO to JSON and some other auxiliary methods.
For the moment I could solve it with AttributesConverter. Nice that Spring can automatically inject the jackson mapper into it:
#Entity
public class Customer {
#Convert(converter = AddressConverter.class)
#Lob
#Column(columnDefinition = "text")
private List<Address> address;
}
#Converter
public class AddressConverter implements AttributeConverter<List<Address>, String> {
private ObjectMapper objectMapper;
#Autowired //injected by spring
public AddressConverter(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
#Override
public String convertToDatabaseColumn(List<AddressConverter> list) {
try {
if (!CollectionUtils.isEmpty(list))
return objectMapper.writeValueAsString(list);
} catch (final JsonProcessingException e) {
LOGGER.error(e);
}
return null;
}
#Override
public List<Address> convertToEntityAttribute(String json) {
try {
if (StringUtils.isNotBlank(json))
return objectMapper.readValue(json, List.class);
} catch (final IOException e) {
LOGGER.error(e);
}
return null;
}
}
My question is kind of similar to Prevent GSON from serializing JSON string but the solution there uses GSON library and I am restricted to using Jackson (fasterxml).
I have an entity class as follows:
package com.dawson.model;
import com.dawson.model.audit.BaseLongEntity;
import lombok.extern.log4j.Log4j;
import javax.persistence.*;
#Table(name = "queue", schema = "dawson")
#Entity
#Log4j
public class Queue extends BaseLongEntity {
protected String requestType;
protected String body;
protected Queue() {
}
public Queue(String requestType, String body) {
this.requestType = requestType;
this.body = body;
}
#Column(name = "request_type")
public String getRequestType() {
return requestType;
}
public void setRequestType(String requestType) {
this.requestType = requestType;
}
#Column(name = "body")
#Lob
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
I want to populate the body field with the json string representation of a map and then send this as part of the ResponseEntity. Something as follows:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.writer().withDefaultPrettyPrinter();
HashMap<String, String> map = new HashMap<>(5);
map.put("inquiry", "How Can I solve the problem with Jackson double serialization of strings?");
map.put("phone", "+12345677890");
Queue queue = null;
try {
queue = new Queue("General Inquiry", mapper.writeValueAsString(map));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
String test = mapper.writeValueAsString(map)
System.out.println(test);
Expected Output: "{"requestType": "General Inquiry","body": "{"inquiry":"How Can I solve the problem with Jackson double serialization of strings?","phone":"+12345677890"}"}"
Actual Output:"{"requestType": "General Inquiry","body": "{\"inquiry\":\"How Can I solve the problem with Jackson double serialization of strings?\",\"phone\":\"+12345677890\"}"}"
I am using
Jackson Core v2.8.2
I tried playing with
#JsonIgnore
and
#JsonProperty
tags but that doesn't help because my field is already serialized from the map when writing to the Entity.
Add the #JsonRawValue annotation to the body property. This makes Jackson treat the contents of the property as a literal JSON value, that should not be processed.
Be aware that Jackson doesn't do any validation of the field's contents, which makes it dangerously easy to produce invalid JSON.
I am trying to parse a jcelulas object that has a few many to one relationships. I can't seem to parse them correctly. Any help is appreciated.
Model:
#Entity
#Table(name = "jcelulas", catalog = "7jogos")
public class Jcelulas implements java.io.Serializable {
private Integer id;
private Jconcorrentes jconcorrentes;
private Jgrelhas jgrelhas;
private Jcodigos jcodigos;
private Jpremios jpremios;
private boolean checked;
private Date dataChecked;
// getters and setters
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ConcorrentesId")
public Jconcorrentes getJconcorrentes() {
return this.jconcorrentes;
}
public void setJconcorrentes(Jconcorrentes jconcorrentes) {
this.jconcorrentes = jconcorrentes;
}
}
Controller:
#RequestMapping(value = "/jtabuleiros/play/commit",
method = RequestMethod.POST,
headers = {"Content-type=application/json"})
#ResponseBody
public JsonResponse playcelula(#ModelAttribute DataJson celula,#RequestBody String json) {
System.out.println(celula.toString());
System.out.println(json);
ObjectMapper mapper = new ObjectMapper();
try {
// read from file, convert it to user class
Jcelulas user = mapper.readValue(json, Jcelulas.class);
// display to console
System.out.println(user);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new JsonResponse("OK","");
}
Request:
{
"id":1,
"jconcorrentes":1,
"jgrelhas":1,
"jcodigos":1
}
How should I parse jconcorrentes? I tried as an int and got the following error:
org.codehaus.jackson.map.JsonMappingException: Can not instantiate value of type [simple type, class com.setelog.spring.model.Jconcorrentes] from JSON integral number; no single-int-arg constructor/factory method (through reference chain: com.setelog.spring.model.Jcelulas["jconcorrentes"])
Jconcorrentes:
#Entity
#Table(name = "jconcorrentes", catalog = "7jogos")
public class Jconcorrentes implements java.io.Serializable {
private Integer id;
....
private Date dataRegisto;
private Set<Jcelulas> jcelulases = new HashSet<Jcelulas>(0);
}
PS: These models were generated with hibernate from the mysql database
The problem is that jconcorrentes is being serialized as a number, not JSON Object. So Jackson does not know how to construct a Jconcorrentes out of value 1.
We have a big table with a lot of columns. After we moved to MySQL Cluster, the table cannot be created because of:
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 14000. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs
As an example:
#Entity #Table (name = "appconfigs", schema = "myproject")
public class AppConfig implements Serializable
{
#Id #Column (name = "id", nullable = false)
#GeneratedValue (strategy = GenerationType.IDENTITY)
private int id;
#OneToOne #JoinColumn (name = "app_id")
private App app;
#Column(name = "param_a")
private ParamA parama;
#Column(name = "param_b")
private ParamB paramb;
}
It's a table for storing configuration parameters. I was thinking that we can combine some columns into one and store it as JSON object and convert it to some Java object.
For example:
#Entity #Table (name = "appconfigs", schema = "myproject")
public class AppConfig implements Serializable
{
#Id #Column (name = "id", nullable = false)
#GeneratedValue (strategy = GenerationType.IDENTITY)
private int id;
#OneToOne #JoinColumn (name = "app_id")
private App app;
#Column(name = "params")
//How to specify that this should be mapped to JSON object?
private Params params;
}
Where we have defined:
public class Params implements Serializable
{
private ParamA parama;
private ParamB paramb;
}
By using this we can combine all columns into one and create our table. Or we can split the whole table into several tables. Personally I prefer the first solution.
Anyway my question is how to map the Params column which is text and contains JSON string of a Java object?
You can use a JPA converter to map your Entity to the database.
Just add an annotation similar to this one to your params field:
#Convert(converter = JpaConverterJson.class)
and then create the class in a similar way (this converts a generic Object, you may want to specialize it):
#Converter(autoApply = true)
public class JpaConverterJson implements AttributeConverter<Object, String> {
private final static ObjectMapper objectMapper = new ObjectMapper();
#Override
public String convertToDatabaseColumn(Object meta) {
try {
return objectMapper.writeValueAsString(meta);
} catch (JsonProcessingException ex) {
return null;
// or throw an error
}
}
#Override
public Object convertToEntityAttribute(String dbData) {
try {
return objectMapper.readValue(dbData, Object.class);
} catch (IOException ex) {
// logger.error("Unexpected IOEx decoding json from database: " + dbData);
return null;
}
}
}
That's it: you can use this class to serialize any object to json in the table.
The JPA AttributeConverter is way too limited to map JSON object types, especially if you want to save them as JSON binary.
You don’t have to create a custom Hibernate Type to get JSON support, All you need to do is use the Hibernate Types OSS project.
For instance, if you're using Hibernate 5.2 or newer versions, then you need to add the following dependency in your Maven pom.xml configuration file:
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<version>${hibernate-types.version}</version>
</dependency>
Now, you need to declare the new type either at the entity attribute level or, even better, at the class level in a base class using #MappedSuperclass:
#TypeDef(name = "json", typeClass = JsonType.class)
And the entity mapping will look like this:
#Type(type = "json")
#Column(columnDefinition = "json")
private Location location;
If you're using Hibernate 5.2 or later, then the JSON type is registered automatically by MySQL57Dialect.
Otherwise, you need to register it yourself:
public class MySQLJsonDialect extends MySQL55Dialect {
public MySQLJsonDialect() {
super();
this.registerColumnType(Types.JAVA_OBJECT, "json");
}
}
And, set the hibernate.dialect Hibernate property to use the fully-qualified class name of the MySQLJsonDialect class you have just created.
If you need to map json type property to json format when responding to the client (e.g. rest API response), add #JsonRawValue as the following:
#Column(name = "params", columnDefinition = "json")
#JsonRawValue
private String params;
This might not do the DTO mapping for server-side use, but the client will get the property properly formatted as json.
It is simple
#Column(name = "json_input", columnDefinition = "json")
private String field;
and in mysql database your column 'json_input' json type
There is a workaround for those don't want write too much code.
Frontend -> Encode your JSON Object to string base64 in POST method, decode it to json in GET method
In POST Method
data.components = btoa(JSON.stringify(data.components));
In GET
data.components = JSON.parse(atob(data.components))
Backend -> In your JPA code, change the column to String or BLOB, no need Convert.
#Column(name = "components", columnDefinition = "json")
private String components;
In this newer version of spring boot and MySQL below code is enough
#Column( columnDefinition = "json" )
private String string;
I was facing quotes issue so I commented below line in my project
#spring.jpa.properties.hibernate.globally_quoted_identifiers=true
I had a similar problem, and solved it by using #Externalizer annotation and Jackson to serialize/deserialize data (#Externalizer is OpenJPA-specific annotation, so you have to check with your JPA implementation similar possibility).
#Persistent
#Column(name = "params")
#Externalizer("toJSON")
private Params params;
Params class implementation:
public class Params {
private static final ObjectMapper mapper = new ObjectMapper();
private Map<String, Object> map;
public Params () {
this.map = new HashMap<String, Object>();
}
public Params (Params another) {
this.map = new HashMap<String, Object>();
this.map.putAll(anotherHolder.map);
}
public Params(String string) {
try {
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
};
if (string == null) {
this.map = new HashMap<String, Object>();
} else {
this.map = mapper.readValue(string, typeRef);
}
} catch (IOException e) {
throw new PersistenceException(e);
}
}
public String toJSON() throws PersistenceException {
try {
return mapper.writeValueAsString(this.map);
} catch (IOException e) {
throw new PersistenceException(e);
}
}
public boolean containsKey(String key) {
return this.map.containsKey(key);
}
// Hash map methods
public Object get(String key) {
return this.map.get(key);
}
public Object put(String key, Object value) {
return this.map.put(key, value);
}
public void remove(String key) {
this.map.remove(key);
}
public Object size() {
return map.size();
}
}
HTH
If you are using JPA version 2.1 or higher you can go with this case.
Link Persist Json Object
public class HashMapConverter implements AttributeConverter<Map<String, Object>, String> {
#Override
public String convertToDatabaseColumn(Map<String, Object> customerInfo) {
String customerInfoJson = null;
try {
customerInfoJson = objectMapper.writeValueAsString(customerInfo);
} catch (final JsonProcessingException e) {
logger.error("JSON writing error", e);
}
return customerInfoJson;
}
#Override
public Map<String, Object> convertToEntityAttribute(String customerInfoJSON) {
Map<String, Object> customerInfo = null;
try {
customerInfo = objectMapper.readValue(customerInfoJSON,
new TypeReference<HashMap<String, Object>>() {});
} catch (final IOException e) {
logger.error("JSON reading error", e);
}
return customerInfo;
}
}
A standard JSON object would represent those attributes as a HashMap:
#Convert(converter = HashMapConverter.class)
private Map<String, Object> entityAttributes;