Query method to searchin related collection - spring

public class Trader {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
public String name;
public String title;
public String email;
public String phone;
public String address;
#OneToMany
public Set<Trader> customers;
}
I need an auto generated query method to search among customers names of a given trader.
Sql query is :
SELECT trader.name FROM trader WHERE trader.id IN
(SELECT * FROM trader AS t
INNER JOIN trader_customers AS tc ON tc.trader_id = t.id
WHERE t.id = 'Trader ID')
Need somethin like
findInCustomersByName(#Param("trader") Trader trader, #Param("name") String name)

You can use simple JPQL like
"select t.customers from Trade t where t.name= :name"
It gives you a list of Trade Objects and then get names of the respective objects.

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

JPA Native Query. Cannot select specific columns

I'm working on a Spring Boot project using JPA to connect to my DB. I wan to make a native query to select some specific fields but it doesn't allow me to do. For example, I want to get only id, firstName, lastName and phoneNumber of a customer But it will throws me error like,
The column name current_access_token was not found in this ResultSet.
Here is my query code in the JPA repository,
#Query(value = "SELECT c.id, c.phone_number, c.firstname, c.lastname FROM tbl_customers c JOIN tbl_subscriptions s ON c.id = s.customer_id WHERE s.role = 'member' AND s.deleted_at IS NULL", nativeQuery = true)
List<Customer> findMemberByRole(String role);
Here is my Cutomer.java
#Getter
#Setter
#Accessors(chain=true)
#NoArgsConstructor
#AllArgsConstructor
#ToString
#Entity
#Table(name = "tbl_customers")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(unique = true)
private Long id;
#Column(nullable = false, name = "phone_number")
private String phoneNumber;
private String firstname;
private String lastname;
#Column(name = "current_access_token")
private String currentAccessToken;
#Column(name = "consent_accepted")
private Boolean consentAccepted;
...
...
}
How can I avoid or ignore unwanted columns? Thanks a lot for helps.
If you really want to return only 4 columns from the customer table, then the signature you want to use here is List<Object[]>:
#Query(value = "SELECT c.id, c.phone_number, c.firstname, c.lastname FROM tbl_customers c JOIN tbl_subscriptions s ON c.id = s.customer_id WHERE s.role = 'member' AND s.deleted_at IS NULL", nativeQuery = true)
List<Object[]> findMemberByRole(String role);
Then, when accessing your result set, you would use something like:
List<Object[]> resultSet = findMemberByRole("admin");
for (Object[] rs : resultSet) {
Long id = (Long) rs[0];
String phoneNumber = (String) rs[1];
String firstName = (String) rs[2];
String lastName = (String) rs[3];
}

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

unable to translate native sql query to jpa query

Hi I am new to jpql and using spring data jpa with postgres and I am not able to translate below query.
select
"user".table_1.id, "user".table_2.name,
"user".table_2.email
from
"user".table_1
left outer join
"user".table_2
on
"user".table_1.table2_id = "user".table_2.id
where
"user".table_1.parent_id=5
and below is my model classes
#entity
#table(name="table_1)
class Table1{
#id
#GeneratedValue
private Long id;
#OneToOne(mappedBy = "table_2")
private Table2 table_2;
#ManyToOne
#JoinColumn(name = "parent_id")
private Table1 parent_id;
#OneToMany(mappedBy = "account", fetch = FetchType.LAZY)
private List<Table1> childs;
}
#entity
#table(name="table_2)
class Table2
{
#id
private Long id;
private String emailId;
private String name;
#OneToOne
#JoinColumn(name = "table1_id")
private Table1 table1;
}
Since I am using DTO with spring data and I need help I am not able to solve this.
This is best I tried:
#query("select t1.id, t2.name,t2.email from Table1 t1 left outer join
t2.table_2 where t1.parent_id=?1")
public List<CustomDTO>findByParentId(Long parentId);
public class CustomDTO{
private Long table1Id;
private String name;
private String email;
}
I am not able to solve this error as I am getting the hibernate qwery as
select
table10_.id as col_0_0_,
table21_.name as col_1_0_,
table21_.email as col_2_0_
from
"user".table1 table0_
left outer join
"user".table2 table_21_
on table10_.id=table_21_.table_1 where
table0_.parent_id=?
Please help me to solve this error
If you need any help let me know.
Thanks :)
Your JPA query would look like (not tested though)
#Query("select t1.id as table1Id, t2.name as name ,t2.emailId as email from Table1 t1 join table_2 t2 where t1.parent_id= :parentId")
public List<CustomDTO>findByParentId(Long parentId){
public interface CustomDTO{
private Long table1Id;
private String name;
private String email;
}

Spring Specification dynamic query join

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?

Resources