how to find objects field [duplicate] - spring

This question already has answers here:
Spring JPA selecting specific columns
(18 answers)
Closed 5 years ago.
I have Location and I want to retrieve all locations in db by company
I can do this in this way List<Location> findByCompanyId(Long companyId);
but How can I retrieve ids of Locations not whole object
List<Long> findByCompanyId(Long companyId);
I want the same thing as in first method but without whole object only ids
public class Location extends BaseEntity {
#Column(name = "`street_first`", nullable = false)
private String streetFirst;
#Column(name = "`street_second`")
private String streetSecond;
#Column(name = "`city`", nullable = false)
private String city;
#Column(name = "`zip`")
private String zip;
#Column(name = "`state`", nullable = false)
private String state;
#Column(name = "`phone`", nullable = false)
private String phone;
#JoinColumn(name = "`company_id`", nullable = false)
private Company company;
}
//getters and setters

#Query("SELECT l.id FROM Location l WHERE l.company.id = :companyId");
List<Long> getLocationIds(#Param("companyId")Long companyId);

Related

Spring specification query for one to many join and sum of field is grater then given value

I am creating filter using joining this three entity seeker_job_application,seeker_profile and seeker_experience. where I want achieve result as below query.
In filter I want to find out seeker_profile whose total_moth of experience should be grater then or equal to given value i.e 20, one seeker_profile has multiple experience so I need to group by profile and sum of their experience and then compare with given value. is it possible to do this using spring specification?
How to check that seeker total month of experience is grater then or equal to given value?
Relation between table is
seeker_job_application 1<-->1 seeker_profile 1<---->* seeker_experience
Want to achieve query like this
select r.sja_id,r.sp_id,r.name,r.company_name,r.total_month from (
select sja.id as sja_id , sp.id as sp_id , sp.`name`,se.company_name,sum(se.total_month) as total_month
from seeker_job_application sja
INNER JOIN seeker_profile sp on sp.id = sja.seeker_id
INNER JOIN seeker_experience se on se.seeker_id = sp.id
where job_id =1 group by sp.id ) as r where r.total_month > 20;
#Entity
#Table(name = "seeker_job_application")
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class SeekerJobApplication implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#NotNull
#Column(name = "seeker_id", nullable = false)
private Long seekerId;
#NotNull
#Column(name = "job_id", nullable = false)
private Long jobId;
#Column(name = "apply_date")
private Instant applyDate;
#Column(name = "profile_viewed")
private Boolean profileViewed;
#Column(name = "on_hold")
private Boolean onHold;
#Column(name = "interview_schedule")
private Boolean interviewSchedule;
#Column(name = "rejected")
private Boolean rejected;
#Column(name = "selected")
private Boolean selected;
#Column(name = "prefered_location_id")
private Long preferedLocationId;
#Column(name = "work_preference")
private String workPreference;
#Column(name = "resume_file_path")
private String resumeFilePath;
#Column(name = "status")
private String status;
#ManyToOne
#JoinColumn(name="seeker_id",referencedColumnName = "id", insertable = false, updatable = false)
private SeekerProfile seekerProfile;
#Data
#Entity
#Table(name = "seeker_profile")
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class SeekerProfile implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "id")
private Long id;
#Column(name = "name", nullable = false)
private String name;
#Column(name = "mobile_number", nullable = false)
private String mobileNumber;
#Column(name = "password")
private String password;
#Column(name = "email", nullable = false)
private String email;
#Column(name = "house_number")
private String houseNumber;
#Column(name = "address_line_1")
private String addressLine1;
#Column(name = "address_line_2")
private String addressLine2;
#Column(name = "city")
private String city;
#Column(name = "postcode")
private String postcode;
#Column(name = "state")
private String state;
#Column(name = "country")
private String country;
#Column(name = "website")
private String website;
#Column(name = "linkedin")
private String linkedin;
#Column(name = "facebook")
private String facebook;
#Column(name = "gender")
private String gender;
#Column(name = "dob")
private String dob;
#Column(name = "resume")
private String resume;
#Column(name = "wfh")
private String wfh;
#Column(name = "profile_completed")
private String profileCompleted;
#OneToOne
#JoinColumn(unique = true)
private Location preferedLocation;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "seeker_skill", joinColumns = { #JoinColumn(name = "seeker_id") }, inverseJoinColumns = { #JoinColumn(name = "skill_id") })
private Set<Skill> skills;
#OneToMany(fetch = FetchType.EAGER)
#JoinColumn(name="seeker_id",referencedColumnName = "id", insertable = false, updatable = false)
private Set<SeekerExperience> seekerExperiences;
#OneToMany
#JoinColumn(name="seeker_id",referencedColumnName = "id", insertable = false, updatable = false)
private Set<SeekerEducation> seekerEducation;
#Entity
#Table(name = "seeker_experience")
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class SeekerExperience implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#NotNull
#Column(name = "seeker_id", nullable = false)
private Long seekerId;
#NotNull
#Column(name = "job_title", nullable = false)
private String jobTitle;
#NotNull
#Column(name = "company_name", nullable = false)
private String companyName;
#NotNull
#Column(name = "start_date", nullable = false)
private String startDate;
#NotNull
#Column(name = "end_date", nullable = false)
private String endDate;
#Column(name = "total_month")
private Integer totalMonth;
#Column(name = "location")
private String location;
#Column(name = "role_description")
private String roleDescription;
Specification<SeekerJobApplication> specification = Specification.where(null);
specification = specification.and((root, query, cb) -> {
Join<SeekerJobApplication, SeekerProfile> seekerProfile=root.join(SeekerJobApplication_.seekerProfile);
Join<SeekerProfile, SeekerExperience> seekerExperience = seekerProfile.join(SeekerProfile_.seekerExperiences);
query.having(cb.greaterThanOrEqualTo(cb.sum(seekerExperience.get(SeekerExperience_.totalMonth)), criteria.getTotalExperience().getEquals()));
query.getRestriction();
});
This will give me result as below query
select sja.* from seeker_job_application sja
INNER JOIN seeker_profile sp on sja.seeker_id = sp.id
INNER JOIN seeker_experience se on se.seeker_id = sp.id
where sja.job_id = 1
GROUP BY sp.id
having sum(se.total_month) > 20

How to write custom findAll() with Specification in JPA repository

When I use skuRepository.getAll(), it works OK, but when I apply filters, defined in Specification (List filteredRegs = skuRepository.getAll(specification)) I still get all the rows of the table
What should i do to apply the specifications to my custom method?
public interface SkuRepository extends CrudRepository<Sku, Integer>, JpaSpecificationExecutor<Sku> {
#Query("select s from Sku s join fetch s.unit un join fetch s.supplier sup WHERE un.id = sku_unit_id AND sup.id = supplier_id")
List<Sku> getAll(#Nullable Specification<Sku> var1);
#Query("select s from Sku s join fetch s.unit un join fetch s.supplier sup WHERE un.id = sku_unit_id AND sup.id = supplier_id")
List<Sku> getAll();
}
UPD:
Here is my entities.
When I make sampling by a Sku table using the Specification API, I see three separate selects in log: one for Sku entity, one for Unit and one for Suppliers. I want my app to make one select with joins.
I read that this is due to the fact that I use EAGER fetch type, so I change it to LAZY, but then I got another problem: "InvalidDefinitionException: No serializer found..." This is logical because related entities Unit and Supplier are not loaded.
Then I decided to write my custom getAll() with request:
#Query("select s from Sku s join fetch s.unit un join fetch s.supplier sup WHERE un.id = sku_unit_id AND sup.id = supplier_id ORDER BY s.name")
But now it does not support Specification.
Please advise what to do.
#Entity
#Table(name = "sku")
public class Sku implements Cloneable, CloneableEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "sku_code", length = 6, nullable = false, unique = true)
private String code;
#Column(name = "sku_name", nullable = false)
private String name;
#ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
#JoinColumn(name = "sku_unit_id", nullable = false)
private Unit unit;
#ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
#JoinColumn(name = "supplier_id", nullable = false)
private Supplier supplier;
#Column(name = "qty_in_sec_pkg")
private int quantityInSecondaryPackaging;
#Column(name = "sku_is_active", nullable = false)
private boolean isActive;
//constructors, getters, setters
}
#Entity
#Table(name = "units")
public class Unit {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id ")
private int id;
#Column(name = "unit", nullable = false, unique = true)
private String unit;
#Column(name = "description")
private String description;
//constructors, getters, setters
}
#Entity
#Table(name = "suppliers")
public class Supplier {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id ")
private int id;
#Column(name = "supplier_code", length = 6, nullable = false, unique = true)
private String supplierCode;
#Column(name = "supplier_name", nullable = false)
private String name;
#Column(name = "create_date", length = 19, nullable = false)
private String createDate;
#Column(name = "update_date", length = 19)
private String updateDate;
//constructors, getters, setters
}
You can't mix #Query and Specification
You can only use JpaSpecificationExecutor interface methods to use Specification.
Find more details here

