I see some class like this in the code I am looking, and wonder how
it was generated, they looks like generated by a plugin or by eclipse itself, I know eclipse can create a POJO file for your through wizard, but how do I get results like below?
public class Item implements Serializable{
private static final long serialVersionUID = 3868244754652312286L;
#JsonProperty("name")
private String name;
#JsonProperty("quantity")
private String quantity;
#JsonProperty("price")
private String price;
#JsonProperty("tax")
private String tax;
#JsonProperty("sku")
private String sku;
#JsonProperty("originalPrice")
private String originalPrice;
#JsonIgnore
private HashMap<String, Object> additionalProperties = new HashMap<>();
#JsonProperty("name")
public String getName() {
return name;
}
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
Related
I have a table entity_detail that has following structure:
id detail_id center_code Comments updated_by updated_on created_on created_by
1 121 0 Test user 2020-04-22 2020-04-21 user
2 122 1 Test user1 2020-04-22 2020-04-22 user
I have an entity corresponding to this table:
#Entity(name = "entity_detail")
public class EntityDetail extends AuditableEntity {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long detailId;
private Boolean centerCode;
private String comments;
}
There is another class AuditableEntity which manages the Audit.
#EntityListeners(AuditingEntityListener.class)
#Data
public class AuditableEntity implements Serializable {
private static final long serialVersionUID = 1L;
#CreatedBy
private String createdBy;
#CreatedDate
private Date createdOn;
#LastModifiedBy
private String updatedBy;
#LastModifiedDate
private Date updatedOn;
}
Now when I try to fetch the data from the table by using id:
savedEntityDetailTest = entityDetailRepository.findById(id);
All the attributes which are coming from AuditableEntity get returned null.
which means when I try to fetch updatedBy field using the following line it returns null.
savedEntityDetailTest.getUpdatedBy();
while when I try to get comments in the same way I get value which is saved in the table.
savedEntityDetailTest.getcomments();
Please suggest me a fixture or workaround.
Add EnableJpaAuditing annotation above your main class.
#SpringBootApplication
#EnableJpaAuditing
public class H2Database2Application {
public static void main(String[] args) {
SpringApplication.run(H2Database2Application.class, args);
}
}
Add MappedSuperclass annotation to the AuditableEntity class.
#EntityListeners(AuditingEntityListener.class)
#MappedSuperclass
#Data
public class AuditableEntity implements Serializable {
private static final long serialVersionUID = 1L;
#CreatedBy
private String createdBy;
#CreatedDate
private Date createdOn;
#LastModifiedBy
private String updatedBy;
#LastModifiedDate
private Date updatedOn;
}
Add Data annotation to the EntityDetail class.
#Entity(name = "entity_detail")
#Data
public class EntityDetail extends AuditableEntity {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long detailId;
private Boolean centerCode;
private String comments;
}
And Add AuditorAware like below:
#Component
public class SecurityAuditorAware implements AuditorAware<String> {
#Override
public Optional<String> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
return Optional.empty();
}
return Optional.of(((User)authentication.getPrincipal()).getUsername());
}
}
I never understand that how can I use gson.
this is my json string that is fetched from my web service:
{
"GetHistoricalNotificationsInTopicByFilterResult":[
{
"BusinessCode":"10-1-75-16-1-3-0",
"CreationDateTime":"\/Date(1502550561602)\/",
"DeviceId":"8998432005",
"Distributions":null,
"EventData":[ ],
"EventId":"com.test.revisit.events",
"EventTitle":"sending",
"Id":"69dbc367-09ws-bf3c-9re8-5c6b35ecbrtg",
"ProcessId":"4ebb6271-bf3c-9re8-a148-5c6b35ec458",
"SystemId":"com.safarayaneh.revisit",
"SystemTitle":"seeing",
"UserFullName":"jack",
"UserId":"69dbc367-32f3-4e94-bf3c-5c6b35ec3456",
"WKT":"POLYGON ((59.0 36.0, 59.01 36.01, ...))",
"WorkItemId":2354365
},{
....
}
and this is my contract class:
public class SaveNotify implements Parcelable {
private long id;
private String NotificationID;
private String MessageID;
private String CreationDateTime;
private String DeviceId;
private String UserId;
private String UserFullName;
private String SystemId;
private String SystemTitle;
private String EventId;
private String EventTitle;
private String EventData;
private String BusinessCode;
private String ProcessId;
private String WorkItemId;
private String WKT;
private String Distributions;
private String Address;
private String SaveDate;
private String Status;
private String DistributionId;
private String SchedulerCreationDateTime;
private String ExpirationDateTime;
how can I convert json string that i receive from my webservice to pojo class as array list? I want to put this list to my recycler view adapter for showing this info as a list.
What you need to create is an object that gets the field GetHistoricalNotificationsInTopicByFilterResult
public class MainObject implements Parceable{
List<SaveNotify > GetHistoricalNotificationsInTopicByFilterResult;
}
And then, with Gson parce you JSON to The MainObject
Gson gson = new Gson();
MainObject mainObject = gson.fromJson(jsonString, MainObject.class);
I have a table "Project" in my MySQL Databse that contains an ArrayList saved as LONGBLOB (FiledDetailsData).
public class ProjectEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private String projectName;
private String city;
private int nbFields;
private List<FiledDetailsData> FiledDetails;...
I already have alot of data saved and would like to keep it. The problem is that I had to change to structure of FiledDetailsData to add new fields
I've changed it from
#Embeddable
#XmlRootEllement
public class FiledDetailsData implements Serializable`{
private String id;
private String lot;
private String number;
private String street;
private String size;
private String status;
to
#Embeddable
#XmlRootEllement
public class FiledDetailsData implements Serializable`{
private String id;
private String lot;
private String number;
private String street;
private String size;
private String status;
private BigDecimal extraField;
private BigDecimal extraParking;
When I try to run the application with the previous data, I get this error
Could not deserialize object from byte array. Internal Exception: local class incompatible
I can fin it by deleting the LONGBLOB in my DAtaBase and recreating it, but then I lose all my data.
here are my save/edit methods
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
Thank you.
i have a json like
"weatherInfo":{
"city":"北京",
"publishDate":"2014年3月4日",
"week":"星期二",
"tempRange":"8℃~-3℃",
"feelTemp":"10",
"time":"16:05",
"temp":"11",
"WD":"北风",
"WS":"2级",
"SD":"27%",
"weather1":"晴"
}
and my class is
public class WeatherVO implements Serializable{
private static final long serialVersionUID = 2348480036959754071L;
#JsonProperty(value="weatherinfo")
private WeatherInfoVO weatherInfoVO;
#JsonIgnoreProperties(ignoreUnknown=true)
public class WeatherInfoVO{
//城市
#JsonProperty(value="city")
private String city;
//发布日期
private String publishDate;
//发布时间
#JsonProperty(value="time")
private String publishTime;
//星期
private String week;
//温度范围
private String tempRange;
//当前时刻温度
#JsonProperty(value="temp")
private String currentTemp;
//风向
#JsonProperty(value="WD")
private String windDirection;
//风力
#JsonProperty(value="WS")
private String windForce;
//当前时刻湿度
#JsonProperty(value="SD")
private String currentHumidity;
//体感温度
private String feelTemp;
//天气描述
private String weatherDesc;
}
}
i want to convert json to object like:
WeatherVO weatherVO = objectMapper.readValue (jsonString, WeatherVO.class);
and i want to return json use org.springframework.http.converter.json.MappingJacksonHttpMessageConverter class
and the return json is
"weatherInfo":{
"city":"北京",
"publishDate":"2014年3月4日",
"week":"星期二",
"tempRange":"8℃~-3℃",
"feelTemp":"10",
"time":"16:05",
"temp":"11",
"WD":"北风",
"WS":"2级",
"SD":"27%",
"weather1":"晴"
}
but i want to return like
"weatherInfo":{
"city":"北京",
"publishDate":"2014年3月4日",
"week":"星期二",
"tempRange":"8℃~-3℃",
"feelTemp":"10",
"publishTime":"16:05",
"currentTemp":"11",
"windDirection":"北风",
"windForce":"2级",
"currentHumidity":"27%",
"weather":"晴"
}
how can i do that?
thanks for your any suggestion and help.
You can achieve this by marking the getter of the field by #JsonIgnore then create another method that get the field and mark it as #JsonProperty.
My advice is to rename first your fields to avoid confusion. I renamed it like the json you have. So for example.
public class WeatherInfoVO{
private String city;
private String publishDate;
private String week;
private String tempRange;
private String feelTemp;
private String time;
private String temp;
private String WD;
private String WS;
private String SD;
private String weather1;
//getters and setters
}
then in you setters method mark the appropriate #JsonProperty.
#JsonProperty(value="time")
public void setTime(String time) {
this.temp = temp;
}
#JsonProperty(value="temp")
public void setTemp(String temp) {
this.temp = temp;
}
#JsonProperty(value="WD")
public void setWD(String WD) {
this.WD = WD;
}
#JsonProperty(value="WS")
public void setWS(String WS) {
this.WS = WS;
}
#JsonProperty(value="SD")
public void setSD(String SD) {
this.SD = SD;
}
#JsonProperty(value="weather1")
public void setWeather1(String weather1) {
this.weather1 = weather1;
}
//other setters here
and in your getters, make sure to add #JsonIgnore to the fields you want to rename. Since you declare it as #JsonIgnore, you need to create another getter and mark it as #JsonProperty. Do it only to the fields you are going to rename, in your case the fields are time, temp, WD, WS, SD and weather1 only. Here's an example.
#JsonIgnore
public void getTime(){
return time;
}
#JsonProperty(value="publishTime")
public void getPublishTime(){
return time;
}
#JsonIgnore
public void getTemp(){
return temp;
}
#JsonProperty(value="currentTemp")
public void getCurrentTemp(){
return temp;
}
#JsonIgnore
public void getWD(){
return WD;
}
#JsonProperty(value="windDirection")
public void getWindDirection(){
return WD;
}
#JsonIgnore
public void getWS(){
return WS;
}
#JsonProperty(value="windForce")
public void getWindForce(){
return WS;
}
#JsonIgnore
public void getSD(){
return SD;
}
#JsonProperty(value="currentHumidity")
public void getCurrentHumidity(){
return SD;
}
#JsonIgnore
public void getWeather1(){
return weather1;
}
#JsonProperty(value="weather")
public void getWeather(){
return weather1;
}
I have the following pojo
public class Like {
private Long commentId;
private Collection<Long> accountIds;
}
public class Comment {
private Long personId;
private Long pageId;
private Long Id;
private String text;
private Like like;
private LocalDate commentDate;
}
public class Page {
private Long Id;
private Long textId;
private Collection<Comment> comments;
private LocalTime postingDate;
private ViewType type;
private String mediaUrl;
private Collection<Long> openAccountIds;
private Like like;
}
public class Text{
private Long accountId;
private Long Id;
private String name;
private LocalTime firstPostedTime;
private LocalTime lastPostedTime;
private ViewType type;
private Collection<Page> pages;
private Like like;
private String description;
private Collection<Long> openAccountIds;
}
Now i have my text repository as follows:
public interface TextRepository {
Collection<Text> getAllTexts(Long accountId);
Diary getText(Long TextId);
Page getPage(Long pageId);
Comment getComment(Long commentId);
void addPageToText(Long TextId , Page page);
void addCommentToPage(Long pageId , Comment comment);
void updateText(Text text);
void deletePage(Long pageId);
void deleteComment(Long commentId);
void updateLikeToText(Long textIds);
void updateLikeToPage(Long pageId);
void updateLikeToComment(Long commentId);
}
I am a new bie to mysql. I wanted to know how to efficiently create mysql tables so i can retrieve the data in less possible time. Also if my pojo's contains any flaw in structure go ahead to change them or provide suggestions.
Here are some suggestions for the object model to consider (see comments),
// Specifying all the fields as private will not allow
// any other class to use the data!
public class Account
{
public String name;
public String location;
}
public class Text
{
public Collection<Account> likedBy;
public Collection<Account> openAccounts;
public Collection<Page> pages;
public Account postedBy;
public String name; // Not sure what this field represents...
public LocalTime firstPostedTime;
public LocalTime lastPostedTime;
public ViewType type;
public String description;
// Consider using get/set methods for collections,
// so as to expose only minimal required information
// public like(Account account)
// {
// likedBy.add(account);
// }
//
// public dislike(Account account)
// {
// likedBy.remove(account);
// }
}
public class Page
{
public Collection<Comment> comments;
public LocalTime postingDate;
public ViewType type;
public String mediaUrl;
public Collection<Account> openAccounts;
public Collection<Account> likedBy;
// public addComment(Comment comment)
// {
// ...
// Update posting date
// }
//
// public addOpenAccount(Account account)
// {
// ...
// }
}
public class Comment
{
public Account postedBy;
public String text;
public Collection<Account> likedBy;
public LocalDate commentDate;
}
The next step would be to construct an entity-relationship diagram. The primary keys and foreign keys (xxxId) are introduced while normalizing the schema.
The schema could look like this,
Account [id, name, location]
ViewType [id, description]
Comment [id, posted_by_account_id, text, postedDate]
CommentLikes [comment_id, account_id]
Text [id, account_id, name, firstPostedTime, lastPostedTime, type_Id, description]
TextAccounts [text_id, account_id]
TextLikes [text_id, account_id]
TextPages [text_id, page_id]
Page [id, mediaUrl, type_id, postingDate]
PageLikes [page_id, account_id]
PageComments [page_id, comment_id]
PageAccounts [page_id, account_id]