spring data neo4j ,i can't solve it - spring

I use spring data neo4j,i have user.class.movie.class,rating.class,i create relationship between movie and rating,when i run the programer,i can get the rating(star,comment)but cannot get the movie's title(null)
movie.class
package com.oberon.fm.domain;
#NodeEntity
public class Movie {
#GraphId
Long nodeId;
#Indexed(indexType = IndexType.FULLTEXT, indexName = "id")
String id;
#Indexed(indexType = IndexType.FULLTEXT, indexName = "search", numeric = false)
String title;
String description;
#RelatedTo(type = "DIRECTED", direction = INCOMING)
Person director;
#RelatedTo(type = "ACTS_IN", direction = INCOMING)
Set<Person> actors;
#RelatedToVia(elementClass = Role.class, type = "ACTS_IN", direction = INCOMING)
// Iterable<Role> roles;
Set<Role> roles = new HashSet<>();
#RelatedToVia(elementClass = Rating.class, type = "RATED", direction = INCOMING)
#Fetch
Iterable<Rating> ratings;
// Set<Rating> ratings = new HashSet<>();
private String language;
private String imdbId;
private String tagline;
private Date releaseDate;
private Integer runtime;
private String homepage;
private String trailer;
private String genre;
private String studio;
private Integer version;
private Date lastModified;
private String imageUrl;
public Movie() {
}
public Long getNodeId() {
return nodeId;
}
public void setNodeId(Long nodeId) {
this.nodeId = nodeId;
}
public Movie(String id, String title) {
this.id = id;
this.title = title;
}
public Collection<Person> getActors() {
return actors;
}
public Collection<Role> getRoles() {
return IteratorUtil.asCollection(roles);
}
public int getYear() {
if (releaseDate == null)
return 0;
Calendar cal = Calendar.getInstance();
cal.setTime(releaseDate);
return cal.get(Calendar.YEAR);
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
#Override
public String toString() {
return String.format("%s (%s) [%s]", title, releaseDate, id);
}
public String getDescription() {
return description;
}
public int getStars() {
Iterable<Rating> allRatings = ratings;
if (allRatings == null)
return 0;
int stars = 0, count = 0;
for (Rating rating : allRatings) {
stars += rating.getStars();
count++;
}
return count == 0 ? 0 : stars / count;
}
public Collection<Rating> getRatings() {
Iterable<Rating> allRatings = ratings;
return allRatings == null ? Collections.<Rating> emptyList()
: IteratorUtil.asCollection(allRatings);
}
/*
* public Set<Rating> getRatings() { return ratings; }
*/
public void setRatings(Set<Rating> ratings) {
this.ratings = ratings;
}
/*
* public void addRating(Rating rating) { ratings.add(rating); }
*/
public void setTitle(String title) {
this.title = title;
}
public void setLanguage(String language) {
this.language = language;
}
public void setImdbId(String imdbId) {
this.imdbId = imdbId;
}
public void setTagline(String tagline) {
this.tagline = tagline;
}
public void setDescription(String description) {
this.description = description;
}
public void setReleaseDate(Date releaseDate) {
this.releaseDate = releaseDate;
}
public void setRuntime(Integer runtime) {
this.runtime = runtime;
}
public void setHomepage(String homepage) {
this.homepage = homepage;
}
public void setTrailer(String trailer) {
this.trailer = trailer;
}
public void setGenre(String genre) {
this.genre = genre;
}
public void setStudio(String studio) {
this.studio = studio;
}
public void setVersion(Integer version) {
this.version = version;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getLanguage() {
return language;
}
public String getImdbId() {
return imdbId;
}
public String getTagline() {
return tagline;
}
public Date getReleaseDate() {
return releaseDate;
}
public Integer getRuntime() {
return runtime;
}
public String getHomepage() {
return homepage;
}
public String getTrailer() {
return trailer;
}
public String getGenre() {
return genre;
}
public String getStudio() {
return studio;
}
public Integer getVersion() {
return version;
}
public Date getLastModified() {
return lastModified;
}
public String getImageUrl() {
return imageUrl;
}
public String getYoutubeId() {
String trailerUrl = trailer;
if (trailerUrl == null || !trailerUrl.contains("youtu"))
return null;
String[] parts = trailerUrl.split("[=/]");
int numberOfParts = parts.length;
return numberOfParts > 0 ? parts[numberOfParts - 1] : null;
}
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Movie movie = (Movie) o;
if (nodeId == null)
return super.equals(o);
return nodeId.equals(movie.nodeId);
}
#Override
public int hashCode() {
return nodeId != null ? nodeId.hashCode() : super.hashCode();
}
public Person getDirector() {
return director;
}
}
user.class
package com.oberon.fm.domain;
#NodeEntity
public class User {
#GraphId
Long nodeId;
public static final String SALT = "cewuiqwzie";
public static final String FRIEND = "FRIEND";
public static final String RATED = "RATED";
#Indexed(indexType = IndexType.FULLTEXT, indexName = "login")
String login;
#Indexed
String name;
String password;
public void setPassword(String password) {
this.password = password;
}
String info;
private Roles[] roles;
public User() {
}
public User(String login, String name, String password, Roles... roles) {
this.login = login;
this.name = name;
this.password = encode(password);
this.roles = roles;
}
private String encode(String password) {
return new Md5PasswordEncoder().encodePassword(password, SALT);
}
#RelatedToVia(type = RATED)
#Fetch
Iterable<Rating> ratings;
// Set<Rating> ratings = new HashSet<>();
#RelatedTo(type = RATED)
Set<Movie> favorites;
public Set<Movie> getFavorites() {
return favorites;
}
public void setFavorites(Set<Movie> favorites) {
this.favorites = favorites;
}
#RelatedTo(type = FRIEND, direction = Direction.BOTH)
#Fetch
Set<User> friends;
public void addFriend(User friend) {
this.friends.add(friend);
}
public Rating rate(Neo4jOperations template, Movie movie, int stars,
String comment) {
final Rating rating = template.createRelationshipBetween(this, movie,
Rating.class, RATED, false).rate(stars, comment);
return template.save(rating);
}
/*
* public Rating rate(Movie movie, int stars, String comment) { if (ratings
* == null) { ratings = new HashSet<>(); }
*
* Rating rating = new Rating(this, movie, stars, comment);
* ratings.add(rating); movie.addRating(rating); return rating; }
*/
public Collection<Rating> getRatings() {
return IteratorUtil.asCollection(ratings);
}
/*
* public Set<Rating> getRatings() { return ratings; }
*/
#Override
public String toString() {
return String.format("%s (%s)", name, login);
}
public String getName() {
return name;
}
public Set<User> getFriends() {
return friends;
}
public Roles[] getRole() {
return roles;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public void updatePassword(String old, String newPass1, String newPass2) {
if (!password.equals(encode(old)))
throw new IllegalArgumentException("Existing Password invalid");
if (!newPass1.equals(newPass2))
throw new IllegalArgumentException("New Passwords don't match");
this.password = encode(newPass1);
}
public void setName(String name) {
this.name = name;
}
public boolean isFriend(User other) {
return other != null && getFriends().contains(other);
}
public enum Roles implements GrantedAuthority {
ROLE_USER, ROLE_ADMIN;
#Override
public String getAuthority() {
return name();
}
}
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
User user = (User) o;
if (nodeId == null)
return super.equals(o);
return nodeId.equals(user.nodeId);
}
public Long getId() {
return nodeId;
}
#Override
public int hashCode() {
return nodeId != null ? nodeId.hashCode() : super.hashCode();
}
}
rating.class
package com.oberon.fm.domain;
#RelationshipEntity
public class Rating {
private static final int MAX_STARS = 5;
private static final int MIN_STARS = 0;
#GraphId
Long id;
#StartNode
User user;
#EndNode
Movie movie;
int stars;
String comment;
public User getUser() {
return user;
}
public Movie getMovie() {
return movie;
}
public int getStars() {
return stars;
}
public void setStars(int stars) {
this.stars = stars;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Rating rate(int stars, String comment) {
if (stars >= MIN_STARS && stars <= MAX_STARS)
this.stars = stars;
if (comment != null && !comment.isEmpty())
this.comment = comment;
return this;
}
public Rating() {
}
public void setUser(User user) {
this.user = user;
}
public void setMovie(Movie movie) {
this.movie = movie;
}
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Rating rating = (Rating) o;
if (id == null)
return super.equals(o);
return id.equals(rating.id);
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : super.hashCode();
}
}
controller
#RequestMapping(value = "/user", method = RequestMethod.GET)
public String profile(Model model, HttpServletRequest request) {
// User user=populator.getUserFromSession();
HttpSession session = request.getSession(false);
User user = (User) session.getAttribute("user");
model.addAttribute("user", user);
if (user != null) {
List<MovieRecommendation> mr = movieRepository.getRecommendations(user.getLogin());
MovieRecommendation movie = new MovieRecommendation();
Movie m = new Movie();
m.setTitle("AA");
movie.setMovie(m);
mr.add(movie);
model.addAttribute("recommendations", mr);
}
return "user/index";
}![enter image description here][4]

It only loads the movie's id by default, if you don't specify #Fetch on the movie field. But I'd rather recommend to use template.fetch(rating.movie) to load it only when you need it.

Related

Foregine key is not updating in spring boot Jpa

Basically, I am trying to establish a relationship between my two tables using spring boots.
And the relationship which I had used was the #onetoone and #onetomany relationship.
But after building the relationship and creating the table in MySQL whenever I run the program my foreign key is not updating.
The relationship is one user can have many contacts. I have tried unidirectional as well as bidirectional mapping but it is not working.
I want in contact table there will be a separate column for the foreign key. Based on that key I will show all contacts for that particular user.
This is my contact entity...
package com.example.jpa.contactEntities;
#Entity
#Table(name = "Contact")
public class ContactEntities {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long c_id;
private String c_name;
private String second_c_name;
private String c_work;
private String c_emali;
private String c_phone;
private String c_image;
#Column(length = 5000)
private String c_description;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "contact_id")
private UserEntities userEntities;
public ContactEntities() {
super();
}
public ContactEntities(long c_id, String c_name, String second_c_name, String c_work, String c_emali,
String c_phone, String c_image, String c_description, UserEntities userEntities) {
super();
this.c_id = c_id;
this.c_name = c_name;
this.second_c_name = second_c_name;
this.c_work = c_work;
this.c_emali = c_emali;
this.c_phone = c_phone;
this.c_image = c_image;
this.c_description = c_description;
this.userEntities = userEntities;
}
public long getC_id() {
return c_id;
}
public void setC_id(int c_id) {
this.c_id = c_id;
}
public String getC_name() {
return c_name;
}
public void setC_name(String c_name) {
this.c_name = c_name;
}
public String getSecond_c_name() {
return second_c_name;
}
public void setSecond_c_name(String second_c_name) {
this.second_c_name = second_c_name;
}
public String getC_work() {
return c_work;
}
public void setC_work(String c_work) {
this.c_work = c_work;
}
public String getC_emali() {
return c_emali;
}
public void setC_emali(String c_emali) {
this.c_emali = c_emali;
}
public String getC_phone() {
return c_phone;
}
public void setC_phone(String c_phone) {
this.c_phone = c_phone;
}
public String getC_image() {
return c_image;
}
public void setC_image(String c_image) {
this.c_image = c_image;
}
public String getC_description() {
return c_description;
}
public void setC_description(String c_description) {
this.c_description = c_description;
}
public UserEntities getUserEntities() {
return userEntities;
}
public void setUserEntities(UserEntities userEntities) {
this.userEntities = userEntities;
}
#Override
public String toString() {
return "ContactEntities [c_id=" + c_id + ", c_name=" + c_name + ", second_c_name=" + second_c_name + ", c_work="
+ c_work + ", c_emali=" + c_emali + ", c_phone=" + c_phone + ", c_image=" + c_image + ", c_description="
+ c_description + ", userEntities=" + userEntities + "]";
}
}
this is my user entity...
package com.example.jpa.userEntities;
#Entity
#Table(name = "UserEntities")
public class UserEntities {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long userId;
#NotBlank
#Size(min = 2, max = 20)
private String userName;
#NotBlank
#Column(unique = true)
#Email(regexp = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$")
private String userEmail;
#NotNull(message = "password should not be blank")
private String userPass;
private boolean enable;
private String role;
#Column(length = 500)
private String userAbout;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "userEntities", orphanRemoval = true)
private List<ContactEntities> contactList = new ArrayList<>();
public UserEntities() {
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getUserPass() {
return userPass;
}
public void setUserPass(String userPass) {
this.userPass = userPass;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public String getRoll() {
return role;
}
public void setRoll(String role) {
this.role = role;
}
public String getUserAbout() {
return userAbout;
}
public void setUserAbout(String userAbout) {
this.userAbout = userAbout;
}
public List<ContactEntities> getContactList() {
return contactList;
}
public void setContactList(List<ContactEntities> contactList) {
this.contactList = contactList;
}
#Override
public String toString() {
return "UserEntities [userId=" + userId + ", userName=" + userName + ", userEmail=" + userEmail + ", userPass="
+ userPass + ", enable=" + enable + ", role=" + role + ", userAbout=" + userAbout + ", contactList="
+ contactList + "]";
}
}
Repository of Contact
package com.example.jpa.repo;
import java.util.List;
import com.example.jpa.contactEntities.ContactEntities;
public interface ContactRepo extends JpaRepository<ContactEntities, Integer> {
#Query("from ContactEntities as c where c.userEntities.userId=:u_Id")
public List<ContactEntities> findContactsByUser(#Param("u_Id") long l);
}
Repository of User
package com.example.jpa.repo;
import com.example.jpa.userEntities.UserEntities;
#EnableJpaRepositories
public interface UserRepository extends JpaRepository<UserEntities, Integer> {
#Query("select u from UserEntities u where u.userEmail=:userEmail")
public UserEntities getUserByUserName(#Param("userEmail") String userEmail);
}
User controller
package com.example.jpa.controller;
#Controller
#RequestMapping("/user")
public class UserController {
#Autowired
private UserRepository userRepository;
#Autowired
private ContactRepo contactRepo;
#ModelAttribute
public void addCommonData(Model model, Principal principal) {
String username = principal.getName();
System.out.println("UserName:-" + username);
UserEntities userEntities = this.userRepository.getUserByUserName(username);
System.out.println("User:- " + userEntities);
model.addAttribute("userEntities", userEntities);
}
//dash board home
#RequestMapping("/index")
public String dashboard(Model model, Principal principal) {
return "normal/user_dashboard";
}
// open add form handler
#GetMapping("/add-contact")
public String openAddContactForm(Model model) {
model.addAttribute("title", "Add contact");
model.addAttribute("contactEntitie", new ContactEntities());
return "normal/add_contact";
}
// processing and contact form
#PostMapping("/upload")
public String processContact(#ModelAttribute ContactEntities contactEntitie,
#RequestParam("userImage") MultipartFile multipartFile, Principal principal, Model model,
HttpSession session) {
try {
model.addAttribute("contactEntitie", new ContactEntities());
String name = principal.getName();
UserEntities userEntities = userRepository.getUserByUserName(name);
userEntities.getContactList().add(contactEntitie);
// processing and uploading file....
if (multipartFile.isEmpty()) {
System.out.println("File is empty");
} else {
// upload the the file and update
contactEntitie.setC_image(multipartFile.getOriginalFilename());
File saveFile = new ClassPathResource("static/img").getFile();
// bring the folder path...
Path path = Paths
.get(saveFile.getAbsolutePath() + File.separator + multipartFile.getOriginalFilename());
Files.copy(multipartFile.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Image is uploaded");
}
userRepository.save(userEntities);
System.out.println("Datas are :" + contactEntitie);
// message success
session.setAttribute("message", new Messages("Your Contact is added !!! Add more...", "success"));
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
// error message
session.setAttribute("message", new Messages("Something went wrong !!! Try Again", "danger"));
}
return "normal/add_contact";
}
// show Contact handler
#GetMapping("/show-contacts")
public String showContact(Model model, Principal principal) {
model.addAttribute("title", "Show Contacts");
String userName = principal.getName();
UserEntities userEntities = userRepository.getUserByUserName(userName);
List<ContactEntities> contactList = contactRepo.findContactsByUser(userEntities.getUserId());
model.addAttribute("contactList", contactList);
return "normal/show_contacts";
}
}
All configuration class
User Details configuration
package com.example.jpa.Myconfiguration;
public class UserDetailsServiceImple implements UserDetailsService {
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// fetching data from DB
UserEntities userEntities = userRepository.getUserByUserName(username);
if (userEntities == null) {
throw new UsernameNotFoundException("Could not found user !!!");
}
CustomUserDetails customUserDetails = new CustomUserDetails(userEntities);
return customUserDetails;
}
}
package com.example.jpa.Myconfiguration;
public class CustomUserDetails implements UserDetails {
private UserEntities userEntities;
public CustomUserDetails(UserEntities userEntities) {
super();
this.userEntities = userEntities;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(userEntities.getRoll());
return List.of(simpleGrantedAuthority);
}
#Override
public String getPassword() {
return userEntities.getUserPass();
}
#Override
public String getUsername() {
return userEntities.getUserEmail();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
Application property:-
#Database configuration
spring.datasource.url=jdbc:mysql://localhost:3306/smartcontact
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.NonRegisteringDriver
spring.jpa.properties.hibernate.dilact=org.hibernate.dialect.Mysql8Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=2KB
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

Error Spring React REST Controller Using Custom Class Response (WebFlux)

I'm trying to build a Spring WebFlux project and realize the follow business logic:
1 - Call an external REST Api using WebClient and parse the Json results using the Models below. It is working OK
2 - To show the Mono results Mono<DeviceList> devices, I'm using the ResponseApi class and returning it, but it is NOT working
I'm getting the follow error:
Response status 406 with reason "Could not find acceptable representation"
Thanks
# Json Result
{
"data": [
{
"id": "5bc3c0efe833d93f401bafa8",
"name": "XXXXX",
"group": "5b8fd1fa0499f54cfa7febb8",
"description": "Geolocalizacao gps",
"payloadType": "None",
"contract": "5bc08be5e833d93f40e1f936",
"keepAlive": 0
}
]
}
# Controller
public class DeviceController{
...
...
#RequestMapping(value = V1 + BASE_URL + "/devices/types", method = GET, produces = APPLICATION_JSON)
public Mono<ServerResponse> getDeviceTypes(){
Mono<DeviceList> devices = deviceService.findDeviceTypes();
ResponseApi r = new ResponseApi();
r.setMessage("Test");
r.setCode("200");
r.setStatus(200);
r.setData(devices);
return ok().body(Mono.just(r), ResponseApi.class);
}
}
# Repository
public Mono<DeviceList> findDeviceTypes() {
return webClient.get()
.uri(DEVICE_TYPES_URL)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(DeviceList.class);
}
# Model
public class DeviceList{
#JsonProperty("data")
private List<Device> data;
public List<Device> getData() {
return data;
}
public void setData(List<Device> data) {
this.data = data;
}
}
public class Device{
#JsonProperty("id")
private String id;
#JsonProperty("name")
private String name;
#JsonProperty("group")
private String group;
#JsonProperty("description")
private String description;
#JsonProperty("keepAlive")
private Integer keepAlive;
#JsonProperty("payloadType")
private String payloadType;
#JsonProperty("contract")
private String contract;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getKeepAlive() {
return keepAlive;
}
public void setKeepAlive(Integer keepAlive) {
this.keepAlive = keepAlive;
}
public String getPayloadType() {
return payloadType;
}
public void setPayloadType(String payloadType) {
this.payloadType = payloadType;
}
public String getContract() {
return contract;
}
public void setContract(String contract) {
this.contract = contract;
}
}
#JsonRootName("data")
public class ResponseApi{
#JsonProperty("status")
private Integer status;
#JsonProperty("code")
private String code;
#JsonProperty("message")
private String message;
#JsonProperty("data")
private Object data;
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
You can get devices, then in non blocking way, map them to the ResponseApi like that:
#RequestMapping(value = V1 + BASE_URL + "/devices/types", method = GET, produces = APPLICATION_JSON)
public Mono<ServerResponse> getDeviceTypes(){
return deviceService.findDeviceTypes()
.flatMap(devices -> {
ResponseApi r = new ResponseApi();
r.setMessage("Test");
r.setCode("200");
r.setStatus(200);
r.setData(devices);
return ok().body(Mono.just(r), ResponseApi.class);
});
}

Spring mongo repository sort descending by a certain property

I want to sort Descending by lastChange property, the List of items from mongo.
RequestRepository interface:
public interface RequestRepository extends MongoRepository<Request, String> {
List<Request> findByUser(String id);
}
Request.java:
#Document(collection = "Requests")
public class Request {
#Id
private String id;
private String user;
private String username;
private String requestTitle;
private String requestMessage;
private boolean read;
private Date lastChange;
private Date requestDate;
private boolean isActiveRequest;
private boolean isPremiumRequest; //paid request
public Request() {}
public Request(
String user,
String requestTitle,
String requestMessage,
boolean read,
Date lastChange,
Date requestDate,
boolean isActiveRequest) {
this.user = user;
this.requestTitle = requestTitle;
this.requestMessage = requestMessage;
this.read = read;
this.lastChange = lastChange;
this.requestDate = requestDate;
this.isActiveRequest = isActiveRequest;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getRequestTitle() {
return requestTitle;
}
public void setRequestTitle(String requestTitle) {
this.requestTitle = requestTitle;
}
public String getRequestMessage() {
return requestMessage;
}
public void setRequestMessage(String requestMessage) {
this.requestMessage = requestMessage;
}
public boolean isRead() {
return read;
}
public void setRead(boolean read) {
this.read = read;
}
public Date getLastChange() {
return lastChange;
}
public void setLastChange(Date lastChange) {
this.lastChange = lastChange;
}
public Date getRequestDate() {
return requestDate;
}
public void setRequestDate(Date requestDate) {
this.requestDate = requestDate;
}
public boolean isActiveRequest() {
return isActiveRequest;
}
public void setActiveRequest(boolean activeRequest) {
isActiveRequest = activeRequest;
}
public boolean isPremiumRequest() {
return isPremiumRequest;
}
public void setPremiumRequest(boolean premiumRequest) {
isPremiumRequest = premiumRequest;
}
}
In my code I have the following list:
List<Request> = RequestRepository.findByUser(userObj.getId());
I want to have the data from RequestRepository.findByUser(userObj.getId()); sorted DESCENDING by the property lastChange.
I have searched on StackOverflow, and found the following method to sort:
List<Request> findAllByOrderByUpdatedAtDesc();
but this does not work if I search by User.
What is the solution to search by User id and to sort by lastChange?
Thank you!
This should do it.
List<Request> findByUserOrderByLastChangeDesc(String user);
Update your question with proper details.

sort the list of objects for a record based on two dates(create date and update date)

In the below example I have a department with many cases. I need to get the latest case from the department where the sort order is based on udpatedTime (if udpatedTime is null have to consider createDate) and have to return the first item in the list that is the most recent one (either created or updated). For the newly created case, the updatetime would be null until a case is updated.
public class Case{
Long id;
String number;
String status;
LocalDateTime createDate;
String createdBy;
LocalDateTime udpatedTime;
String updatedBy;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public LocalDateTime getCreateDate() {
return createDate;
}
public void setCreateDate(LocalDateTime createDate) {
this.createDate = createDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public LocalDateTime getUdpatedTime() {
return udpatedTime;
}
public void setUdpatedTime(LocalDateTime udpatedTime) {
this.udpatedTime = udpatedTime;
}
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
}
public class Department {
String id;
List<Case> allCases;
Case latestCase;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<Case> getAllCases() {
return allCases;
}
public void setAllCases(List<Case> allCases) {
this.allCases = allCases;
}
public Case getLatestCase() {
if (getAllCases().isEmpty()) {
return null;
}
getAllCases().sort(new Comparator<Case>() {
#Override
public int compare(Case o1, Case o2) {
if (o1.getUdpatedTime() != null) {
o1.getUdpatedTime().isAfter(o2.getUdpatedTime());
} else if (o2.getUdpatedTime() != null) {
o1.getUdpatedTime().isAfter(o2.getUdpatedTime());
}
return 0;
}
});
return null;
}
}
You do not need to sort the list to get the most recent entry. Just use max:
import static java.util.Comparator.comparing;
getAllCases().stream()
.max(comparing(
c -> c.getUpdatedTime() == null ? c.getCreatedTime() : c.getUpdatedTime()
));
In java 9, you can replace the key extractor with c -> Objects.requireNonNullElse(c.getUpdatedTime(), c.getCreatedTime())
or c -> Objects.requireNonNullElseGet(c.getUpdatedTime(), c::getCreatedTime) (but that's probably overkill)

Spring merge - java.sql.SQLException: Invalid column index

I have a table that has 2 columns that create the primary key:
#Entity
#Table(name="DW.DW$SF$MONTHLY")
public class DWMonthly implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId DWMonthlyPK monthlyPK;
#Id
#Column(name="AID", insertable=false, updatable=false)
#IndexColumn(name="DW$SF$MONTHLY_PK")
private Long id;
#Column(name="CHNG_STATUS")
private BigDecimal chngStatus;
#Column(name="NAR")
private BigDecimal nar;
#Column(name="SF_AMID")
private String sfAmid;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="N_DATE", insertable=false, updatable=false)
#IndexColumn(name="DW$SF$MONTHLY_PK")
private Date nDate;
public DWMonthly() {}
public DWMonthly(Long id, String sfAmid, Date nDate) {
this.id = id;
this.sfAmid = sfAmid;
this.nDate = nDate;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public BigDecimal getChngStatus() {
return this.chngStatus;
}
public void setChngStatus(BigDecimal chngStatus) {
this.chngStatus = chngStatus;
}
public BigDecimal getNar() {
return this.nar;
}
public void setNar(BigDecimal nar) {
this.nar = nar;
}
public String getSfAmid() {
return this.sfAmid;
}
public void setSfAmid(String sfAmid) {
this.sfAmid = sfAmid;
}
public Date getNDate() {
return nDate;
}
public void setNarDate(Date nDate) {
this.nDate = nDate;
}
}
Embeddable table:
#Embeddable
public class DWMonthlyPK implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name="AID")
private long aid;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="N_DATE")
private java.util.Date nDate;
public DWMonthlyPK() {
}
public long getAid() {
return this.aid;
}
public void setAid(long aid) {
this.aid = aid;
}
public java.util.Date getNDate() {
return this.narDate;
}
public void setNDate(java.util.Date nDate) {
this.nDate = nDate;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof DWMonthlyPK)) {
return false;
}
DWMonthlyPK castOther = (DWMonthlyPK)other;
return
(this.aid == castOther.aid)
&& this.nDate.equals(castOther.nDate);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + ((int) (this.aid ^ (this.aid >>> 32)));
hash = hash * prime + this.nDate.hashCode();
return hash;
}
}
Find the record and update:
#Repository(value="MonthlyNarDaoRepository")
#Import({JpaConfigurationImpl.class})
#Transactional(value="dwTransactionManager",readOnly = true, propagation=Propagation.REQUIRES_NEW)
public class MonthlyNarDaoImpl implements MonthlyNarDao {
#Override
#Transactional(value="dwTransactionManager")
public void findAndUpdateMonhtlyByAccountId(Map<DWAccount, UpsertResult> accountsLoadedResult) {
for (DWAccount dwAccount : accountsLoadedResult.keySet()){
try {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<DWMonthlyNar> criteriaQuery = criteriaBuilder.createQuery(DWMonthlyNar.class);
Root<DWMonthlyNar> root = criteriaQuery.from(DWMonthlyNar.class);
Predicate p = criteriaBuilder.conjunction();
p = criteriaBuilder.and(criteriaBuilder.equal(root.get("id"), dwAccount.getId()), criteriaBuilder.notEqual(root.get("nar").as(BigDecimal.class), new BigDecimal(0.0)), criteriaBuilder.isNull(root.get("sfAmid")));
criteriaQuery.select(root);
criteriaQuery.where(p);
for (DWMonthlyNar dwMonthlyNar : this.entityManager.createQuery(criteriaQuery).getResultList()){
if (dwMonthlyNar.getSfAmid()==null || !dwMonthlyNar.getSfAmid().equals(accountsLoadedResult.get(dwAccount).getId())){
dwMonthlyNar.setSfAmid(accountsLoadedResult.get(dwAccount).getId());
this.entityManager.merge(dwMonthlyNar);
}
}
} catch (Exception e) {
logger.error("MonthlyNarDaoImpl.findAndUpdateMonhtlyNarByAccountId(): " + e.getMessage());
}
}
}
}
Error:
Hibernate: update DW.DW$SF$MONTHLY set CHNG_STATUS=?, NAR=?,
SF_AMID=? where AID=? and NAR_DATE=? 16:04:58.864 [main] DEBUG
o.h.e.jdbc.spi.SqlExceptionHelper - Invalid column index [n/a]
java.sql.SQLException: Invalid column index

Resources