I have two tables with many to one realtion. I want to sort data in table "user" by column "street" that is in "address" table in ASC or DESC direction defined by request param:
localhost:8080/getUsers?sort=address,desc
When I execute sql script:
SELECT * FROM user INNER JOIN address ON user.address_id=address.id ORDER BY street DESC
in workbench or phpMyAdmin it works good. All data are sorted by street name;
But when i try get it in postman by:
getUsers?sort=address,desc
I have this error in console output:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'INNER.address' in 'order clause'
Where is problem?
#Table(name = "user")
public class User {
private Long id;
private String name;
#ManyToOne()
#JoinColumn(name = "address_id")
private Address address;
}
#Table(name = "address")
public class Address {
private Long id;
private String street
#OneToMany(mappedBy = "address")
private List<User> user;
}
public interface UserRepository extends JpaRepository<User, Long> {
#Query(value = "SELECT * FROM user INNER JOIN address ON user.address_id=address.id",
countQuery = "SELECT * FROM contact_messages INNER JOIN contact_topics ON contact_messages.contact_topic_id=contact_topics.id",
nativeQuery = true)
Page<User> findAll(Pageable pageable);
}
Also when i wrote query in repository like this it works as good as in workbench:
#Query(value = "SELECT * FROM user INNER JOIN address ON user.address_id=address.id ORDER BY address DESC",
countQuery = "SELECT * FROM contact_messages INNER JOIN contact_topics ON contact_messages.contact_topic_id=contact_topics.id ORDER BY address DESC",
nativeQuery = true)
But i want to have controll of request and sort data when i want (using sort param).
Try replacing the SQL to
SELECT u, a FROM user u INNER JOIN u.address a ORDER BY street DESC
Related
My object is
#Entity
public class DiscoveryResult {
.....
#ManyToOne
#JoinColumn
private Company company;
....
I want to querying like this;
#Query(value="SELECT scope from DiscoveryResult where company = :companyId group by scope")
List<String> findDistinctCategories(long companyId);
How can I query by id which under company
You need to join the DiscoveryResult and Company entities and then compare the id column of the Company with the companyId query parameter.
#Query(value="SELECT r.scope from DiscoveryResult r JOIN r.company c where c.id = :companyId group by scope")
List<String> findDistinctCategories(long companyId);
I have 3 entities - usergroup, user, usergroupmemberships. usergroupmemberships has a 1 to 1 to both user and usergroup. im trying to get a users groups with his id
The following Query works in my DB:
SELECT *
FROM UserGroup g
JOIN UserGroupMembership ON
UserGroupMembership.usergroup_id = g.id
WHERE UserGroupMembership.user_id = 868
Wildfly:
the same as a Java REST POST that uses a query from my entitymanager doesnt with a nullpointerexception
SELECT g
FROM UserGroup g
JOIN UserGroupMembership
ON UserGroupMembership.usergroup = g.id
WHERE UserGroupMembership.user = :id
How do i write this correctly?
Tried different ways to write the query and tried writing user_id
im on wildfly and java ee
public List<UserGroup> findUserGroupbyUser(long id) {
return em.createQuery("SELECT g FROM UserGroup g JOIN
UserGroupMembership ON UserGroupMembership.usergroup = g WHERE
UserGroupMembership.user.id = :id", UserGroup.class).setParameter("id",
id).getResultList();
}
#Entity
public class UserGroupMembership {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#OneToOne(cascade = CascadeType.ALL)
private UserGroup usergroup;
#OneToOne(cascade = CascadeType.ALL)
private User user;
expected result is 1 entry
My application under Spring Boot v1.5.7
I have 3 entities (schematically):
#Entity
public class Word {
#Id
#GeneratedValue
private Integer id
...
}
#Entity
public class UserWordList {
#Id
#GeneratedValue
private Integer id
#ManyToOne
#JoinColumn(name = "user_id")
private User user;
#ManyToOne
#JoinColumn(name = "word_id")
private Word word;
}
#Entity
public class UserAnotherWordList {
#Id
#GeneratedValue
private Integer id
#ManyToOne
#JoinColumn(name = "user_id")
private User user;
#ManyToOne
#JoinColumn(name = "word_id")
private Word word;
}
And now I need to select all Words for User, but exclude Words placed in user's lists
Native SQL for user_id=1 is
select *
from Word w
left join UserWordList uwl
on w.id = uwl.word_id and uwl.user_id = 1
left join UserAnotherWordList uawl
on w.id = uawl.word_id and uawl.user_id = 1
where uwl.word_id is NULL
and uawl.word_id is NULL
What is a best way to do it? Ideally I would like to use Spring Data features or HQL, but I don't understand how...
UPD
I solve my problem with native query:
#Entity
#NamedNativeQuery(
name = "User.getWordsToProcess",
resultClass = Word.class,
query = "<...native query to select Words...>"
)
public class User {...}
...
public interface UserRepository extends CrudRepository<User, Integer> {
List<Word> getWordsToProcess(Integer userId);
}
Fastest answer is Criteria api (but that is deprecated in hibernate 5.2 and above.)
So you can use Hql :
getSession().createQuery(" select * from UserWordList u left join fetch u.word
left join fetch u.user").list()
And you can use union or create another query to fetch UserAnotherWordList.
Also you can set any restrictions in Hql like below:
Query query = getSession().createQuery(" select * from UserWordList u left join fetch u.word left join fetch u.user us where us.user = :sample").list();
query.setParameter("sample",value);
query.list();
I would like to be able to get mutual friends of both users in hql.
Is there any way to do it with h2 db.
I'm using spring-boot 1.5.6 with h2 embedded db.
Below is my User entity.
#Entity
#Table(name="user")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Long id;
#Version
#Column(name="version")
private int version;
#NotNull
#Column(name="username", nullable=false, unique=true)
private String username;
#Column(name="email", nullable=false, unique=true)
private String email;
#Column(name="password", nullable=false)
private String password;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "friends")
private Set<User> friends;
and repository
public interface UserRepository extends PagingAndSortingRepository<User, Long>{
User findByEmailAndPassword(String email, String password);
Here's my latest try which gives me the exception for some reason.
#Query("Select friends from User U join U.friends friends where size (friends.username) > 1 and exists (select friends from User U1 join U1.friends friends1 where friends1.username = ?1) and exists (select friends from User U2 join U2.friends friends2 where friends2.username = ?2)")
List<User> findMutualFriends(String username, String friend);
And when I try to get only duplicate values from it I get the exception. Can't access friends of username even though I'm using join on them. Here's stack trace:
Caused by: org.h2.jdbc.JdbcSQLException: Column "USER2_.USER_ID" not found; SQL statement:
select user2_.id as id1_4_, user2_.acc_status as acc_stat2_4_, user2_.email as email3_4_, user2_.gender as gender4_4_, user2_.password as password5_4_, user2_.username as username6_4_, user2_.version as version7_4_ from user user0_ inner join friends friends1_ on user0_.id=friends1_.user_id inner join user user2_ on friends1_.friends_id=user2_.id where (select count(user2_.user_id) from friends friends1_, user user2_ where user0_.id=friends1_.user_id and friends1_.friends_id=user2_.id)>1 and (exists (select user2_.id as id1_4_ from user user3_ inner join friends friends4_ on user3_.id=friends4_.user_id inner join user user5_ on friends4_.friends_id=user5_.id where user5_.username=?)) and (exists (select user2_.id as id1_4_ from user user6_ inner join friends friends7_ on user6_.id=friends7_.user_id inner join user user8_ on friends7_.friends_id=user8_.id where user8_.username=?)) [42122-196]
Any idea how to do it cause I couldn't find the answer. Maybe it can be done easier but I'm new to hql and can't figure it out.
Thanks.
I thought I know how to use JOIN in JPQL but apparently not. Can anyone help me?
select b.fname, b.lname from Users b JOIN Groups c where c.groupName = :groupName
This give me Exception
org.eclipse.persistence.exceptions.JPQLException
Exception Description: Syntax error parsing the query
Internal Exception: org.eclipse.persistence.internal.libraries.antlr.runtime.EarlyExitException
Users have a OneToMany relationship with Groups.
Users.java
#Entity
public class Users implements Serializable{
#OneToMany(mappedBy="user", cascade=CascadeType.ALL)
List<Groups> groups = null;
}
Groups.java
#Entity
public class Groups implements Serializable {
#ManyToOne
#JoinColumn(name="USERID")
private Users user;
}
My second question is let say this query return a unique result, then if I do
String temp = (String) em.createNamedQuery("***")
.setParameter("groupName", groupName)
.getSingleResult();
*** represent the query name above. So does fname and lname concatenated together inside temp or I get a List<String> back?
Join on one-to-many relation in JPQL looks as follows:
select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName
When several properties are specified in select clause, result is returned as Object[]:
Object[] temp = (Object[]) em.createNamedQuery("...")
.setParameter("groupName", groupName)
.getSingleResult();
String fname = (String) temp[0];
String lname = (String) temp[1];
By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use #Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:
#Entity #Table(name = "Users")
public class User implements Serializable { ... }