I have found lots of answers for how to send a list parameter in to a query and check if a value is in that list but I'm trying to do the opposite - pass in the value and check if it's contained in a list in the object.
I have the following code to try to retrieve a Person using their username.
Person person = uniqueResult(namedQuery(Person.FIND_BY_USERNAME)
.setParameter("username", username).setMaxResults(1));
The username is contained in a list in the Person object.
#Column(name = "usernames")
#Convert(converter = PersonUsernameConvertor.class)
private List<String> usernames;
Is it possible to get the Person with the username parameter in their list with a NamedQuery or do I need something else? Below is what I have so far but it's not working, I'm guessing because the parameter value is on the left of the equation.
#NamedQuery(name = Person.FIND_BY_USERNAME,
query = "SELECT p from Person p WHERE :username IN p.usernames)
Example1:
#NamedQuery(name = Person.FIND_BY_USERNAME,
query = "SELECT p from Person p WHERE p.usernames in (:username)")
If usernames list contains only John and passing the parameter username with john, the above query works and returns the result.
Example2:
#NamedQuery(name = Person.FIND_BY_USERNAME,
query = "SELECT p from Person p WHERE p.usernames like CONCAT('%',:username,'%')")
If usernames list contains John,Joe and passing the parameter username with joe,the above query will check the list whether joe exists in the list or not.
Related
For eg,i have a reqmsg object having fields name and email.from postman I'm passing Email value inside object .this object is passed as parameter to a method in repository,for eg
#Query(SELECT* FROM Table WHERE email= reqmsg.getEmail)
List <Person> findPersonBySearchValue(#Param "reqmsg"RequestMsg reqmsg);
Is this the correct way?
Correct way would be to pass the search fields individually as parameters. Also in JPQL the queries reference entities not tables
#Query(SELECT p FROM Person p WHERE p.email = :email)
List <Person> findPersonByEmail(#Param("email") String email);
#Query(SELECT p FROM Person p WHERE p.name = :name)
List <Person> findPersonByName(#Param("name") String name);
From one query findAllByName(personName) I am getting back List Objects. I want to sum their age. So I make something like this:
int sum =
listPerson
.stream()
.mapToInt(PersonEntity::getAge)
.sum();
I know that I can use for example EntityManager and Query:
Query query = em.createQuery(
"SELECT SUM(p.age) FROM PErson p");
But it will sum age from all entities.
How can I write a query instead of this, to sum Person age from list, based on argument?
You can write a function inside your repository which will return a Long or int (depends on your database size) type and is annotated with #Query
#Query(value = "SELECT SUM(age) FROM Person", nativeQuery = true)
Long getAgeSum();
EDIT: After your edit, the current method could be modified like this for
1) List arguments
#Query(value = "SELECT SUM(p.age) FROM Person p WHERE p.id IN :idList", nativeQuery = true)
Long getAgeSum(#Param("idList") List<String> idList);
2) Simple arguments
#Query(value = "SELECT SUM(p.age) FROM Person p WHERE p.jobName=:jobNameParam", nativeQuery = true)
Long getAgeSum(#Param("jobNameParam") String jobNameParam);
What I want to do is
final String query = "select userName from users where userId in
(?) and isActive = 1";
SqlFieldsQuery sql = new SqlFieldsQuery(query);
List<Long> userIds = new ArrayList<Long>();
userIds.add(140l);
userIds.add(245l);
sql.setArgs(userIds.toArray());
List<List<?>> rsList = usersCache.query(sql).getAll();
. It is not giving the desired result. It is returning only one result
instead of two.
Please suggest
It's impossible to pass an array as an argument for in. You can rewrite your query to use a join instead. It will look as follows:
select u.userName from users u
join table (userId bigint=?) t on u.userId=t.userId
where u.isActive=1
Another thing you should take into account is that SqlFieldsQuery.setArgs(...) takes a vararg as an argument. So, to prevent your array from being unfolded, you should add a cast to Object:
sql.setArgs((Object)userIds.toArray());
I have a class named Submission and another SubmissionDAO for the repository. The submission class has a number of fields such as id, author, title,...
What I want to do is search through the database and get a list of (count, author) pairs for each author value in the database.
I made a query
#Query(value = "select author, count(*) from submissions GROUP BY author order by count(author) desc", nativeQuery = true)
List<Submission> findByAuthorOccurance();
Obviously, this doesn't work because it can't put the count value in the Submission object.
My question is how would I go about getting this pair of values back to my controller?
I've tried searching but nothing comes up.
In case anyone comes here in the future for whatever reason, I figured my problem out.
When you specify a range of data points to get from the query (ie author and count), it groups the values into object arrays (Object[]) and puts those in a normal List.
So my code ended up being like this:
#Query(value = "select author, count(*) from submissions GROUP BY author order by count(author) desc", nativeQuery = true)
List<Object[]> findByAuthorOccurance();
For the query and
List<Object[]> map =submissionRepository.findByAuthorOccurance();
for(Object[] objs : map){
System.out.println((String)objs[0]+" : "+(BigInteger)objs[1]);
}
To get the data.
I have two tables linked by another table like this:
ROLES(RoleID, RoleName)
EMPLOYEES(EmployeeID, E_Name, Address)
ROLE_EMPLOYEES(RoleID#,EmployeeID#).
I want a query that retrieves all from EMPLOYEES and RoleID from ROLES and displays on Java form.
I have tried this but does not work:
rs=st.executeQuery("SELECT EMPLOYEES.*, ROLES.* FROM EMPLOYEES JOIN ROLES");
while(rs.next()){
//MOVE THE CURSOR TO THE FIRST RECORD AND GET DATA
int employeeid=rs.getInt("EmployeeID");
String id=Integer.toString(employeeid);
String name=rs.getString("E_Name");
String addr=rs.getString("Address");
String s = rs.getString("RoleID");
jComboBox1.addItem(s.trim());
//DISPLAY THE FIRST RECORD IN THE TEXT FIELD
txtEmpNumber.setText(id);
txtEmpName.setText(name);
txtEmpAddress.setText(addr);
jComboBox1.setSelectedItem(s);
}
You may try this:
SELECT
EM.*, RL.*
FROM
EMPLOYEES EM
INNER JOIN
ROLE_EMPLOYEES REM ON REM.EmployeeID = EM.EmployeeID
INNER JOIN
ROLES RL ON RL.RoleID = REM.RoleID
Just by writing the keyword JOIN the db-engine does not know in which way it should join the data of the tables; unless you want to retrieve a cartesian product (that's not your case), you need to explicitly set the criteria by using the ON clause.