JPA JPQL request with select and Concat

4,268 views
Skip to first unread message

xael-fry

unread,
Mar 5, 2012, 3:57:18 AM3/5/12
to play-fr...@googlegroups.com

I have in java differents class

@Entity
@Table(name = "users")
public class User extends Model {
 
public String name;

 
@ManyToMany
 
public List<Role> roles;
}

And

@Entity
@Table(name = "roles")
public class Role extends Model {
 
public String name;
}

Tables contains

Table Users    |        |   Table Roles   |           |Table Users_roles    |
id    
| Name   |        | id    | Name    |           |users_id  | roles_id |
1     | User 1 |        | 1     | CEO     |           |    2     |    1     |
2     | User 2 |        | 2     | Manager |           |    2     |    2     |
3     | User 3 |                                      |    3     |    1     |

I want to make the following request (ok with PostgreSql 9.1.12)

SELECT u.*, array_to_string(array_agg(r.name ORDER BY r.name ASC), ' / ')
  FROM  users u
  LEFT OUTER JOIN users_roles ur ON u
.id=ur.users_id
  FULL JOIN roles r ON r
.id=ur.roles_id
  GROUP BY u
.id, ur.users_id
  ORDER BY array_to_string ASC

I have the result I Want

User name | roles
User 1    |          
User 3    | CEO        
User2     | CEO / MANAGER        

Can you help me to get the JPA syntax for this request?

christian sarnataro

unread,
Mar 5, 2012, 4:42:12 AM3/5/12
to play-fr...@googlegroups.com
Hi, you could try with a native query.

See this thread:


I think that native queries can be useful when you want to get some "custom" data.

tazmaniac

unread,
Mar 5, 2012, 5:42:47 AM3/5/12
to play-fr...@googlegroups.com
I needed to do something similar to access MySQL group_concat function from within JPA. And to do that I did the following:

1. Implement org.hibernate.dialect.function.SQLFunction to render the group_concat function:

public String render(Type firstArgumentType, List arguments, SessionFactoryImplementor factory)
throws QueryException {
if (arguments.size() < 1) {
throw new QueryException(new IllegalArgumentException("group_concat should have at least one arg"));
}
StringBuilder builder = new StringBuilder();
if (arguments.size() > 1 && arguments.get(0).equals("'distinct'")) {
builder.append("distinct ");
builder.append(arguments.get(1));
} else {
builder.append(arguments.get(0));
}
return "group_concat(" + builder.toString() + ")";
}

2. Extend MySQL5InnoDBDialect to register the group_concat function:
public CustomMySQL5InnoDBDialect() {
super();
registerFunction("group_concat", new GroupConcatFunction());
}

3. Update application.conf to use the custom Hibernate dialect:

jpa.dialect=utils.CustomMySQL5InnoDBDialect

Reply all
Reply to author
Forward
0 new messages