Spring Specification dynamic query join - spring

I have two entity:
#Entity
public class User{
#Id
private String id;
...
private String username;
private String customerId;
}
public class Customer{
#Id
private String id;
private String name;
}
How can I create dynamic query just like:
select * from user where username='...';
select * from user u left join customer c o u.customerId=c.id where c.name='...';
and without #OneToOne?

Related

jpql join without relationship cannot map to column

I am suing left join to join table that has no relationship
SELECT a, u.fullname FROM admin a
LEFT JOIN useru ON a.username = u.username
and return it as an List<Admin>
Admin class:
public class Admin {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String email;
private Integer status;
#Transient
private String fullname;
}
but fullname is null

How to retrieve only a specific field from child entity on #OneToOne relationship, not all fields?

When I use jpa's #OneToOne annotation, I want to get the userName field from the table, not all fields. What should I do instead?
#Setter
#Getter
#Entity
public class Menu implements Serializable {
private static final long serialVersionUID = 4462798713783196961L;
/**
* id
*/
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
...
#OneToOne
#JoinColumn(name = "createUserId",referencedColumnName = "userId")
private User createUser;
#Column(nullable = false)
private LocalDateTime createTime;
}
What do I need to do, can I get the userName field in the User object, but not all of it? Thank you in advance.
You can create a POJO with required fields. e.g. You only want id from Menu and userName from User:
public class CustomMenu {
private Long menuId;
private String userName;
public CustomMenu(Long menuId, String userName) {
this.menuId = menuId;
this.userName = userName;
}
// getters, setters
}
Then you can write a query with hql using the constructor in the CustomMenu with parameters new com.yourpackage.CustomMenu(m.id, m.createUser.userName) and join User entity (join m.createUser) :
TypedQuery<CustomMenu> query = entityManager.createQuery("select new com.yourpackage.CustomMenu(m.id, m.createUser.userName)"
+ "from com.yourpackage.Menu m join m.createUser", CustomMenu.class);
List<CustomMenu> menus = query.getResultList();
This generates one sql query with inner join fetching only required fields :
select menu0_.id as col_0_0_, user1_.user_name as col_1_0_ from menu menu0_ inner join user user1_ on menu0_.create_user_id=user1_.user_id

Spring, JPA: How to query for Entities under another Entity with a many-to-many relationship bridge table setup

I'm fairly new to Spring. I'm trying to query all the donations under one donor with this ERD:
Donor |----* Agreement *----| Donations (A many-to-many relationship that uses a bridge table)
Here's my code:
Donor.java
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
public class Donor extends Auditable implements Comparable<Donor>{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotBlank(message = "Cannot have an empty account number field.")
private String accountNumber;
private String accountName;
private String salutation;
private String donorName;
private String cellphoneNumber;
private String emailAddress;
private String companyTIN;
private String phone1;
private String phone2;
private String faxNumber;
private String address1;
private String address2;
private String address3;
private String address4;
private String address5;
private String companyAddress;
private LocalDate birthDate;
private String notes;
#OneToMany(mappedBy = "donor")
List<MOA> moaList = new ArrayList<>();
...
}
Donation.java
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
public class Donation extends Auditable implements Comparable<Donation> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotBlank(message = "Cannot have an empty account number field.")
private String accountNumber;
private String accountName;
private String orNumber;
private String date;
private Double amount;
private String notes;
private String needCertificate;
private String purposeOfDonation;
#OneToMany(mappedBy = "donation")
List<MOA> moaList = new ArrayList<>();
...
}
MOA.java (Agreement)
#Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
public class MOA extends Auditable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne
#JoinColumn(name = "donor_id")
#JsonIgnoreProperties("moaList")
private Donor donor;
#ManyToOne
#JoinColumn(name = "donation_id")
#JsonIgnoreProperties("moaList")
private Donation donation;
private String name;
private String donorAccountNumber;
private Long foreignDonationId;
private LocalDate dateSigned;
}
In my DonorRepository I'm trying to make this query which I expected would give me what I want:
public interface DonorRepository extends JpaRepository<Donor, Long> {
...
#Query(value = "SELECT * FROM donor WHERE account_number = ?1", nativeQuery = true)
List<Donation> findDonorsDonations(String accountNumber);
...
This gives me an error
Failed to convert from type [java.lang.Object[]] to type [com.package.server.domain.Donation] for value '{1, admin, 2021-04-01 10:29:53.0, admin, 2021-04-01 10:29:53.0, School, 123456, null, null, null, null, null, null, null, null, null, John Doe, null, null, null, null, null, Mr.}'; nested exception is org
You can use specification api and SpecificationExecutor.
You have to Join Donation with MAO(MAO with Donor) then query for donations of a particular Donor.

Want to implement Search function in springboot restapi

So i have two entity classes Employee and Address and they are in #OneToOne Relation I'm able to search a Employee's with different parameter like name,designation,department. But i want to search a employee using address fields like Areaname,pincode, phone etc.. How to implement this functionality i'm currently using JpaRepo with Mysql.
#Entity
public class Employee{
#Id#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String Name;
private String Designation;
private String Department;
#OneToOne(cascade=CascadeType.ALL)
private Address address;}
#Entity
public class Address{
private String Streetname;
private String Areaname;
private String City;
private Long pincode;
#Id
private Long phone;
}
try like this:
#Query("FROM Employee AS emp LEFT JOIN emp.address AS adr WHERE adr.areaname= ?1")
public List<Employee > FindAllEmployeeByAreaName(String areaname);

Spring JPA projection with sublist

I have question about creating native query with custom response (spring projection) with nested „custom“ sublist i.e. i am trying to generate JSON output with nested sublists.
Child entity is:
#Entity
public class Child {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#NotNull
#Column(nullable = false)
private String firstName;
#NotNull
#Column(nullable = false)
private String secondName;
#Enumerated(EnumType.STRING)
private Gender gender;
private Date dateOfBirth;
private String phone;
#ManyToOne
#JoinColumn(name="child_id")
private List<Parent> parents = new ArrayList<Parent>();
//...
}
Parent entity is, for example:
#Entity
public class Parent {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#NotNull
#Column(nullable = false)
private String firstName;
#NotNull
#Column(nullable = false)
private String secondName;
private Date dateOfRegistration;
#OneToMany(fetch = FetchType.LAZY)
private List<Child> child = new ArrayList<Child>();
//...
}
Projection interface:
public interface ChildProjectionInterface {
public int getParentId();
public Date getFirstName();
public List<ChildResponse> getChildData();
interface ChildResponse {
public int getChildID();
public String getFirstName();
}
}
Query (but, obviously, doesn't working):
#Query(value = "SELECT p.id AS parentId, p.firstName AS firstName, c.id AS childData.childId, c.firstName AS childData.firstName FROM parent p LEFT JOIN child c ON p.child_id = c.child_id AND p.secondName = :secondName", nativeQuery = true)
List<ChildProjectionInterface> getListWithSubList(#Param(value ="secondName") String secondName);
I was reading and researching and trying..but nothing works (I saw https://medium.com/swlh/spring-data-jpa-projection-support-for-native-queries-a13cd88ec166, saw "for json auto" clause but not for spring jpa, etc.)
Did you try jpa fetch operator?
#Query("select p from parent p left join fetch p.child c where p.secondName = :secondName")

Resources