SQL Statement to Spring Data - PersistentEntity must not be null - mysql

I´m doing a Web-Application with a Spring Boot Backend and an AngularJS frontend.
Database is MySQL.
I try do get the Top 5 Items out of my database. I´m doing this through the
#Query Annotation. I tried my SQL Statement directly onto the DB and i get the expected values.
SQL Statement:
select item
from work_item
group by item
order by count(*) desc
limit 3
#Query:
#Query(value="SELECT WORK_ITEM_ITEM FROM WORK_ITEM GROUP BY WORK_ITEM_ITEM ORDER BY COUNT( *) DESC LIMIT 5", nativeQuery = true)
List< String > find5MostUsedItems();
When i try to access the related URL i´m getting the following error:
java.lang.IllegalArgumentException: PersistentEntity must not be null!
Would be glad if someone could push me into the right direction.
In case you need more information, plz ask. (My first question :) )
Edit: my Entity:
#Entity
public class WorkItem {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "workItem_ID")
private long id;
#Column(name = "workItem_date")
private LocalDate date;
#Column(name = "workItem_mitarbeiterNummer")
private int mitarbeiterNummer;
#Column(name = "workItem_startTime")
private LocalTime startTime;
#Column(name = "workItem_endTime")
private LocalTime endTime;
#Column(name = "workItem_workDuration")
private int workDuration;
#Column(name = "workItem_item")
private String item;
#Column(name = "workItem_itemDescription")
private String itemDescription;
Greetings!

I think you should try SELECT WORKITEM_ITEM instead of SELECT WORK_ITEM_ITEM

Related

Spring data jpa - Aggregate list of values in many-to-many relationship

I have the following (simplified) entities:
#Table(name = "groups")
public class Group {
#Column(name = "id")
private long id;
#Column(name = "name")
private String name;
#ManyToMany(fetch = FetchType.LAZY)
private Set<User> users;
...
}
#Table(name = "users")
public class StoredUser extends StoredBase {
#Column(name = "id")
private long id;
#Column(nullable = false, unique = true)
private String username;
#ManyToMany(mappedBy = "users")
private Set<Group> groups;
...
}
So I wanted to get something like list of username group by groupId:
group_id group_name username
--- --- ----
1 gr1 1, 2, 3
2 gr2 4, 5
3 gr3 1, 4
At first I was just using groupRepository.findAll() and convert the response based on that. But the amount of unrelated data coming with Group and User is big and is slowing down the response. So I want to fetch just the related values only.
So I wonder what is the best way to achieve this?
Many thanks
group_concat and a 'group by' should get you there.
Something like (untested, but someone will be along to tell me if I'm being fick):
select g.group_id, g.group_name, group_concat(u.username) as all_users
from groups as g join users as u on g.users = u.id
group by u.id;
You can use projections from Spring Data JPA (doc). In your case, create interface:
interface GroupAndUsers{
String getId();
String getName();
Set<Integer> getUsersId();
}
and add following method to your repository:
List<GroupAndUsers> findAllGroupAndUsers();

Order by with jpa, how to force it to sort by a specific variable?

I have a project where i query and sort using the Pageable class in Spring boot JPA.
Imagine, i have a Project object which has a relation to ForumPost which is basically a forum.
In my DAO definitions i have an abstract class that defines a uuid for all ids, a createdDate, lasModified, createdBy and lastModifiedBy. When i try to get a page of posts from a project sorted by createdDatem its is sorting by the PROJECT createdDate instead of the post.
I have
PageRequest.of(page, size, Sort.by(Direction.valueOf(orderDir.toUpperCase()), order))
where order="createdDate" and orderDir="ASC".
How can i force it to use the post createdDate to sort?
EDIT: as asked in the comments
This is the query printed out by hibernate
select posts1_.id as id1_7_, posts1_.created_by as created_2_7_, posts1_.created_date as created_3_7_, posts1_.message as message4_7_, posts1_.project_id as project_5_7_ from projects projectdao0_ inner join forumposts posts1_ on projectdao0_.id=posts1_.project_id where projectdao0_.name=? order by projectdao0_.created_date desc limit ?
this is the POJO
public class ForumPostDAO implements DAO {
private static final long serialVersionUID = -7552574683834215423L;
#Id
#GeneratedValue(generator = "uuid2")
#Column(columnDefinition = "BINARY(16)", unique = true)
#GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
private UUID id;
#NotBlank
#Size(min = 25)
#Column(length = 2048)
private String message;
#CreatedDate
private long createdDate;
#CreatedBy
private String createdBy;
#ToString.Exclude
#EqualsAndHashCode.Exclude
#JoinColumn(name = "project_id")
#ManyToOne(cascade = { CascadeType.PERSIST , CascadeType.MERGE, CascadeType.REFRESH }, fetch = FetchType.LAZY)
private ProjectDAO project;
public ForumPostDAO(ForumPostDTO post) {
this.message = post.getMessage();
this.createdBy = post.getCreatedBy();
this.createdDate = post.getCreatedDate();
}
}

Spring Data JPA - How to query table with no entity class?

I am working on below database tables :
users table - Each row represents a User in the system. It has a foreign key constraint to countries table.
countries table - Each row represents a Country and each country can have a list of dialects stored in table dialects.
I am using Spring data JPA and have created below entity classes
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "full_name")
private String fullName;
#Column(name = "createdAt")
private Date createdAt;
#Column(name = "country_code")
private Integer countryCode;
#Column(name = "dialect_key")
private String dialectKey;
}
public class Country {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer country_code;
#Column(name = "name")
private String name;
#Column(name = "continent_name")
private String continentName;
#ElementCollection
#CollectionTable(name = "Dialect", joinColumns = { #JoinColumn(name = "country_code") })
private List<Dialect> dialectList;
}
#Embeddable
public class Dialect {
private String name;
}
Now I have a use case where I need to fetch the full name and dialect name for a given User.
Select u.full_name, d.name from users u
join countries c on u.country_code = c.country_code
join dialects d on c.country_code = d.country_code
where u.id = :user_id and u.dialect_key = d.dialect_key
Question - The above query works fine when ran as a native query and returns a List of Object. Further I am mapping the Objects List to the List of POJO. Is there a better way to do this to avoid Object -> POJO conversion explicitly ?