Spring Data JPA update a Row without getting the row ById

I want to update the table using spring-jpa
This is my Entity Class
public class RewardEntity {
#Id
#Column(name = "reward_id", columnDefinition = "bigserial")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long rewardId;
#Column(name = "reward_title", nullable = false)
private String rewardTitle;
#Column(name = "reward_text")
private String rewardText;
#Column(name = "reward_type", nullable = false)
private String rewardType;
#Column(name = "reward_for_code", nullable = false)
private String rewardFor;
#Column(name = "reward_from_date", nullable = false)
private OffsetDateTime rewardFromDate;
#Column(name = "reward_to_date", nullable = false)
private OffsetDateTime rewardToDate;
#Column(name = "is_display_on", nullable = false)
private Boolean isDisplayOn;
#Column(name = "created_id", length = 50, nullable = false)
private String createdId;
#Column(name = "updated_id", length = 50)
private String updatedId;
#Column(name = "created_date", columnDefinition = "timestamptz", nullable = false)
private OffsetDateTime createdDate;
#Column(name = "last_modified_date", columnDefinition = "timestamptz")
private OffsetDateTime lastModifiedDate;
}
I have a PutMapping Spring boot API that gets below Json Input
{
"rewardId": 53,
"rewardTitle": "Reward is Allocated",
"rewardText": "Reward allocated for your recent purchase with our shop located at ABC-Mall",
"rewardType": "Informational",
"rewardFor": "Customer",
"rewardFromDate": "2019-04-12T00:00:00+05:30",
"rewardToDate": "2019-04-15T00:00:00+05:30",
"isDisplayOn": false
}
My Controller takes Principal object for both creation and updating the rewards table
#PutMapping
public ResponseEntity<RewardsResponse> updateRewards(Principal updatedPrincipal,
#RequestBody RewardUpdateRequest RewardUpdateRequest) {
But I won't send my createdId or updatedId from my Angular-UI.. So when i try to insert the updated-entity in to the table, using the below service-layer code
public RewardEntity updateReward(Principal principal, rewardEntity rewardEntity) {
String updatedId = null != principal ? principal.getName() : "defaultUpdatedId";
rewardEntity.setUpdatedCdsId(updatedId);
rewardEntity.setLastModifiedDate(OffsetDateTime.now());
return rewardRepository.save(rewardEntity);
}
I get the below error
could not execute statement; SQL [n/a]; constraint [created_id]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
My assumption is that RewardEntity gets updated in the same row by mapping the ID that we pass and update only the fields that i set and do not touch rest of the fields ...
Should i first get my RewardEntity object from the DB based on the ID and then update on top of it ?? This makes the code connect DB twice for every update.
Request your inputs please
I would first get reference object using updatedId
RewardEntity rewardEntity = rewardRepository.getOne(updatedId )
update this object as per your requirement
rewardEntity.setLastModifiedDate(OffsetDateTime.now());
and finally use save to update this.
return rewardRepository.save(rewardEntity);
getOne() returns a reference to the entity and internally invokes EntityManager.getReference() method. It will always return a proxy without hitting the database (lazily fetched).

SQL to JPQL, How to query Nested JPQL

I wonder if JPQL can be nested query. I am studying Spring Data JPA, and I also have uploaded several related questions.
If I have below sql in MySQL, how do I produce JPQL:
select
c.*
from
cheat c
left join (select * from cheat_vote where val = 1) v on c.cheat_seq = v.cheat_fk
group by
c.cheat_seq
having
count(*) < 10
limit 5
I have two entities.
public class Cheat implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "cheat_seq", length = 10)
private Long cheatSeq;
#Column(name = "question", unique = true, nullable = false)
private String question;
#Column(name = "answer", unique = true, nullable = false)
private String answer;
#Column(name = "writer_ip", nullable = false)
private String writerIP;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "reg_date", nullable = false)
private Date regDate;
#Transient
private String regDateText;
#OneToMany(mappedBy = "cheat", fetch=FetchType.LAZY)
private Set<CheatVote> vote;
#Override
public String toString() {
return "Cheat [cheatSeq=" + cheatSeq + "]";
}
}
Above entity has a #OneToMany collection, and the collection entity is below.
public class CheatVote implements Serializable{
private static final long serialVersionUID = 1L;
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Id
#Column(name="seq", nullable=false)
private Long seq;
#Column(name="val", nullable=false)
#NonNull
private Integer value;
#Column(name="ip_address", nullable=false)
#NonNull
private String ipAddress;
#JoinColumn(name="cheat_fk", referencedColumnName="cheat_seq")
#ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
#NonNull
private Cheat cheat;
#Override
public String toString() {
return "CheatVote [seq=" + seq + "]";
}
}
I want to get Cheat entitiy which has less than 10 children CheatVote entities.
You can try it:
#Query("SELECT c FROM Cheat c LEFT JOIN c.vote v WHERE v.value = 1 GROUP BY c.cheatSeq HAVING count(c) < 10")
About 'LIMIT' you can use parameter Pageable of Spring Data JPA

