Query on value of foreign key

I have two classes: Plan and InvestmentOption. Plan has a Collection of InvestmentOptions. In the DB, the INVESTMENT_OPTION table has a PLAN_OID column which is a foreign key to PLAN. PLAN's primary key is called OID.
Now suppose I have a Plan OID and I want to retrieve all InvestmentOptions within that Plan identified by the OID, without retrieving the Plan object. Here's the code:
int planOID = 1;
Expression expr = new ExpressionBuilder().get("plan").get("oid").equal(planOID);
session.readAllObjects(InvestmentOption.class, expr);
TopLink executes the following query:
SELECT t1.oid, t1.name, t1.plan_oid FROM plan t0
, investment_option t1 WHERE ((t0.oid = 1) AND (t0.oid = t1.plan_oid))
TopLink joins PLAN and INVESTMENT_OPTION even though that's not necessary - it would have been sufficient to say:
SELECT t1.oid, t1.name, t1.plan_oid FROM investment_option t1 WHERE (1 = t1.plan_oid)
One way to avoid the join is to add a plan_oid attribute to InvestmentOption, map INVESTMENT_OPTION.PLAN_OID to plan_oid as a read-only attribute, and modify the expression as follows:
Expression expr = new ExpressionBuilder().get("plan_oid").equal(planOID);
Is there another way to accomplish this without adding the read-only attribute?

You can define a query key[1] 'planId' on InvestmentOption for the PLAN_OID column. That'll let you write an expression like the one below which does not produce a join. The nice part about the query key is that it does not require you to add attributes to your object in order to query o them.
Expression plan = new ExpressionBuilder();
Expression where = plan.get("planId").equal(somePlanId);--Shaun
[1] http://www.oracle.com/technology/products/ias/toplink/doc/10131/main/_html/descfg010.htm#sthref3039