Hibernate generates query without using where cluase

I use hibernate and MySQL.
I have a query in MySQL database which looks like:
select
phones0_.c_id as c_id_1, phones0_.cp_id as cp_id1_2, phones0_.cp_phone as cp_phon1
from
customer_phone phones0
where
phones0_.c_id in (select customer0_.c_id from customer customer0_ )
The issue is that there is no where clause in nested select. But I always use restrictions when i do some operations in JpaRepository.
I guess there are some issues in mapping.
Here are the examples of entities:
#Data
#Entity
class Customer {
#GeneratedValue
#Id
#Column(name="c_id")
Long id;
#Column(name="c_name")
private String name;
#OneToMany( mappedBy = "customer" )
#Fetch( FetchMode.SUBSELECT )
private List<CustomerPhone> phones;
}
#Data
#Entity
#Table(name = "customer_phone")
class CustomerPhone {
#GeneratedValue
#Id
#Column(name="cp_id")
Long id;
#Column(name="cp_phone")
private String phone;
#ManyToOne( fetch = FetchType.LAZY )
#JoinColumn( name = "id", nullable = false, updatable = false )
private Customer customer;
}

Hibernate HQL query get data from table associated with another table

I have an entity called Locality as:-
#Entity
#Table(name = "CMN_LOCALITY_MASTER")
public class Locality {
#Id
#Column(name = "LOCALITY_ID", unique = true, nullable = false,length = 11)
#GeneratedValue(strategy = GenerationType.IDENTITY)
int localityId;
#Column(name = "LOCALITY_DESCRIPTION",length=70)
String localityDescription;
#JsonProperty(access = Access.WRITE_ONLY)
#ManyToOne
#JoinColumn(name = "PINCODE_ID")
Pincode pinCode;
#JsonIgnore
#ManyToOne
City city;
}
which contains another entity called City and Pincode.
City is as below:-
#Entity
#Table(name = "CMN_CITY_MASTER")
public class City{
#Id
#Column(name = "CITY_ID", unique = true, nullable = false,length = 11)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int cityId;
#Column(name = "CITY",length = 150)
private String description;
#JsonIgnore
#ManyToOne
#JoinColumn(name = "STATE_ID")
private State state;
}
I want to Get all data from Locality entity/table which has City ID = (e.g. 1)
I tried below queries:-
#Query("SELECT a FROM Locality a INNER JOIN a.city c WHERE c.cityId=?1")
List<Locality>getAllLocalityByCity(int cityId);
and also
#Query("SELECT a FROM Locality a WHERE a.city.cityId=?1")
List<Locality>getAllLocalityByCity(int cityId);
But these are not working.
Could you please suggest me something/way to query the data?
Also, is there an Eclipse Plug-In/Tool to test HQL queries in a faster way than restarting the server for every change in the query?
Could you also suggest reading documents/book for learning HQL?
Since you are not providing any logs or explanation I can suggest you try the following:
#Query("SELECT a FROM Locality a INNER JOIN a.city c WHERE c.cityId = :cityId")
List<Locality>getAllLocalityByCity(#Param("cityId") int cityId);
For learning the HQL I would start with Hibernate Docs. You can take a look at Criteria API as well.