Superclass Fields Using #Builder Lombok - spring-boot

WHow to fetch the Superclass fields in the builder?
Parent:
package com.goomo.sso.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
#AllArgsConstructor
#NoArgsConstructor
#Data
public class BaseResponseModel implements Serializable {
private static final long serialVersionUID = 1L;
private String status;
private StatusMessage statusMessage;
}
Child:
package com.goomo.sso.dto;
import java.io.Serializable;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
#Data
#EqualsAndHashCode(callSuper=false)
#ToString
public class UserRequest extends BaseResponseModel implements Serializable {
private static final long serialVersionUID = 1L;
private String clientName;
private String role;
private String groupName;
private String userName;
#Builder
public UserRequest(String status, StatusMessage statusMessage, String clientName, String role, String groupName,
String userName) {
super(status,statusMessage);
this.clientName = clientName;
this.role=role;
this.groupName=groupName;
this.userName = userName;
}
}
I couldn't get the fields of the parent class in the builder. Can you please suggest me the correct way of achieving it?

Related

Handle Date data type with spring data ldap

I am using spring-data-ldap to find all the users who are created or modified in a certain date range. My UserRepository
package com.test.service.ldap.com;
import org.springframework.data.ldap.repository.LdapRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface UserRepository extends LdapRepository<User> {}
My User class
package com.test.service.ldap.com;
import lombok.Data;
import lombok.ToString;
import org.springframework.data.domain.Persistable;
import org.springframework.ldap.odm.annotations.Attribute;
import org.springframework.ldap.odm.annotations.Entry;
import org.springframework.ldap.odm.annotations.Id;
import org.springframework.ldap.odm.annotations.Transient;
import javax.naming.Name;
import java.util.Date;
#Entry(base = "ou=people,dc=example,dc=com",objectClasses = { "top","person","organizationalPerson","inetOrgPerson" })
#Data
#ToString
public final class User implements Persistable<Name> {
private #Id Name id;
private #Attribute(name = "cn") String firstname;
private #Attribute(name = "sn") String lastname;
private #Attribute(name = "mobile") String mobile;
private #Attribute(name = "createTimestamp") Date createdtime;
private #Attribute(name = "modifyTimestamp") Date modifiedtime;
#Transient
private Boolean isNew = false;
#Override
public boolean isNew() {
return isNew;
}
}
I get the below exception when I try to findAll()
org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '20221229074251.850Z'
at org.springframework.core.convert.support.ObjectToObjectConverter.convert(ObjectToObjectConverter.java:117)
at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:41)
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:192)
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:175)
at org.springframework.ldap.odm.typeconversion.impl.ConversionServiceConverterManager.convert(ConversionServiceConverterManager.java:67)
...
...
I want to know
How to handle Date data type in spring-data-ldap
Can I use something like findAllOrderByModifiedTimeDesc or use Between two dates

JPA Query is not throwing any errors and I keep getting only null

I'm fairly new to Spring and JPA.
I have a User entity:
package com.cooksys.twitter.entities;
import java.sql.Timestamp;
import java.util.List;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import lombok.NoArgsConstructor;
#Table(name = "user_table")
#Entity
#NoArgsConstructor
#Getter
#Setter
public class User {
#Id
#GeneratedValue
private Long id;
#Embedded
private Credentials credentials;
#Embedded
private Profile profile;
#CreationTimestamp
private Timestamp joined;
#JsonIgnore
#OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
private List<Tweet> tweets;
#ManyToMany(mappedBy = "likes")
private List<Tweet> likedTweets;
#ManyToMany(mappedBy = "following")
private List<User> followers;
#ManyToMany
private List<User> following;
#ManyToMany(mappedBy = "userMentioned")
private List<Tweet> mentions;
#Column
private boolean deleted;
}
I have a Credentials entity:
package com.cooksys.twitter.entities;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import lombok.Data;
import lombok.NoArgsConstructor;
#NoArgsConstructor
#Data
#Embeddable
public class Credentials {
#Column(unique=true)
private String username;
private String password;
}
I have my UserRepository:
package com.cooksys.twitter.repositories;
import com.cooksys.twitter.entities.Credentials;
import com.cooksys.twitter.entities.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByCredentials(Credentials credentials);
User findByCredentials_Username(String username);
User findByCredentialsUsernameAndPassword(String username, String password);
}
I'm getting passed in a TweetRequestDto that has Credentials inside with a username and password. Now when I pass those credentials into my repository query :
User user = userRepository.findByCredentials_Username(tweetRequestDto.getCredentials().getUsername());
or any variation of the queries in my repository, I only get returned null. I know the credentials are correct and in the database.
Any help is appreciated, thank you.

Nested property not found in a Spring Data query method declaration