Similar Messages

  • Query Builder recognizing primary/foreign key

    Is there a way to have Query Builder recogninze the primary/foreign keys of the tables when they are selected? Right now it looks like you have to manually join the tables together by selected the column(s) to join.
    Thanks

    You can define a query key[1] 'planId' on InvestmentOption for the PLAN_OID column. That'll let you write an expression like the one below which does not produce a join. The nice part about the query key is that it does not require you to add attributes to your object in order to query o them.
    Expression plan = new ExpressionBuilder();
    Expression where = plan.get("planId").equal(somePlanId);--Shaun
    [1] http://www.oracle.com/technology/products/ias/toplink/doc/10131/main/_html/descfg010.htm#sthref3039

  • How to get multiple row data in single row for one value of foreign key

    i want to get data from a table in a way that all the emp_id corresponding to one manager_id
    in employee table come in one row. (emp_id is the primary key and manager_id is the foreign key) Since there are different emp_id whose manager_id is same
    so how can i get all the emp_id in one row .

    One way with 10g:
    select mgr,
           rtrim(xmlagg(xmlelement(empno,empno||',').extract('//text()')),',')  emps
    from emp
    where mgr is not null
    group by mgr;10g:
    -- define this function:
    create or replace
    function concatenate(c Sys_refcursor, sep varchar2 default null) return varchar2
    as
      val varchar2(100);
      return_value varchar2(4000);
    begin
    --  open c;
      loop
      fetch c into val;
      exit when c%notfound;
      if return_value is null then
        return_value:=val;
      else
        return_value:=return_value||sep||val;
      end if;
      end loop;
      return return_value;
    end;
    select mgr,
           concatenate(cursor(select empno from emp e where e.mgr=emp.mgr order by empno),',')
    from emp
    where mgr is not null
    group by mgr;With 11g:
    select mgr,
           listagg(empno,',') within group (order by empno) emps
    from emp
    where mgr is not null
    group by mgr;

  • Foreign key constraint on multi-column primary key accepts 1 empty column!?

    Hi, we have a reference table with a two-column primary key. In the child table there is a non-mandatory foreign key constraint to this table. So if both child columns are null it's ok too. But now we see that if one of the two child table columns that build up the foreign key is null, the other column can have any (non-existant in the master-tabel) value you like!? That does not make sense.
    Can anyone explain this to me???
    Regards, Paul.

    Paul, I believe that this is in accordance to the ANSI SQL standard requirement for the treatment of nulls in a multi-column FK. In any case Oracle specifically states this is the way FK work From the 10 Concepts manual, Ch 21 Data Integrity, topic Nulls and Foreign Keys:
    The relational model permits the value of foreign keys either to match the referenced primary or unique key value, or be null. If any column of a composite foreign key is null, then the non-null portions of the key do not have to match any corresponding portion of a parent key. <<HTH -- Mark D Powell --

  • Question about scripting of foreign keys

    When I script FK_SalesOrderHeader_Address_BillToAddressID key from AdventureWorks.[Sales].[SalesOrderHeader] I get this:
    ALTER TABLE [Sales].[SalesOrderHeader] WITH CHECK ADD CONSTRAINT [FK_SalesOrderHeader_Address_BillToAddressID] FOREIGN KEY([BillToAddressID])
    REFERENCES [Person].[Address] ([AddressID])
    GO
    ALTER TABLE [Sales].[SalesOrderHeader] CHECK CONSTRAINT [FK_SalesOrderHeader_Address_BillToAddressID]
    GO
    EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Foreign key constraint referencing Address.AddressID.' , @level0type=N'SCHEMA',@level0name=N'Sales', @level1type=N'TABLE',@level1name=N'SalesOrderHeader', @level2type=N'CONSTRAINT',@level2name=N'FK_SalesOrderHeader_Address_BillToAddressID'
    GO
    What is second ALTER statement for (the one highlighted with bold font)? First ALTER statement already includes WITH CHECK, so isn't the second one redundant?

    The 2nd Statement enables the Foreign Key.
    I think it is redundant because FOREIGN KEY is enabled by default when you execute the 1st statement.
    This script is generated by SSMS (Yes?), This is added just to ensure that CONSTRAINT is enabled.
    - Vishal
    SqlAndMe.com
    Yes, it is generated by SSMS 2008.

  • Logical foreign key display values

    I have a schema in which the primary keys are auto generated numbers. Foreign keys exist from child tables to the primary key of the parent.
    I have figured out how to change auto generated forms to display a dropdown list of display/values to the user on insert or update instead of the meaningless number.
    What I can't figure out how to do is have the generated report show the display that I am looking for without losing the ability to edit the child record. As soon as I manipulate the query to include another table I lose the icon in the application to edit the row.
    Is it possible to keep the edit icon on the report while showing logical values instead of actual ones?
    Thanks in advance,
    Chris S.

    We'll use a football analogy because it's time for the ployoffs.
    Let's create a TEAMS table and a DIVISIONS table.
    TEAMS consists of:
    TEAM_ID NUMBER -> PK
    LOCATION VARCHAR2(35)
    TEAM_NAME VARCHAR2(35)
    and DIVISIONS consists of:
    DIVISION_ID NUMBER -> PK
    DIV_NAME VARCHAR2(35)
    Now there can't just be a link from a team to a division because they move around a bit. The Detroit Lions used to be in the NFC Central. That doesn't exist anymore and now they are in the NFC North. (Please set aside the fact that the NFC should be a part of the conferences table).
    This means that I would create a table to link the TEAM record to a DIVISION record with the season that the team became a part of the division and potentially the last season that they were in that division. This table will be called DIVISION_TEAM_XREF and looks like this:
    LINK_ID NUMBER -> PK
    DIVISION_ID NUMBER -> FK(DIVISIONS.DIVISION_ID)
    TEAM_ID NUMBER -> FK(TEAMS.TEAM_ID)
    SEASON_EFF NUMBER(4) (actually a year maybe a VARCHAR2 would be better)
    SEASON_TERM NUMBER(4) (nullable)
    Now I created all of that through HTML DB with foreign keys from the XREF table to the teams and divisions tables. Then I create an application throught the application builder. I choose report and form and the application type like the demo. for each of the three tables. Choose a theme and walah there is an application with all three tables. If I add data to TEAMS or DIVISIONS I can see them in the report page that is created and there is an icon to the left of each row which when clicked will allow me to edit the row.
    The problem comes with my XREF table. The creation screen is just a form which expects me to know the auto generated number that was created for my division and team. I have figured out how to change this in the application builder so that it is a drop down list built from a query of the respective table.
    Once I create a record I can see it in the report page for the XREF table. This page has the option to edit the record but the values on the screen are the auto generated numbers that don't mean anything to a user. When I change this page to use display values from the parent tables I lose the edit icon.
    Here is the original query that the application builder used:
    select
    "LINK_ID",
    "DIVISION_ID",
    "TEAM_ID",
    "SEASON_EFF",
    "SEASON_TERM"
    from "DIVISION_TEAM_XREF"
    and here is what I would like to change it to:
    select
    XREF.LINK_ID "LINK_ID",
    DIV.DIV_NAME "DIVISION",
    TEAM.TEAM_NAME "TEAM",
    XREF.SEASON_EFF "SEASON_EFF",
    XREF.SEASON_TERM "SEASON_TERM"
    from "DIVISION_TEAM_XREF" XREF, DIVISIONS DIV, TEAMS TEAM
    where XREF.DIVISION_ID = DIV.DIVISION_ID
    and XREF.TEAM_ID = TEAM.TEAM_ID
    Sorry for the long post. Hope that clarifies.
    Chris S.

  • Filtering a Query result for a specific value of a key figure

    Hi folks,
    I want to filter a query for a specific value of a key figure. The report should display all customer who has an account balance greater than EUR 500'000.
    Can I only implement this kind of filter via a condition in Query-Designer? If I run that query on an InfoCube with non-cumulative key figures over all our customers (> 400'000) I have problems with the consumption of the memory. If I restrict the amount of the customers to 50'000 - 60'000 then it works. It seems that the query reads all customer records in an internal table before applying the condition.
    Is there another way to deal with? Any help appreciated.
    Kind regards
    Hansjörg Luzi
    Graubündner Kantonalbank
    CH-7002 Chur

    You could try to implement an alternative solution: define a new Characteristc with discrete values (in the following example I suppose to have intervals of 10)
    KF -> CHAR
    115 -> 110 (110 <= KF < 120)
      5 ->   0 (  0 <= KF <  10)
    83 ->  80 ( 80 <= KF <  90)
    Then you can use these dicrete values to filter ...
    I know that it's not so "flexible" (discetization must be predefined), but query response time is quicker and you can use Aggregates ...
    Hope it helps
    GFV

  • Unable to create foreign key: InvalidArgument=Value of '0' is not valid for 'index'. Parameter name: index

    I am running an SQL(CE) script to create a DB. All script commands succeed, but the DB get "broken" after creating the last costaint: after running the script, viewing table properties of Table2 and clicking on "Manage relations" gives the following error: Unable to create foreign key: InvalidArgument=Value of '0' is not valid for 'index'. Parameter name: index. Wondering what does that refer to...
    Here it is the script. Please note that no error is thrown by running the following queries (even from code that passing the queries by hand, one-by-one to sql server management studio).
    CREATE TABLE [table1] (
    [id_rubrica] numeric(18,0) NOT NULL
    , [id_campo] numeric(18,0) NOT NULL
    , [nome] nvarchar(100) NOT NULL
    GO
    ALTER TABLE [table1] ADD PRIMARY KEY ([id_rubrica],[id_campo]);
    GO
    CREATE UNIQUE INDEX [UQ__m_campi] ON [table1] ([id_campo] Asc);
    GO
    CREATE TABLE [table2] (
    [id_campo] numeric(18,0) NOT NULL
    , [valore] nvarchar(4000) NOT NULL
    GO
    ALTER TABLE [table2] ADD PRIMARY KEY ([id_campo],[valore]);
    GO
    ALTER TABLE [table2] ADD CONSTRAINT [campo_valoriFissi] FOREIGN KEY ([id_campo]) REFERENCES [table1]([id_campo]);
    GO
    Sid (MCP - http://www.sugata.eu)

    I know this is kind of old post, but did this realy solved your problem?
    I'm getting this same error message after adding a FK constraint via UI on VS2008 Server Explorer.
    I can add the constraint with no errors, but the constraint is not created on the DataSet wizard (strongly typed datasets on Win CE 6) and when I click "Manage Relations" on the "Table Properties" this error pop out:
    "InvalidArgument=Value or '0' is not valid for 'index'.
    Parameter name: index"
    Even after vreating my table with the relation in SQL the same occurs:
    CREATE TABLE pedidosRastreios (
        idPedidoRastreio INT NOT NULL IDENTITY PRIMARY KEY,
        idPedido INT NOT NULL CONSTRAINT FK_pedidosRastreios_pedidos REFERENCES pedidos(idPedido) ON DELETE CASCADE,
        codigo NVARCHAR(20) NOT NULL

  • Query the name of the parent table in a foreign key constraint

    Hello,
    Does anyone know how to query for the parent table name in a foreign key constraint? I don't see that relationship in ALL_CONS_COLUMNS or ALL_CONSTRAINTS.
    Thanks in advance,
    Michael

    or try this...
    SELECT rc.TABLE_NAME "PK_Table_Name",cc.TABLE_NAME "FK_Table_Name",
           case when cc.column_name = rc.column_name
                then c.TABLE_NAME || '(' || cc.COLUMN_NAME || ')'
                else r.TABLE_NAME || '(' || rc.COLUMN_NAME || ') = ' ||c.TABLE_NAME || '(' || cc.COLUMN_NAME || ')' end as "TABLE_NAME(COLUMN_NAME)"
    from all_constraints c,
         all_constraints r,
         all_cons_columns cc,
         all_cons_columns rc
    WHERE
         r.table_name = upper('emp')
    and      c.CONSTRAINT_TYPE = 'R'
    and     c.R_OWNER = r.OWNER
    and     c.R_CONSTRAINT_NAME = r.CONSTRAINT_NAME
    and     c.CONSTRAINT_NAME = cc.CONSTRAINT_NAME
    and     c.OWNER = cc.OWNER
    and     r.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
    and     r.OWNER = rc.OWNER
    and     cc.POSITION = rc.POSITION
    ORDER BY r.TABLE_NAME;

  • Query Builder - foreign key relationships not showing automatically

    Is it standard functionality in APEX that foreign key to primary key relationships are not shown in Query Builder when choosing related tables? Do you always have to join FKs to PKs manually (i.e. using control click) whenever you create joins in queries? In Oracle forms and SQL Developer the foreign key constaints are always draw in automatically. Any reason why this is not part of APEX's query builder as well? It's such a hassel to have to put them in each time when the relationships could easily be read directly from the data dictionary constraints.
    regards
    Paul P

    bump...

  • Dimension foreign key on Fact gets updated with same value

    Hi All,
    I'm hoping someone has at least seen this problem and can provide insight.
    Background:
    - We are on OWB 10.2
    - Fact table is Billing_F
    - Fact table has foreign keys to Customer_Dim, SalesOrg_Dim, Time_Dim, etc.
    - Fact table has update mode Update/Insert
    Once in a while, every row in the Billing Fact gets updated with the SAME SalesOrg_Dim foreign key column value. In other words, the data would look like:
    Before:
    Line ID Amt SalesOrg_Key
    1 100 19241
    2 200 21925
    3 140 08585
    After:
    Line ID Amt SalesOrg_Key
    1 100 12345
    2 200 12345
    3 140 12345
    *** The Source tables contain values in the Before table. ***
    We can't reproduce this on a consistent basis. The only way to "correct" the data is to rerun the mapping from source -> staging -> fact again. No other change.
    Please, has anyone else at least experienced this problem? If so, how were you able to fix it permanently?
    Any help is greatly appreciated!
    irene

    Hi Irene
    Difficult to help here without reviewing your mappings/schedule but does SalesOrgKey 12345 represent a particular value e.g. Unknown, Default?
    I suspect it's something to do with your load order in that the data in the dimension is not available/ready when the fact is loaded and therefore a default value is being inserted. When the fact load is rerun I'm guessing the load of the dimension has finished and therefore the key lookup returns the proper keys from the dimension. Is the dimension truncated and reloaded?
    Regards
    Si

  • Hi, Cant use Query builder in Apps. Because there is no Foreign Keys define

    Hi,
    We Cant use any Query Builder (SqlDeveloper) in Oracle Apps.
    Because there is no Foreign Keys defined on the table except primary key.
    I agree that common colums are there on different table,
    But it's bit difficult to digout for numbers of tables from different modules (schema).
    Do any one have any query which can find common colums from different tables though the tables may or may not be from different Schemas too.
    Thanks in advance.
    Bachan

    >
    Due to performance oracle has not applied constraints
    on tables except Primary Key.
    I find this hard to believe. The most likely reason for this, is to speed up inserts, but thats only applicable if you have lots of inserts at the same time.
    But they have given eTRM to refer the forigen columns
    on different tables.
    Forigen column is just for name shake there is no
    constraint available except Primary key.
    And whenever we have to make query and apply join, we
    have to dig a lot.
    Even we cant use Sqldeveloper Query builder, which is
    a dam good tool for making Joins and query.
    My problem is the Time and effort which we have to
    put for diging tables.
    just want to reduce that with some intleactual
    Query.You will get quicker as you get more experienced. Of course, everytime you have a query to do a specific job you could save it in an appropriately named file and store it in your source control system.
    >
    Can u help me with names of the Tables which store
    information about tables, schema, columns, index, and
    views.select * from dictionary

  • How to transfer database table contain null values, primary key, and foreign key to the another database in same server. using INSERT method.

    how to transfer database table contain null values, primary key, and foreign key to the another database in same server. using INSERT method.  thanks

    INSERT targetdb.dbo.tbl (col1, col2, col3, ...)
       SELECT col1, col2, col3, ...
       FROM   sourcedb.dbo.tbl
    Or what is your question really about? Since you talke about foreign keys etc, I suspect that you want to transfer the entire table definition, but you cannot do that with an INSERT statement.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • How to insert value for composed foreign key?

    My problem when I update or insert to table Ffclient which has link 1-1 with other table ClientLoan by composes primary key loanId and clienId (break table). I auto mapping by Jdeveloper 10g version 10.1.2. In FfClient table has two fields compose foreign key of ClientLoan as loanId and clienId not nullable. In toplink object Ffclient it only has one reference ClientLoan object by clientLoan field, not has two fields loanId and clienId . When I insert or update to database, I can't set value for these two fields direct so I have created new ClientLoan object and set value for composed primary key loanId and clienId, after that set it to object Ffclient. But when I update or insert to database it occurs exception about insert null for two not nullable fields: loanId and clienId.
    Any one has error as mime? Any one help me correct my error.
    Thanks in advance.
    Mapping is:
    ….
    <database-mapping>
    <attribute-name>ffclientCollection</attribute-name>
    <read-only>false</read-only>
    <get-method-name>getFfclientCollection</get-method-name>
    <set-method-name>setFfclientCollection</set-method-name>
    <reference-class>uk.co.lsb.elb.toplink.Ffclient</reference-class>
    <relationship-partner-attribute-name>clientLoan</relationship-partner-attribute-name>
    <is-private-owned>false</is-private-owned>
    <uses-batch-reading>false</uses-batch-reading>
    <indirection-policy>
    <mapping-indirection-policy>
    <type>oracle.toplink.internal.indirection.TransparentIndirectionPolicy</type>
    </mapping-indirection-policy>
    </indirection-policy>
    <container-policy>
    <mapping-container-policy>
    <container-class>oracle.toplink.indirection.IndirectList</container-class>
    <type>oracle.toplink.internal.queryframework.ListContainerPolicy</type>
    </mapping-container-policy>
    </container-policy>
    <source-key-fields>
    <field>LSB.CLIENT_LOAN.CLIENT_ID</field>
    <field>LSB.CLIENT_LOAN.LOAN_ID</field>
    </source-key-fields>
    <target-foreign-key-fields>
    <field>LSB.FFCLIENT.CLIENT_ID</field>
    <field>LSB.FFCLIENT.LOAN_ID</field>
    </target-foreign-key-fields>
    <type>oracle.toplink.mappings.OneToManyMapping</type>
    </database-mapping>
    …..
    <database-mapping>
    <attribute-name>clientLoan</attribute-name>
    <read-only>false</read-only>
    <reference-class>uk.co.lsb.elb.toplink.ClientLoan</reference-class>
    <relationship-partner-attribute-name>ffclientCollection</relationship-partner-attribute-name>
    <is-private-owned>false</is-private-owned>
    <uses-batch-reading>false</uses-batch-reading>
    <indirection-policy>
    <mapping-indirection-policy>
    <type>oracle.toplink.internal.indirection.BasicIndirectionPolicy</type>
    </mapping-indirection-policy>
    </indirection-policy>
    <uses-joining>false</uses-joining>
    <foreign-key-fields>
    <field>LSB.FFCLIENT.CLIENT_ID</field>
    <field>LSB.FFCLIENT.LOAN_ID</field>
    </foreign-key-fields>
    <source-to-target-key-field-associations>
    <association>
    <association-key>LSB.FFCLIENT.LOAN_ID</association-key>
    <association-value>LSB.CLIENT_LOAN.LOAN_ID</association-value>
    </association>
    <association>
    <association-key>LSB.FFCLIENT.CLIENT_ID</association-key>
    <association-value>LSB.CLIENT_LOAN.CLIENT_ID</association-value>
    </association>
    </source-to-target-key-field-associations>
    <type>oracle.toplink.mappings.OneToOneMapping</type>
    </database-mapping>

    Yes, many thanks for you reply.
    My project has many layer (include DAO + EJB + BO + WEB).
    Toplink objects which are auto created by TopLink has only using in DAO and EJB layer, then toplink objects are transfer to Bean objects (valueObject) which are contain primitive java type as int, long, double... not java wrapper object as Integer, Long, Double... Bean objects are using from EJB to WEB layer. So when set value to bean object from toplink object I sometime don't set all reference toplink object to reference object of bean (although bean has references bean object as toplink object) because there are too big. So when I update data from WEB layer to EJB layer, before update to database, I must get fill all data for foreign key of update object by create new reference toplink object, add reference_id to this object and set it to update object. I waste a lot of time, its very handwork and tire. Are you has any solution about this problem?
    Thank in advanced.
    ThangNQ

  • Update query with multiple foreign key parameters

    I am trying to perform an update query on one field that uses multiple foreign key parameters from one table to update the other table. The data in all three foreign key parameter fields are not constant. Accuracy is absolutely critical. I tied this as well as other various scenarios with no success. Can anyone help?
    Update A_table a
    set a.rate = (
    select b.rate
    from B_table b
    where b.id = a.id
    and b.transdate = a.transdate
    and b.orgnum = a.orgnum
    and b.transdate = to_date('31/12/2007', 'dd/mm/yyyy')
    )

    I would check symbols by a user name and number of posts before calling anyone a hot shot, especially damorgon.<br><br>
    Yes version matters (due to bugs and features in each version).<br>
    DDL matters because of indexes and associations.<br>
    Data matters because it makes a difference on how SQL can be written.<br>
    Reasons why an SQL statement don't work is because we aren't looking over your shoulder at your screen.<br><br>
    damorgon did leave off his list that the best place for this question is on the PL/SQL, where they will ask you similar questions in addition to your explain plan and data volumes.

Maybe you are looking for

  • Why can't I print WORD documents created on my MACBOOK from a PC?

    Our daughter is unable to print documents created on her MACBOOK from a PC.  She has been saving her documents as WORD files, but the PCs in the university computer lab still do not recognize the document, and consequently she cannot print them from

  • Gallery in which user can choose pictures and submit

    HI, Im a begginer, so please be patient;) I want to build an online gallery - very simple, only thumbnails - in which I upload pictures and the viewer can choose the pictures he wants and press a submit button. This will send me an email with the nam

  • Oracle on Linux recommendations

    Hello, I'm looking to migrate our Oracle installation from Windows to Linux. I am an experienced Linux administrator and architect, and I am also very familiar with SAN storage, but have not looked at the details of implementing Oracle on Linux befor

  • Maxify MB5320 How do I make a duplex document flippable ( reverse side upside down)

    I have a 40 page docuiment, in landscape mode, that I duplex. The doc. will be placed in a binder and when the reader reads it he/she will flip the pages top to bottom. I wish to print the reverse side of each page  upside-down so the reader will not

  • Registrating photos

    iWeb is not registrating some of the pictures I import from iphoto : it shows a commentary saying : these documents such and such are missing. Although I have saved them in the preceding sessions.