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.
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'm having trouble with a many to many relation with JPA.
My code looks as follows:
The Sensor class:
#Entity
#Table(name = "sensor")
#Data
#NoArgsConstructor
#AllArgsConstructor
public class Sensor {
#Id
private long chipId;
#OneToMany(mappedBy = "sensor")
#JsonBackReference
private Set<Link> userLinks;
private String firmwareVersion;
private long creationTimestamp;
private String notes;
private long lastMeasurementTimestamp;
private long lastEditTimestamp;
private double gpsLatitude;
private double gpsLongitude;
private double gpsAltitude;
private String country;
private String city;
private boolean indoor;
private boolean published;
}
The user class:
#Entity
#Table(name = "user")
#Data
#NoArgsConstructor
#AllArgsConstructor
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#JsonManagedReference
private int id;
private String firstName;
private String lastName;
private String email;
private String password;
#OneToMany(mappedBy = "user")
private Set<Link> sensorLinks;
private int role;
private int status;
private long creationTimestamp;
private long lastEditTimestamp;
}
And the Link class (relation class):
#Entity
#Table(name = "link")
#Data
#AllArgsConstructor
#NoArgsConstructor
public class Link {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne
#JoinColumn(name = "user_id")
#MapsId("user_id")
private User user;
#ManyToOne
#JoinColumn(name = "sensor_id")
#MapsId("sensor_id")
private Sensor sensor;
private boolean owner;
private String name;
private int color;
private long creationTimestamp;
}
The controller:
...
#RequestMapping(method = RequestMethod.GET, path = "/user/{email}", produces = MediaType.APPLICATION_JSON_VALUE)
#ApiOperation(value = "Returns details for one specific user")
public User getUserByEmail(#PathVariable("email") String email) {
return userRepository.findByEmail(email).orElse(null);
}
...
The UserRepository:
public interface UserRepository extends JpaRepository<User, Integer> {
Optional<User> findByEmail(String email);
#Modifying
#Query("UPDATE User u SET u.firstName = ?2, u.lastName = ?3, u.password = ?4, u.role = ?5, u.status = ?6 WHERE u.id = ?1")
Integer updateUser(int id, String firstName, String lastName, String password, int role, int status);
}
I want to achieve, that the user endpoint shows all linked sensors with that particular user.
What I get is only an error message:
JSON mapping problem:
com.chillibits.particulatematterapi.model.db.main.User["sensorLinks"];
nested exception is
com.fasterxml.jackson.databind.JsonMappingException: Infinite
recursion (StackOverflowError) (through reference chain:
com.chillibits.particulatematterapi.model.db.main.User["sensorLinks"])
How can I fix this issue?
Thanks in advance
Marc
------------------------------------ Edit -----------------------------------
According to Abinash Ghosh's answer, I added following DTOs:
UserDto:
#Data
#NoArgsConstructor
#AllArgsConstructor
public class UserDto {
private int id;
private String firstName;
private String lastName;
private Set<LinkDto> sensorLinks;
private int role;
private int status;
private long creationTimestamp;
private long lastEditTimestamp;
}
LinkDto:
#Data
#NoArgsConstructor
#AllArgsConstructor
public class LinkDto {
private Integer id;
private SensorDto sensor;
private boolean owner;
private String name;
private int color;
private long creationTimestamp;
}
And the mapper (I realized it a bit different, but it should be the same):
public UserDto getUserByEmail(#PathVariable("email") String email) {
User user = userRepository.findByEmail(email).orElse(null);
return convertToDto(user);
}
private UserDto convertToDto(User user) {
return mapper.map(user, UserDto.class);
}
This leads to following Exception:
2020-04-13 14:22:24.383 WARN 8176 --- [nio-8080-exec-2] o.h.e.loading.internal.LoadContexts : HHH000100: Fail-safe cleanup (collections) : org.hibernate.engine.loading.internal.CollectionLoadContext#68ab57c7<rs=HikariProxyResultSet#2017009664 wrapping Result set representing update count of -1>
1) Error mapping com.chillibits.particulatematterapi.model.db.main.User to com.chillibits.particulatematterapi.model.io.UserDto
1 error] with root cause
java.lang.StackOverflowError: null
at com.mysql.cj.NativeSession.execSQL(NativeSession.java:1109) ~[mysql-connector-java-8.0.19.jar:8.0.19]
...
It's working!
This post helped: https://stackoverflow.com/a/57111004/6296634
Seems that you should not use Lombok #Data in such cases.
When User serialized for the response, all getter methods of User's fields are called.
So, User relational field sensorLinks's getter are also called to set value. This happened recursively. That's cause of infinite recursion.
It's better to not use Entity as a response. Create a DTO class for User then map User entity value into DTO then send response. Don't use any Enity class again into DTO then it will result same problem
For dynamically map one model to another you can use ModleMapper
public class UserDTO {
//Fields you want to show in response & don't use enity class
private Set<LinkDTO> sensorLinks;
}
public class LinkDTO{
//Fields you want to show in response &don't use enity class
}
public User getUserByEmail(#PathVariable("email") String email) {
User user = userRepository.findByEmail(email).orElse(null);
UserDTO userDto = merge(user,UserDTO.class)
return userDto;
}
public static <T> void merge(T source, T target) {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
modelMapper.map(source, target);
}
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;
}
I am building a simple get rest call from MySQL database, the problem is that it returns an empty object.
The call itself is takes in an email (I know this is not the best approach), here is my code:
Entity:
#Entity
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id")
private int id;
private String email;
private String password;
private String firstName;
private String userName;
private String lastName;
private boolean active;
#Temporal(TemporalType.DATE)
private Date createDate;
#Temporal(TemporalType.DATE)
private Date updateDate;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "user_role", joinColumns = #JoinColumn(name = "user_id"), inverseJoinColumns = #JoinColumn(name = "role_id"))
private Collection<Role> roles;
// constructor
// get and setter
}
Repository:
public interface UserRepository extends JpaRepository<User, Long> {
// User findById (Integer Id);
#Query("SELECT u.id FROM User u where u.id = :id")
User findById(#Param("id") Integer id);
User findByEmail (String email);
}
Service:
#Service("userService")
public class UserService {
private String status, message;
private final HashMap map = new HashMap();
#Autowired
private UserRepository userRepository;
// #Autowired
// private RoleRepository roleRepository;
public User findByUserEmail (String email) {
return userRepository.findByEmail(email);
}
}
Controller:
#RestController("userControllerService")
#RequestMapping("/user/account")
public class UserController {
#Autowired
private UserService userService;
#GetMapping("/test-get/{email}")
public User jj(#PathVariable("email") String email){
return userService.findByUserEmail(email);
}
}
And my database happens to have the following data:
And here is the response I get after hitting the URL
I have no clue why my response is empty!
You cannot have the #in the URI path. Encode it with %40.
Reference: Can I use an at symbol (#) inside URLs?
Also, right way is to use as a query param as that's more of a good identifier and allows # as it parses as string
#GetMapping("/test-get")
public User jj(#RequestParam("email") String email){
return userService.findByUserEmail(email);
}
Either ways, hit as encoded url as /test-get/email=a#b.com ? or /test-get/a%40b.com for your previous code.
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]