How to retrieve data based on inverseColumn data using CrudRepository in springboot?

I have two tables i.e. users and events. Users table will be filled when new user will sign up. Later same user can create calendar events. so events table will be filled and users_events will keep mapping of events based on user.
I would like to find all events based on logged in userId. so here is query, it should return data based on it.
select * from events where eventid in (select eventId from users_event where id_user=x ). Here is my Users and Event Entity class.
User.java
#Entity
#Table(name = "users")
public class User {
#Id
#GenericGenerator(name = "generator", strategy = "increment")
#GeneratedValue(generator = "generator")
#Column(name = "id", nullable = false)
private Long id;
#Column(name = "first_name", nullable = false)
private String firstName;
#Column(name = "family_name", nullable = false)
private String familyName;
#Column(name = "e_mail", nullable = false)
private String email;
#Column(name = "phone", nullable = false)
private String phone;
#Column(name = "language", nullable = false)
private String language;
#Column(name = "id_picture")
private String pictureId;
#Column(name = "login", nullable = false)
private String login;
#Column(name = "password", nullable = false)
private String password;
#Column(name = "birth_date")
private Date birthDate;
#Column(name = "enabled")
private Boolean enabled;
//getter and setter
Event.java
#Entity
#Table(name = "events")
public class Event {
#Id
#GenericGenerator(name = "generator", strategy = "increment")
#GeneratedValue(generator = "generator")
#Column(name = "eventId", nullable = false)
private Long eventId;
#Column(name = "title", nullable = false)
private String title;
#Column(name = "description", nullable = true)
private String description;
#Column(name = "startAt", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
private Date startAt;
#Column(name = "endAt", nullable = true)
#Temporal(TemporalType.TIMESTAMP)
private Date endAt;
#Column(name = "isFullDay", nullable = false)
private Boolean isFullDay;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "users_event", joinColumns = { #JoinColumn(name = "id_event", referencedColumnName = "eventId") }, inverseJoinColumns = { #JoinColumn(name = "id_user", table = "users", referencedColumnName = "id") })
private Set<User> user = new HashSet<User>();
/getter and setter
EventRepo.java
public interface EventRepo extends CrudRepository<Event, Long> {
Event findByUser(Set<User> user);
}
I am trying to implement something, which can give me output of this query.
select * from events where eventid in (select eventId from users_event where id_user=x )
here is my implementation.any input please?
#RequestMapping(value = "/events", method = RequestMethod.GET)
public #ResponseBody List<Event> getEvents() {
logger.debug("get event list");
User x=new User();
x.setId(1);
Set<User> user= new HashSet();
user.add(x);
return (List<Event>) eventRepo.findByUser(user);
}
Just add a following method to your EventRepo:
List<Event> findAllByUserId(Long userId);
And modify your controller to something like this:
#RequestMapping(value = "/events", method = RequestMethod.GET)
public List<Event> getEvents() {
return eventRepo.findAllByUserId(1L);
}

Resources