I'm trying to use findBy... in my repository to get a Savingaccount object passing a nested attribute(name) as a parameter. Currently I'm using:
Mono<SavingAccount> findByOwnerName(String name);
but I'm getting this error: No property name found for type Owner! Traversed path: SavingAccount.owner.
My repository:
package com...SavingAccMS.Repository;
import com.everis.SavingAccMS.Model.Owner;
import com.everis.SavingAccMS.Model.SavingAccount;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import reactor.core.publisher.Mono;
public interface SavingAccountRepo extends ReactiveMongoRepository<SavingAccount, String>
{
Mono<SavingAccount> findByNumber(String number);
//This one is the problem
Mono<SavingAccount> findByOwnerName(String name);
Mono<SavingAccount> findByOwner(Owner owner);
}
My Entity:
package com...SavingAccMS.Model;
import java.security.acl.Owner;
import javax.validation.constraints.NotBlank;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.Data;
#Data
#Document(collection = "SavingAccs")
public class SavingAccount
{
#Id
private String id;
#NotBlank
private String number;
#NotBlank
private Owner owner;
#NotBlank
private String currency;
#NotBlank
private double balance = 0.00;
#NotBlank
private String status;
}
package com...SavingAccMS.Model;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.Data;
#Data
#Document(collection = "Owners")
public class Owner
{
public String dni;
public String name; //findBy this attribute is required.
}
According to your imports, the Owner in your SavingAccount refers to java.security.acl.Owner, not the one you defined yourself in om...SavingAccMS.Model.Owner. The former does not carry a name attribute.
I'm not certain but I don't think you can find the owner name in hibernate like that.
I would try the following!
#Query("SELECT * FROM SavingAccount where owner.name = :name")
Mono<SavingAccount> findByOwnerName(#Param("name") String name);

Hibernate Envers unable to extend DefaultRevisionEntity

I'm trying to extend the DefaultRevisionEntity in order to add a username to the current revision entity. However, instead of simply adding the new field, it's creating a completely new table. Code is as follows
AuditRevisionEntity
package com.example.demo;
import org.hibernate.envers.DefaultRevisionEntity;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
#Entity
#EntityListeners(AuditRevisionListener.class)
public class AuditRevisionEntity extends DefaultRevisionEntity {
private String user;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}
AuditRevisionListener
package com.example.demo;
import org.hibernate.envers.RevisionListener;
public class AuditRevisionListener implements RevisionListener {
#Override
public void newRevision(Object revisionEntity) {
AuditRevisionEntity rev = (AuditRevisionEntity) revisionEntity;
rev.setUser("MYUSER");
}
}
User
package com.example.demo;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
#Entity
#Audited
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#NotBlank()
#Size(min = 1, max = 100)
#Column(name = "email")
private String email;
#NotBlank()
#Size(min = 1, max = 100)
#Column(name = "password")
private String password;
}
Resulting in
Your custom RevisionEntity is missing the required #RevisionEntity annotation.
package com.example.demo;
import org.hibernate.envers.DefaultRevisionEntity;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
#Entity
#RevisionEntity( AuditRevisionListener.class )
public class AuditRevisionEntity extends DefaultRevisionEntity {
private String user;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}
More info and a code sample can be found in the Envers documentation
I believe I have fixed this with adding the table to the custom entity pointing to the main revinfo table
#Entity
#RevisionEntity( AuditRevisionListener.class )
#Table(name = "revinfo")
public class AuditRevisionEntity extends DefaultRevisionEntity {
private String user;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}

Hibernate Query to join two table using Jparepository

Hi all i have a small issue with joining two tables using jparepository using #query but i am getting error. please help me with this.
UserAddress.java
package com.surya_spring.example.Model;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
#Entity
#Table(name = "user_address")
//#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class UserAddress implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3570928575182329616L;
/*#ManyToMany(cascade = {CascadeType.ALL},fetch=FetchType.EAGER,mappedBy = "userAddress",targetEntity=UserData.class)*/
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="user_id")
private UserData userdata;
#Id
#Column(name = "addr_id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long addrid;
#Column(name = "dr_no")
#NotNull
private String doorNo;
#Column(name = "strt_name")
#NotNull
private String streetName;
#Column(name = "city")
#NotNull
private String city;
#Column(name = "country")
#NotNull
private String country;
/*#OneToOne(cascade=CascadeType.ALL)
#Column(name="user_id")*/
public UserData getUserdata() {
return userdata;
}
public void setUserdata(UserData userdata) {
this.userdata = userdata;
}
public Long getAddrid() {
return addrid;
}
public void setAddrid(Long addrid) {
this.addrid = addrid;
}
public String getDoorNo() {
return doorNo;
}
public void setDoorNo(String doorNo) {
this.doorNo = doorNo;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
UserData.java
package com.surya_spring.example.Model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.NonNull;
#Entity
#Table(name = "user_data")
public class UserData implements Serializable{
/**
* Serialization ID
*/
private static final long serialVersionUID = 8133309714576433031L;
/*#ManyToMany(targetEntity=UserAddress.class ,cascade= {CascadeType.ALL },fetch=FetchType.EAGER)
#JoinTable(name="userdata",joinColumns= #JoinColumn(name="userid"),inverseJoinColumns = #JoinColumn(name="userid"))
*/
#Id
#Column(name = "user_id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
#Column(name = "user_name")
#NonNull
private String userName;
#Column(name = "user_email")
#NonNull
private String userEmail;
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;
}
}
Repository:
package com.surya_spring.example.Repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.surya_spring.example.Model.UserData;
public interface UserDataRepository extends JpaRepository<UserData, Long>{
#Query(" FROM UserData where userId= :id")
public List<UserData> findBySearchTerm(#Param("id") Long id);
}
any one let me know the query to join this both the table to get city name from user_address where user_id=? joining user_data table
If you want to get the city for a user you can do:
#Query("SELECT ua.city FROM UserAddress ua WHERE ua.userdata.userId = ?1")
String findCityByUserId(Long userId);
Note that your entity names are used (like in your java classes) and not the table names in database! You do not have to do the join by yourself as you can use the properties of your domain models to access the related data

Resources