Search Results

Search found 49 results on 2 pages for 'jpql'.

Page 1/2 | 1 2  | Next Page >

  • Java: JPQL date function to add a time period to another date

    - by bguiz
    SELECT x FROM SomeClass WHERE x.dateAtt BETWEEN CURRENT_DATE AND (CURRENT_DATE + 1 MONTH) In the above JPQL statement, SomeClass has a memebr dateAttr, which is a java.util.Date and has a @Temporal(javax.persistence.TemporalType.DATE) annotation. I need a way to do the (CURRENT_DATE + 1 MONTH) bit - it is obviously wrong in its current state - but cannot find the doc with the date function for JPQL. Can anyone point me in the direction of a doc that documents JPQL date functions (and also how to do this particular query)?

    Read the article

  • How do i write this jpql query?

    - by Nitesh Panchal
    Hello, Say i have 5 tables, tblBlogs tblBlogPosts tblBlogPostComment tblUser tblBlogMember BlogId BlogPostsId BlogPostCommentId UserId BlogMemberId BlogTitle BlogId CommentText FirstName UserId PostTitle BlogPostsId BlogId BlogMemberId Now i want to retrieve only those blogs and posts for which blogMember has actually commented. So in short, how do i write this plain old sql :- Select b.BlogTitle, bp.PostTitle, bpc.CommentText from tblBlogs b Inner join tblBlogPosts bp on b.BlogId = bp.BlogId Inner Join tblBlogPostComment bpc on bp.BlogPostsId = bpc.BlogPostsId Inner Join tblBlogMember bm On bpc.BlogMemberId = bm.BlogMemberId Where bm.UserId = 1; As you can see, everything is Inner join, so only that row will be retrieved for which the user has commented on some post of some blog. So, suppose he has joined 3 blogs whose ids are 1,2,3 (The blogs which user has joined are in tblBlogMembers) but the user has only commented in blog 2 (of say BlogPostId = 1). So that row will be retrieved and 1,3 won't as it is Inner Join. How do i write this kind of query in jpql? In jpql, we can only write simple queries like say :- Select bm.blogId from tblBlogMember Where bm.UserId = objUser; Where objUser is supplied using :- em.find(User.class,1); Thus once we get all blogs(Here blogId represents a blog object) which user has joined, we can loop through and do all fancy things. But i don't want to fall in this looping business and write all this things in my java code. Instead, i want to leave that for database engine to do. So, how do i write the above plain sql into jpql? and what type of object the jpql query will return? because i am only selecting few fields from all table. In which class should i typecast the result to? I think i posted my requirement correctly, if i am not clear please let me know. Thanks in advance :).

    Read the article

  • How do i write this jpql query? java

    - by Nitesh Panchal
    Hello, Say i have 5 tables, tblBlogs tblBlogPosts tblBlogPostComment tblUser tblBlogMember BlogId BlogPostsId BlogPostCommentId UserId BlogMemberId BlogTitle BlogId CommentText FirstName UserId PostTitle BlogPostsId BlogId BlogMemberId Now i want to retrieve only those blogs and posts for which blogMember has actually commented. So in short, how do i write this plain old sql :- Select b.BlogTitle, bp.PostTitle, bpc.CommentText from tblBlogs b Inner join tblBlogPosts bp on b.BlogId = bp.BlogId Inner Join tblBlogPostComment bpc on bp.BlogPostsId = bpc.BlogPostsId Inner Join tblBlogMember bm On bpc.BlogMemberId = bm.BlogMemberId Where bm.UserId = 1; As you can see, everything is Inner join, so only that row will be retrieved for which the user has commented on some post of some blog. So, suppose he has joined 3 blogs whose ids are 1,2,3 (The blogs which user has joined are in tblBlogMembers) but the user has only commented in blog 2 (of say BlogPostId = 1). So that row will be retrieved and 1,3 won't as it is Inner Join. How do i write this kind of query in jpql? In jpql, we can only write simple queries like say :- Select bm.blogId from tblBlogMember Where bm.UserId = objUser; Where objUser is supplied using :- em.find(User.class,1); Thus once we get all blogs(Here blogId represents a blog object) which user has joined, we can loop through and do all fancy things. But i don't want to fall in this looping business and write all this things in my java code. Instead, i want to leave that for database engine to do. So, how do i write the above plain sql into jpql? and what type of object the jpql query will return? because i am only selecting few fields from all table. In which class should i typecast the result to? I think i posted my requirement correctly, if i am not clear please let me know. Thanks in advance :).

    Read the article

  • Indexed element access in JPQL

    - by Timo Westkämper
    Is it possible to do indexed element access in JPQL like in HQL : select o from Order o where o.items[0].id = 1234 I couldn't find something related in the JPA 2 specs, I am targeting EclipseLink JPA here, so if you come up with an EclipseLink solution, that's ok as well, although a JPQL standard solution is preferred.

    Read the article

  • JPQL cross tab query

    - by Phil
    Hi can anyone tell me if its possible to write a cross tab query in JPQL? (I'm using eclipse link JPA2) An example of a cross tab query in SQL can found here http://onlamp.com/pub/a/onlamp/2003/12/04/crosstabs.html SELECT dept, COUNT(CASE WHEN gender = 'm' THEN id ELSE NULL END) AS m, COUNT(CASE WHEN gender = 'f' THEN id ELSE NULL END) AS f, COUNT(*) AS total FROM person GROUP BY dept How can I do the same thing as a single query in JPQL? Looking at the spec it doesn't seem to look like CASE is valid in COUNT Is there any other way?

    Read the article

  • Google App Engine - DELETE JPQL Query and Cascading

    - by Taylor Leese
    I noticed that the children of PersistentUser are not deleted when using the JPQL query below. However, the children are deleted if I perform an entityManager.remove(object). Is this expected? Why doesn't the JPQL query below also perform a cascaded delete? @OneToMany(mappedBy = "persistentUser", cascade = CascadeType.ALL) private Collection<PersistentLogin> persistentLogins; ... @Override @Transactional public final void removeUserTokens(final String username) { final Query query = entityManager.createQuery( "DELETE FROM PersistentUser p WHERE username = :username"); query.setParameter("username", username); query.executeUpdate(); }

    Read the article

  • JPQL IN clause: Java-Arrays (or Lists, Sets...)?

    - by Bernd Haug
    I would like to load all objects that have a textual tag set to any of a small but arbitrary number of values from our database. The logical way to go about this in SQL would be to build an "IN" clause. JPQL allows for IN, but it seems to require me to specify every single parameter to IN directly (as in, "in (:in1, :in2, :in3)"). Is there some way to specify an array, or a list (or some other container) that should be unrolled to the values of an IN clause?

    Read the article

  • Java: JPQL select statement

    - by bguiz
    select x from X x where x.a.id = :a_id -- Always 0 objects selected Why does the above JPQL statement not work, but the one below work? select a from A a where a.id = :a_id -- a_obj select x from X x where x.a = :a_obj -- Always correct number of objects selected Neither query throws an exception during execution, but a different number of results are obtained. Thanks

    Read the article

  • Java: JPQL search -similar- strings

    - by bguiz
    What methods are there to get JPQL to match similar strings? By similar I mean: Contains: search string is found within the string of the matches entity Case-insensitive Small mispellings: e.g. "arow" matches "arrow" I suspect the first two will be easy, however, I would appreciate help with the last one Thank you

    Read the article

  • Help with JPQL query

    - by Robert
    I have to query a Message that is in a provided list of Groups and has not been Deactivated by the current user. Here is some pseudo code to illustrate the properties and entities: class Message { private int messageId; private String messageText; } class Group { private String groupId; private int messageId; } class Deactivated { private String userId; private int messageId; } Here is an idea of what I need to query for, it's the last AND clause that I don't know how to do (I made up the compound NOT IN expression). Filtering the deactivated messages by userId can result in multiple messageIds, how can I check if that subset of rows does not contain the messageId? SELECT msg FROM Message msg, Group group, Deactivated unactive WHERE group.messageId = msg.messageId AND (group.groupId = 'groupA' OR group.groupId = 'groupB' OR ...) AND ('someUserId', msg.messageId) NOT IN (unactive.userId, unactive.messageId) I don't know the number of groupIds ahead of time -- I receive them as a Collection<String> so I'll need to traverse them and add them to the JPQL dynamically.

    Read the article

  • JPQL check many-to-many relationship

    - by Juriy
    Just a quick question: There's the entity (for example User) who is connected with the ManyToMany relationship to the same entity (for example this relation describes "friendship" and it is symmetric). What is the fastest way in terms of execution time to check if User A is a "friend" of user B? The "dumb" way would be to fetch whole List and then check if user exists there but that's obviously the overhead. I'm using JPA 2 Here's the sample code: @Entity @Table(name="users") public class UserEntity { @ManyToMany(fetch = FetchType.LAZY) private List<UserEntity> friends; .... }

    Read the article

  • JPQL (JPA) search substring

    - by JavaBeginner
    Hi, Im facing simple problem with searching entities by some (sub)string, which they might contain. E.g. I have users user1, usr2, useeeer3, user4 and I will enter to search window "use" and I expect to return user1, useeer3, user4. Im sure you know what I mean now. Is there any construction in JPA (JQPL)? It would be nice to search using WHERE somehow in named queries. Something like "SELECT u FROM User u WHERE u.nickname contains :substring"

    Read the article

  • Test JPQL with NetBeans IDE 7.3 Tools

    - by Geertjan
    Since I pretty much messed up this part of the "Unlocking Java EE 6 Platform" demo, which I did together with PrimeFaces lead Çagatay Çivici during JavaOne 2012, I feel obliged to blog about it to clarify what should have happened! In my own defense, I only learned about this feature 15 minutes before the session started. In 7.3 Beta, it works for Java SE projects, while for Maven-based web projects, you need a post 7.3 Beta build, which is what I set up for my demo right before it started. Then I saw that the feature was there, without actually trying it out, which resulted in that part of the demo being a bit messy. And thanks to whoever it was in the audience who shouted out how to use it correctly! Screenshots below show everything related to this new feature, available from 7.3 onwards, which means you can try out your JPQL queries right within the IDE, without deploying the application (you only need to build it since the queries are run on the compiled classes): SQL view: Result view for the above: Here, you see the result of a more specific query, i.e., check that a record with a specific name value is present in the database: Also note that there is code completion within the editor part of the dialog above. I.e., as you press Ctrl-Space, you'll see context-sensitive suggestions for filling out the query. All this is pretty cool stuff! Saves time because now there's no need to deploy the app to check the database connection.

    Read the article

  • Does the JPQL avg aggregate function work with Integers?

    - by Kyle Renfro
    I have a JPA 2 Entity named Surgery. It has a member named transfusionUnits that is an Integer. There are two entries in the database. Executing this JPQL statement: Select s.transfusionUnits from Surgery s produces the expected result: 2 3 The following statement produces the expected answer of 5: Select sum(s.transfusionUnits) from Surgery s I expect the answer of the following statement to be 2.5, but it returns 2.0 instead. Select avg(s.transfusionUnits) from Surgery s If I execute the statement on a different (Float) member, the result is correct. Any ideas on why this is happening? Do I need to do some sort of cast in JPQL? Is this even possible? Surely I am missing something trivial here.

    Read the article

  • JPQL / SQL: How to select * from a table with group by on a single column?

    - by DavidD
    I would like to select every column of a table, but want to have distinct values on a single attribute of my rows (City in the example). I don't want extra columns like counts or anything, just a limited number of results, and it seems like it is not possible to directly LIMIT results in a JPQL query. Original table: ID | Name | City --------------------------- 1 | John | NY 2 | Maria | LA 3 | John | LA 4 | Albert | NY Wanted result, if I do the distinct on the City: ID | Name | City --------------------------- 1 | John | NY 2 | Maria | LA What is the best way to do that? Thank you for your help.

    Read the article

  • JPQL: What kind of objects contains a result list when querying multiple columns?

    - by Bunkerbewohner
    Hello! I'm trying to do something which is easy as pie in PHP & Co: SELECT COUNT(x) as numItems, AVG(y) as average, ... FROM Z In PHP I would get a simple array like [{ numItems: 0, average: 0 }] which I could use like this: echo "Number of Items: " . $result[0]['numItems']; Usually in JPQL you only query single objects or single columns and get Lists types, for example List or List. But what do you get, when querying multiple columns?

    Read the article

  • JPQL get most recent rows

    - by Vinnie
    Let's say I have the following tables my_profile_data ------------- integer: profile_id date: date_changed string: value my_profile ------------- integer: profile_id string: name I want to get the most recent profile information. In plain SQL this would look something like: select mpd.profile_id, mpd.value, max(mpd.date_changed) from my_profile_data mpd, my_profile mp where mpd.profile_id = mp.profile_id and mp.name='The Profile I Want' group by mpd.profile_id I've tried different variants of the following JPQL query, but cant get it to work. SELECT mpd FROM MyProfileData mpd LEFT JOIN (SELECT mpd.profileId profileId, MAX(mpd.dateChanged) FROM MyProfileData mpd LEFT JOIN mp.profile WHERE mp.name = :name GROUP BY mpd.profileId) recent ON (rp.profileid = recent.profileId) Is this query doable in JPA? I'm using EclipseLink as my JPA provider. The innermost exception I get when I try to run this is Caused by: NoViableAltException(81!=[506:7: (n= joinAssociationPathExpression ( AS )? i= IDENT | t= FETCH n= joinAssociationPathExpression )]) at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.join(JPQLParser.java:3669) ... 73 more

    Read the article

  • Configuring JPA Primary key sequence generators

    - by pachunoori.vinay.kumar(at)oracle.com
    This article describes the JPA feature of generating and assigning the unique sequence numbers to JPA entity .This article provides information on jpa sequence generator annotations and its usage. UseCase Description Adding a new Employee to the organization using Employee form should assign unique employee Id. Following description provides the detailed steps to implement the generation of unique employee numbers using JPA generators feature Steps to configure JPA Generators 1.Generate Employee Entity using "Entities from Table Wizard". View image2.Create a Database Connection and select the table "Employee" for which entity will be generated and Finish the wizards with default selections. View image 3.Select the offline database sources-Schema-create a Sequence object or you can copy to offline db from online database connection. View image 4.Open the persistence.xml in application navigator and select the Entity "Employee" in structure view and select the tab "Generators" in flat editor. 5.In the Sequence Generator section,enter name of sequence "InvSeq" and select the sequence from drop down list created in step3. View image 6.Expand the Employees in structure view and select EmployeeId and select the "Primary Key Generation" tab.7.In the Generated value section,select the "Use Generated value" check box ,select the strategy as "Sequence" and select the Generator as "InvSeq" defined step 4. View image   Following annotations gets added for the JPA generator configured in JDeveloper for an entity To use a specific named sequence object (whether it is generated by schema generation or already exists in the database) you must define a sequence generator using a @SequenceGenerator annotation. Provide a unique label as the name for the sequence generator and refer the name in the @GeneratedValue annotation along with generation strategy  For  example,see the below Employee Entity sample code configured for sequence generation. EMPLOYEE_ID is the primary key and is configured for auto generation of sequence numbers. EMPLOYEE_SEQ is the sequence object exist in database.This sequence is configured for generating the sequence numbers and assign the value as primary key to Employee_id column in Employee table. @SequenceGenerator(name="InvSeq", sequenceName = "EMPLOYEE_SEQ")   @Entity public class Employee implements Serializable {    @Id    @Column(name="EMPLOYEE_ID", nullable = false)    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="InvSeq")   private Long employeeId; }   @SequenceGenerator @GeneratedValue @SequenceGenerator - will define the sequence generator based on a  database sequence object Usage: @SequenceGenerator(name="SequenceGenerator", sequenceName = "EMPLOYEE_SEQ") @GeneratedValue - Will define the generation strategy and refers the sequence generator  Usage:     @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="name of the Sequence generator defined in @SequenceGenerator")

    Read the article

  • JPQL: unknown state or association field (EclipseLink)

    - by Kawu
    I have an Employee entity which inherits from Person and OrganizationalUnit: OrganizationalUnit: @MappedSuperclass public abstract class OrganizationalUnit implements Serializable { @Id private Long id; @Basic( optional = false ) private String name; public Long getId() { return this.id; } public void setId( Long id ) { this.id = id; } public String getName() { return this.name; } public void setName( String name ) { this.name = name; } // ... } Person: @MappedSuperclass public abstract class Person extends OrganizationalUnit { private String lastName; private String firstName; public String getLastName() { return this.lastName; } public void setLastName( String lastName ) { this.lastName = lastName; } public String getFirstName() { return this.firstName; } public void setFirstName( String firstName ) { this.firstName = firstName; } /** * Returns names of the form "John Doe". */ @Override public String getName() { return this.firstName + " " + this.lastName; } @Override public void setName( String name ) { throw new UnsupportedOperationException( "Name cannot be set explicitly!" ); } /** * Returns names of the form "Doe, John". */ public String getFormalName() { return this.lastName + ", " + this.firstName; } // ... } Employee entity: @Entity @Table( name = "EMPLOYEES" ) @AttributeOverrides ( { @AttributeOverride( name = "id", column = @Column( name = "EMPLOYEE_ID" ) ), @AttributeOverride( name = "name", column = @Column( name = "LASTNAME", insertable = false, updatable = false ) ), @AttributeOverride( name = "firstName", column = @Column( name = "FIRSTNAME" ) ), @AttributeOverride( name = "lastName", column = @Column( name = "LASTNAME" ) ), } ) @NamedQueries ( { @NamedQuery( name = "Employee.FIND_BY_FORMAL_NAME", query = "SELECT emp " + "FROM Employee emp " + "WHERE emp.formalName = :formalName" ) } ) public class Employee extends Person { @Column( name = "EMPLOYEE_NO" ) private String nbr; // lots of other stuff... } I then attempted to find an employee by its formal name, e.g. "Doe, John" using the query above: SELECT emp FROM Employee emp WHERE emp.formalName = :formalName However, this gives me an exception on deploying to EclipseLink: Exception while preparing the app : Exception [EclipseLink-8030] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.JPQLException Exception Description: Error compiling the query [Employee.FIND_BY_CLIENT_AND_FORMAL_NAME: SELECT emp FROM Employee emp JOIN FETCH emp.client JOIN FETCH emp.unit WHERE emp.client.id = :clientId AND emp.formalName = :formalName], line 1, column 115: unknown state or association field [formalName] of class [de.bnext.core.common.entity.Employee]. Local Exception Stack: Exception [EclipseLink-8030] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.JPQLException Exception Description: Error compiling the query [Employee.FIND_BY_CLIENT_AND_FORMAL_NAME: SELECT emp FROM Employee emp JOIN FETCH emp.client JOIN FETCH emp.unit WHERE emp.client.id = :clientId AND emp.formalName = :formalName], line 1, column 115: unknown state or association field [formalName] of class [de.bnext.core.common.entity.Employee]. Qs: What's wrong? Is it prohibited to use "artificial" properties in JPQL, here the WHERE clause? What are the premises here? I checked the capitalization and spelling many times, I'm out of luck.

    Read the article

  • How to do a timestamp comparison with JPA query?

    - by Robert
    We need to make sure only results within the last 30 days are returned for a JPQL query. An example follows: Date now = new Date(); Timestamp thirtyDaysAgo = new Timestamp(now.getTime() - 86400000*30); Query query = em.createQuery( "SELECT msg FROM Message msg "+ "WHERE msg.targetTime < CURRENT_TIMESTAMP AND msg.targetTime > {ts, '"+thirtyDaysAgo+"'}"); List result = query.getResultList(); Here is the error we receive: <openjpa-1.2.3-SNAPSHOT-r422266:907835 nonfatal user error org.apache.openjpa.persistence.ArgumentException: An error occurred while parsing the query filter 'SELECT msg FROM BroadcastMessage msg WHERE msg.targetTime < CURRENT_TIMESTAMP AND msg.targetTime {ts, '2010-04-18 04:15:37.827'}'. Error message: org.apache.openjpa.kernel.jpql.TokenMgrError: Lexical error at line 1, column 217. Encountered: "{" (123), after : "" Help!

    Read the article

  • i have some problem with left join JPQL

    - by Dora
    there is something wrong with ths way i use left join, and i dont understand what am i doing wrong. can you see it? select distinct r.globalRuleId, r.ruleId, sv.validFrom, pm.moduleId, nvl(min(rai.failedOnRegistration),0) from TRules r, TSlaVersions sv, TModuleFormulas mv, TPendingModule pm, left join TRulesAdditionalInfo rai on r.ruleId = rai.ruleId where r.slaVersionId = sv.slaVersionId and r.formulaId = mv.pk.formulaId and mv.pk.moduleId = pm.moduleId group by r.globalRuleId, r.ruleId, sv.validFrom, pm.moduleId order by pm.moduleId

    Read the article

  • JPA native query join returns object but dereference throws class cast exception

    - by masato-san
    I'm using JPQL Native query to join table and query result is stored in List<Object[]>. public String getJoinJpqlNativeQuery() { String final SQL_JOIN = "SELECT v1.bitbit, v1.numnum, v1.someTime, t1.username, t1.anotherNum FROM MasatosanTest t1 JOIN MasatoView v1 ON v1.username = t1.username;" System.out.println("get join jpql native query is being called ============================"); EntityManager em = null; List<Object[]> out = null; try { em = EmProvider.getDefaultManager(); Query query = em.createNativeQuery(SQL_JOIN); out = query.getResultList(); System.out.println("return object ==========>" + out); System.out.println(out.get(0)); String one = out.get(0).toString(); //LINE 77 where ClassCastException System.out.println(one); } catch(Exception e) { } finally { if(em != null) { em.close; } } } The problem is System.out.println("return object ==========>" + out); outputs: return object ==========> [[true, 0, 2010-12-21 15:32:53.0, masatosan, 0.020], [false, 0, 2010-12-21 15:32:53.0, koga, 0.213]] System.out.println(out.get(0)) outputs: [true, 0, 2010-12-21 15:32:53.0, masatosan, 0.020] So I assumed that I can assign return value of out.get(0) which should be String: String one = out.get(0).toString(); But I get weird ClassCastException. java.lang.ClassCastException: java.util.Vector cannot be cast to [Ljava.lang.Object; at local.test.jaxrs.MasatosanTestResource.getJoinJpqlNativeQuery (MasatosanTestResource.java:77) So what's really going on? Even Object[] foo = out.get(0); would throw an ClassCastException :(

    Read the article

  • How do I limit JPQ output?

    - by den-javamaniac
    I need to limit number of entities returned by a query to some certain value inside a JPA query (through JPQL). Particularly: select m from Manual m //constraint e.g. in sql (mysql syntax) I would do it like: select * from Manual limit 1 The only solution that comes up is simply to get all entities and then choose first one, which is out of the issue. Any ideas?

    Read the article

  • Compare two dates with JPA

    - by Kiva
    Hello everybody, I need to compare two dates in a JPQL query but it doesn't work. Here is my query: Query query = em.createQuery("SELECT h FROM PositionHistoric h, SeoDate d WHERE h.primaryKey.siteDb = :site AND h.primaryKey.engineDb = :engine AND h.primaryKey.keywordDb = :keyword AND h.date = d AND d.date <= :date ORDER BY h.date DESC"); My parameter date is a java.util.Date My query return a objects list but the dates are upper and lower to my parameter. Someone kown how to do this ? Thanks.

    Read the article

1 2  | Next Page >