JPA query by entity/object ?
I am trying to write an abstract API which dynamically assigns any Entity Class that needs to be persisted and retrieved using the Entity Manager.
Saving into the database is not a problem, I just do entityManager.save(Class) and it works for any class that needs to be persisted.
However, when querying for the object based upon the attributes, I want to avoid naming particular attributes and want to use the Entity class's attributes against itself for querying.
For example, the client program will say something like this to query by name and age of a Person:
-------calling (client) program: ---
Person p = << get from UI, not saved yet, no Id but has all other attributes like name and age etc. >>
List<Person> persons = dao.getAllThatMatch(p);
--- end client Program --
--- DAO class ---
List<T> getAllThatMatch(T t) { //note that expectation is that returned is a list of Object which is the same as the querying object
List<T> entityList = em.someFinderMethod(t);
//the someFinderMethod method should automatically query for all Person objects that match the attributes provided by the object of Person supplied as criteria
//NOTE: there is no attribute mentioned extensively like name, age etc.
return entityList ;
-- end DAO class --
Edited by: user7626479 on Feb 6, 2013 3:55 PM
Edited by: user7626479 on Feb 6, 2013 3:55 PM
Query by example is not included in the JPA standard, but it is possible to do with EclipseLink.
See http://wiki.eclipse.org/EclipseLink/Examples/JPA/ORMQueries#Query_By_Example
for how to use query by example with native EclipseLink queries. To execute a native query through JPA, you will need to call createQuery(DatabaseQuery query) on the org.eclipse.persistence.jpa;JpaEntityManager obtained from the javax.persistence.EntityManager instance by calling getDelegate() or unwrap.
Best Regards,
Chris
Similar Messages
-
Using JPA Entity-Objects defined in other EJB-Development Component
Hello Community,
I'm working on a Java-Application on NW CE 7.1, using JEE5 Beans in the Business-Logic-Layer and WebDynpro/Java in the UI-Layer.
I designed a Bean for working with data, stored in a database-table of the system-database.
For that addtionally i created a class, representing the Entity-Object, in the same Development-Component of Type EJB 3.0.
It looks like this:
@NamedQueries ({
@NamedQuery (name="findAllSdCust", query="SELECT c from SdCust c ORDER BY c.kdnr"),
@NamedQuery (name="findSdCustByKdnr", query="SELECT c from SdCust c WHERE c.kdnr = :kdnr"),
@NamedQuery (name="findSdCustByIlnnr", query="SELECT c from SdCust c WHERE c.ilnnr = :ilnnr")
@Entity
@Table(name="ZKALL_SD_CUST")
public class SdCust implements Serializable {
@Id
@TableGenerator (name="idGenerator", table="ZKALL_ID_GEN", pkColumnName="GEN_KEY", valueColumnName="GEN_VALUE", initialValue=100)
@GeneratedValue (strategy=GenerationType.TABLE, generator="idGenerator")
private long id;
private String name;
private String lname;
private String kdnr;
private String ilnnr;
private long connid;
private long cnt;
@Version
private long version;
Constructor, Getter and Setter methods follow here
The corresponding bean looks like this
@Stateless(name="SdCustBean")
public class SdCustBean implements SdCustLocal {
@PersistenceContext (unitName="xyz")
private EntityManager em;
public SdCust getSdCustByKdnr (String kdnr)
SdCust result = new SdCust();
// List<Manufacturer> resultList = new ArrayList<Manufacturer>();
Query myQuery = em.createNamedQuery("findSdCustByKdnr");
myQuery.setParameter("kdnr", kdnr);
result = (SdCust) myQuery.getSingleResult();
return result;
public void setEM (EntityManager iem)
em = iem;
// other methods .....
After that i created a new Development-Component of Enterprise Application-Type and added above DC to this EAR-DC. I also supplied the nessecary descriptor-files/Enries in EJB-DC and EAR-DC.
When now using this bean from WebDynpro with the Web-Dypro EJB-Model-Import everything works fine.
The bean returns the desired object(s).
But now i created a new DC of type EBJ 3.0
This DC contains a Message Driven Bean. That MDB is a Job-Bean which i want to schedule. That Bean uses JRA to connect to an SAP-Abap-System to read some Data and should use JPA to insert/upate/delete the read data in the Database. This should work as a simple replication for my application.
I assigned that EJB-DC containing the MDB to a new EAR-DC together with job-definition-xml and the neccessary entries in deployment-descriptors.
After deploying i see the corresponding job-defition in the NW scheduler using the administrator-views.
I'm also able to schedule the job and it executes fine. Connecting to SAP-Abap System also works fine using JRA.
But JPA does not work!!!!!
I created an dependency from my EAR-DC containing the Job EJB-DC and to the EJB-DC containing the Entity-Class.
I tried three diferent things to get i running, but all of them failed.
1.)
The part looks like:
public class MasterDataReplicateJobBean extends MDBJobImplementation implements MessageListener
@EJB SdCustBean mybean;
public void onJob(JobContext ctx) throws Exception {
SdCust sdCust = mybean.getSdCustByKdnr (mykdnr);
Compiles fine. But this fails because the Data is stored in the system-database. The exception says, that i have to use a datasource which supports 2-Phase commit. I know, that i could possibly solve this problem by annotation the Method getSdCustByKdnr with the Annotation for the Transaction-Manager to use REQUIRES_NEW Transaction. But i dont want to generally annotate my methods this way.
2.)
This part looks like this
public class MasterDataReplicateJobBean extends MDBJobImplementation implements MessageListener
@PersistenceContext (unitName="xyz")
private EntityManager em;
public void onJob(JobContext ctx) throws Exception {
SdCust cust = new SdCust();
Query myQuery = em.createQuery("SELECT c from SdCust c WHERE c.kdnr = :kdnr");
myQuery.setParameter("kdnr", dbkdnr);
cust = (SdCust) myQuery.getSingleResult();
This also results in a runtime-exception because the entity-Manager cant resolve SdCust from the Query as an Object. The Exception is:
java.lang.IllegalArgumentException: line 1: Abstract Schema Type 'SdCust' doesn't exist
SELECT c from SdCust c WHERE c.kdnr = :kdnr
3.) and last try so far:
public class MasterDataReplicateJobBean extends MDBJobImplementation implements MessageListener
@PersistenceContext (unitName="xyz")
private EntityManager em;
public void onJob(JobContext ctx) throws Exception {
SdCustBean custBean = new SdCustBean();
custBean.setEM(em);
SdCust cust = custBean.getSdCustByKdnr(kdnr);
In this example i use the Bean from the beginning not as a bean itself but as a normal class. that class has an addtional Method setEM to set the Entity-Manager (which is injected when using the class as a bean)
In that way i got the exception, that the named Query "findSdCustByKdnr" cannot be found by the entity-manager.
It seems to me, that i can access the class, but that all annotations belonging to JPA for that class are not recognized.
Does anybody can give me a hint to solve this problem? Did i forgot something important?
best regards
matthias hayk
Edited by: Matthias Hayk on Feb 5, 2009 9:38 AMI was already on wright trace.
My class "SdCust" was not recognized by the Entity-Manager as an Entity-Class.
This relies on the storage of the entity-class and where the Entity-Manager looks for entity-classes.
By default it seems to look for all classes in the same jar file. thats the reason why everything works fine when the using bean and the entity-class are in the same project.
In my last case, the using bean is in another development-component and so also in anohter jar file. in this case the entity-manager must be told where to find entity-classes.
this is done in the persistence.xml file.
i added the line
<jar-file>xxx.yyy.com~mdata_beans.jar</jar-file>
underneath the <persistence-unit>-tag.
This works.
regards
Matthias Hayk -
Customizing Entity Object SQL Query prior to Insert?
I am using an ADF BC Entity Object to store values from a multi-page form input process.
At the end of the process, I plan to call a method that will programmatically take the values from the Entity Object and insert a new row to the database. I need to customize the query to add an encryption function to the insert for one of the fields. For example, instead of 'INSERT password' I need the SQL to be 'INSERT encrypt_fct(password)'.
Is this possible and if so how?
thanksHi javaX
Easiest way of achieving this in ADF BC is overriding the doDML method in your underlying EO's EntityImpl class. The following gives an example, assuming a table called users with username & password columns, where you wish to encrypt the password column with a SQL function named encrypt_fc:
protected void doDML(int operation, TransactionEvent transactionEvent) {
if (operation == DML_INSERT) {
CallableStatement statement = null;
String insertDML =
"INSERT INTO users (username, password) VALUES (?,encrypt_fc(?))";
statement =
getDBTransaction().createCallableStatement(insertDML, 1);
try {
// Bind the statement parameters and execute the statement
statement.setString(1, getUsername().toString());
statement.setString(2, getPassword().toString());
statement.execute();
} catch (Exception ex) {
throw new oracle.jbo.JboException(ex);
} finally {
try {
statement.close();
} catch (Exception nex) {
/* Ignore */
} else // operation == DML_UPDATE || DML_DELETE
super.doDML(operation, transactionEvent);
}Another way is to include the code for your encrypt function in your ADF model project. By this I mean convert the encrypt function to Java, then add it as a piece of code to your EntityImpl or a more generic library if needed elsewhere. This way you don't have to modify the doDML, but rather the EO setter routine to call your encyption function, and the unencrypted password isn't passed between ADF and the DB.
Hope this helps.
CM. -
JPA Query set parameter list of objects
Hi Experts,
Currently i am looking for the resolution to the the following JPA Query. I am sure you guys already came across the answer for that. Please help me to spot some light.
Assume a relation Employees --> Departments. I have list of department and i would like to get all the employees belong to the departments. I was trying using the following JPA query
Select o from EmployeeEntity where o.deparment IN ( :departments ) then set the parameter value to the List of department objects. Now i am getting the following exception
at org.eclipse.persistence.exceptions.QueryException.invalidOperatorForObjectComparison(QueryException.java:598)
at org.eclipse.persistence.internal.expressions.RelationExpression.normalize(RelationExpression.java:388)
at org.eclipse.persistence.internal.expressions.CompoundExpression.normalize(CompoundExpression.java:218)
Any hit ?
ThanksHi,
You can try the following query
select e from Employees e where e.Departments.departmentid in (:deptno)
then set the parameter value to the List of departmentid
Thanks -
Problem to give default value in entity object using query
hi,
i have one entity object and i want to set default value of attribute like division which is based on employee code.
entity object based on table leavedetail and using refrence table employee_hdr(empcode ,division).
so how can i set default value of division attribute which is based on empcode attribute using SQLwell,
yes user, fetish nailed correctly.
make some viewlink.
something like says as example.
department vo
employee vo
make viewlinks between those vo's
important thing: exposed then source and destination accesor.
use groovy :
go to employee vo - create Department name field ( as transiest)
use this statement default value expersion type.
DepartmentView1.DepartmentName
it will get the value. check over.
so this example well suits to your scenario.
i hope this will helps you.
well create is an video. to get the value using groovy.
http://www.youtube.com/watch?v=mpHV4x89a_A
Edited by: ADF7 on Apr 14, 2012 5:46 AM -
What to be targetted by JPA query?
In JPA the SELECT query is against entity objects, but the UPDATE against DB records, aren't they?
i coded some basic JPA staff, then found that the getResultList() method to SELECT query always returned the latest states of entity objects but not of DB records, in contrast the executeUpdate() method to UPDATE query always changed the values of DB records but not of entity objects.
Unfortunately i couldn't prove it from JPA Spec directly. What are the reasons behind? Pls correct me if i were wrong. Thx!
Edited by: solfan on Jun 24, 2009 3:26 AMI suggest you first study and understand fully what the relation between a "transaction", an "entity manager" and a "managed entity" is, before you make any further assumptions.
-
Hello world,
I'm new to JPA 2.0 and there are few things I don't understand.
BTW: I can't figure out the keywords to search for this question, so please pardon me if it's one of the most asked.
Using the Preview, I've seen that alignment went straight to Hell, so I tried to make this as readable as I could using pipes in place of white spaces in the result sets.
I have a couple of tables:
CUST table (for customers):
CUST_ID (pk, integer)
CUST_NAME (varchar)
ORD table (for orders):
ORD_ID (pk, integer)
ORD_STATUS (char) can be: N for new, S for shipped, D for delivered
CUST_ID (fk, integer)
The relationship is, of course, a "one to many" (every customer can place many orders).
Content of the tables:
CUST_ID|CUST_NAME
1|elcaro
2|tfosorcim
3|elppa
ORD_ID|ORD_STATUS|CUST_ID
2|N|1
3|N|1
4|N|1
5|S|1
6|S|1
7|D|1
8|D|1
9|D|1
10|D|2
11|N|2
12|S|3
13|S|3
Here's how I annotated my classes:
Customer.java:
@Entity(name = "Customer")
@Table(name = "CUST")
public class Customer implements Serializable
private static final long serialVersionUID = 1L;
@Id
@Column(name = "CUST_ID")
private Integer id;
@Column(name = "CUST_NAME")
private String name;
@OneToMany(mappedBy = "customer")
private List<Order> orders;
// Default constructor, getters and setters (no annotations on these)
Order.java:
@Entity(name = "Order")
@Table(name = "ORD")
public class Order implements Serializable
private static final long serialVersionUID = 1L;
@Id
@Column(name = "ORD_ID")
private Integer id;
@Column(name = "ORD_STATUS")
private Character status;
@ManyToOne
@JoinColumns
@JoinColumn(name = "CUST_ID", referencedColumnName = "CUST_ID")
private Customer customer;
// Default constructor, getters and setters (no annotations on these)
Everything works just fine, the following JPQL query yields the results I expected:
select c from Customer c
it returns three objects of type Customer, each of which contains the orders that belong to that customer.
But now, I want to extract the list of customers that have orders in status 'N', along with the associated orders (only the status 'N' orders, of course).
Back in the good ol' days I would have written an SQL query like this:
select c.cust_id, c.cust_name, o.ord_id, o.ord_status
from cust c
inner join ord o on (o.cust_id = c.cust_id)
where o.ord_status = 'N'
and it would have returned the following result set:
CUST_ID|CUST_NAME|ORD_ID|ORD_STATUS
1|elcaro|2|N
1|elcaro|3|N
1|elcaro|4|N
2|tfosorcim|11|N
The following JPQL query, however, doesn't yield the expected results:
select distinct c from Customer c join c.orders o where o.status = 'N'
it returns the correct set of customers (customer 'elppa' doesn't have any status 'N' order and is correctly excluded), but each customer contains the full set of orders, regardless of the status.
It seems that the 'where' clause is only evaluated to determine which set of customers has to be extracted and then the persistence provider starts to navigate the relationship to extract the full set of orders.
Thinking a little about it, I must admit that it makes sense.
I then tried out another JPQL query:
select c, o from Customer c join c.orders o where o.status = 'N'
this JPA query yields results that are similar to the ones produced by the previous SQL query: each result (4 results as expected) is a 2-object array, the first object is of type Customer and the second object is of type Order. But, again, the objects of type Customer contain the full set of related orders (as I expected, this time). Not to mention the fact that now the orders are not contained in the Customer objects, but are returned separately, just as in an SQL result set.
Now the question is:
Is it possible to write a JPA query that filters out, not only the customers that don't have an order in status 'N', but the related orders (fetched during relationship navigation) that are not in status 'N' as well?
What I'd like to be able to get is a 2-customer result where each customer contains only its status 'N' orders.
I read the Java EE 6 Tutorial and one of the examples (the Order Application) has a schema that is similar to mine, but I couldn't find a query like this (in the downloaded source code).
Although I think the above is standard behavior, I use an Oracle Weblogic 12c server (through its Eclipse adapter) and the persistence provider appears to be EclipseLink.
Thanks in advance.
Best regards,
Stefano
Edited by: user11265230 on 17-apr-2012 14.11Hello,
When returning an entity from JPQL, it gives you the entity as it is in the database. Your "select distinct c from Customer c join c.orders o where o.status = 'N'" is asking for all customers that have an order with a status of 'N', so that is what it gives you. There is no condition to filter anything on the relationship when building the Customer object in JPA - doing so would mean returning a managed entity that does not reflect what is in the database. This would affect other queries, since JPA requires that queries return the same instance of an entity regardless of the query that is used to bring it back. So a query using your "where o.status = 'N'" would cause conflicting results when used with a query using "where o.status = 'Y'". And these queries would make the EntityManager unable to determine what has changed on the returned objects.
EclipseLink does have the ability to filter over relationships, it is just not available through standard JPA and I would strongly discourage it. Instead of querying for Customers, why not change the query to get Orders instead -
"select o from Customer c join c.orders o where o.status = 'N'". Assuming Orders have a ManyToOne back reference to their Customer, this will mean you do not need to travers the Customer-> order relationship. If using
"select c, o from Customer c join c.orders o where o.status = 'N'"
I am not sure why you would use the orders from the returned customers instead of the orders returned in the results though.
You could also return "select c.id, c.name, o.id, o.status from Customer c join c.orders o where o.status = 'N'" which is the equivalent of what you would get from the SQL you initially posted.
Regards,
Chris -
Delay when querying from CUBE_TABLE object, what is it?
Hi Guys,
We are using Oracle OLAP 11.2.0.2.0 with an 11g Cube, 7 Dimensions, Compressed and partitioned by Month.
We have run into a performance issue when implementing OBIEE.
The main issue we have is a delay while drilling on a hierarchy. Users have been waiting 7-12 seconds per drill on a hierarchy, and the query is only returning a few cells of data. We have managed to isolate this to slow performing queries on CUBE_TABLE.
For example, the following query returns one cell of data:
SELECT FINSTMNT_VIEW.BASE, FINSTMNT_VIEW.REPORT_TYPE, FINSTMNT_VIEW.COMPANY, FINSTMNT_VIEW.SCENARIO, FINSTMNT_VIEW.PRODUCT, FINSTMNT_VIEW.ACCOUNT, FINSTMNT_VIEW.SITE, FINSTMNT_VIEW.TIME
FROM "SCHEMA1".FINSTMNT_VIEW FINSTMNT_VIEW
WHERE
FINSTMNT_VIEW.REPORT_TYPE IN ('MTD' )
AND FINSTMNT_VIEW.COMPANY IN ('E01' )
AND FINSTMNT_VIEW.SCENARIO IN ('ACTUAL' )
AND FINSTMNT_VIEW.PRODUCT IN ('PT' )
AND FINSTMNT_VIEW.ACCOUNT IN ('APBIT' )
AND FINSTMNT_VIEW.SITE IN ('C010885' )
AND FINSTMNT_VIEW.TIME IN ('JUN11' ) ;
1 Row selected in 4.524 Seconds
Note: FINSTMNT_VIEW is the automatically generated cube view.
CREATE OR REPLACE FORCE VIEW "SCHEMA1"."FINSTMNT_VIEW" ("BASE","REPORT_TYPE", "COMPANY", "SCENARIO", "PRODUCT", "ACCOUNT", "SITE", "TIME")
AS
SELECT "BASE", "REPORT_TYPE", "COMPANY", "SCENARIO", "PRODUCT", "ACCOUNT", "SITE", "TIME"
FROM TABLE(CUBE_TABLE('"SCHEMA1"."FINSTMNT"') ) ;
If we increase the amount of data returned by adding to the query, it only increased the query time by .4 seconds
SELECT FINSTMNT_VIEW.BASE, FINSTMNT_VIEW.REPORT_TYPE, FINSTMNT_VIEW.COMPANY, FINSTMNT_VIEW.SCENARIO, FINSTMNT_VIEW.PRODUCT, FINSTMNT_VIEW.ACCOUNT, FINSTMNT_VIEW.SITE, FINSTMNT_VIEW.TIME
FROM "SCHEMA1".FINSTMNT_VIEW FINSTMNT_VIEW
WHERE
FINSTMNT_VIEW.REPORT_TYPE IN ('MTD' )
AND FINSTMNT_VIEW.COMPANY IN ('E01' )
AND FINSTMNT_VIEW.SCENARIO IN ('ACTUAL' )
AND FINSTMNT_VIEW.PRODUCT IN ('PT' )
AND FINSTMNT_VIEW.ACCOUNT IN ('APBIT' )
AND FINSTMNT_VIEW.SITE IN ('C010885', 'C010886', 'C010891', 'C010892', 'C010887', 'C010888', 'C010897', 'C010893', 'C010890', 'C010894', 'C010896', 'C010899' )
AND FINSTMNT_VIEW.TIME IN ('JUN11' ) ;
12 rows selected - In 4.977 Seconds
If we increase the data returned even more:
SELECT FINSTMNT_VIEW.BASE, FINSTMNT_VIEW.REPORT_TYPE, FINSTMNT_VIEW.COMPANY, FINSTMNT_VIEW.SCENARIO, FINSTMNT_VIEW.PRODUCT, FINSTMNT_VIEW.ACCOUNT, FINSTMNT_VIEW.SITE, FINSTMNT_VIEW.TIME
FROM "SCHEMA1".FINSTMNT_VIEW FINSTMNT_VIEW
WHERE
FINSTMNT_VIEW.REPORT_TYPE IN ('MTD' )
AND FINSTMNT_VIEW.COMPANY IN ('ET', 'E01', 'E02', 'E03', 'E04' )
AND FINSTMNT_VIEW.SCENARIO IN ('ACTUAL' )
AND FINSTMNT_VIEW.PRODUCT IN ('PT', 'P00' )
AND FINSTMNT_VIEW.ACCOUNT IN ('APBIT' )
AND FINSTMNT_VIEW.SITE IN ('C010885', 'C010886', 'C010891', 'C010892', 'C010887', 'C010888', 'C010897', 'C010893', 'C010890', 'C010894', 'C010896', 'C010899' )
AND FINSTMNT_VIEW.TIME IN ('JUN11', 'JUL11', 'AUG11', 'SEP11', 'OCT11', 'NOV11', 'DEC11', 'JAN12') ;
118 rows selected - In 14.213 Seconds
If we take the time for each query and divide by the number of rows, we can see that querying more data results in a much more efficient query:
Time/Rows returned:
1 Row - 4.524
12 Rows - 0.4147
118 Rows - 0.120449153
It seems like there is an initial delay of approx 4 seconds when querying the CUBE_TABLE object. Using AWM to query the same data using LIMIT and RPR is almost instantaneous...
Can anyone explain what this delay is, and if there is any way to optimise the query?
Could it be the AW getting attached before each query?
Big thanks to anyone that can help!Thanks Nasar,
I have run a number of queries with logging enabled, the things you mentioned all look good:
Loop Optimization: GDILoopOpt COMPLETED
Selection filter: FILTER_LIMITS_FAST 7
ROWS_FAILED_FILTER 0
ROWS_RETURNED 1
Predicates: 7 pruned out of 7 predicates
The longest action I have seen in the log is the PAGING operation... but I do not see this on all queries.
Time Total Time OPERATION
2.263 27.864 PAGING DYN_PAGEPOOL TRACE GREW 9926KB to 59577KB
1.825 25.601 PAGING DYN_PAGEPOOL TRACE GREW 8274KB to 49651KB
1.498 23.776 PAGING DYN_PAGEPOOL TRACE GREW 6895KB to 41377KB
1.232 22.278 PAGING DYN_PAGEPOOL TRACE GREW 5747KB to 34482KB
1.17 21.046 PAGING DYN_PAGEPOOL TRACE GREW 4788KB to 28735KB
1.03 19.876 PAGING DYN_PAGEPOOL TRACE GREW 3990KB to 23947KB
2.808 18.846 PAGING DYN_PAGEPOOL TRACE GREW 3325KB to 19957KB
What is strange is that the cube operation log does not account for all of the query time. For example:
SELECT "BASE_LVL" FROM TABLE(CUBE_TABLE('"EXAMPLE"."FINSTMNT"'))
WHERE
"RPT_TYPE" = 'MTD' AND
"ENTITY" = 'ET' AND
"SCENARIO" = 'ACTUAL' AND
"PRODUCT" = 'PT' AND
"GL_ACCOUNT" = 'APBIT' AND
"CENTRE" = 'TOTAL' AND
"TIME" = 'YR09';
This query returns in 6.006 seconds using SQL Developer, if I then take the CUBE_OPERATION_LOG for this query and subtract the start time from the end time, I only get 1.67 seconds. This leaves 4.3 seconds unaccounted for... This is the same with the my other queries, see actual time and logged time below:
Query Actual Logged Variance
S3 6.006 1.67 4.336
L1 18.128 13.776 4.352
S1 4.461 0.203 4.258
L2 4.696 0.39 4.306
S2 5.882 1.575 4.307
Any ideas on what this could be or how I can capture this 4.3 second overhead?
Your help has been greatly appreciated. -
Possible?Multi-Entity View Object with one Entity Object that is Read-only.
I know this sounds crazy, but I would like to create a multi-entity view object, where one entity object is based on a table in my application (we'll call it "Users", which basically stores the primary key for the person from the institutional people database), and the other table is a entity object based on a view of the institutional people database table (read only access), which we can call "People".
I know that since no updates will be done to the People table, it really should be a read-only View Object, but I would lose the ability to sort on attributes like Last Name, Hire date, etc, since those would be transient attributes in my ViewObject for the Users. By having People as an entity object, I can then create a multi entity view object and have the ability to join Users to People and be able to sort on the above mentioned fields (like Last Name).
The problem is that when I use the JDev (I'm currently using 10.1.2.1) AppModule BC4J tester, when I click on the multi-entity view object that I added to the AppModule it gives me an error:
oracle.jbo.RowCreateException) JBO-25017: Error while creating a new entity row for People.
----- LEVEL 1: DETAIL 0 -----
(java.lang.InstantiationException) null
I have tried to change all the attributes to updateable in my entity object, but no create method, and I have tried to make them all read-only, but no effect, I get the same error (probably because the People view is read-only in my schema).
Is there a way to change the entity object so that it will not try to create a new row when it runs the Tester? So that the multi entity view object behaves more like a view link, but gives me the added bonus of being able to sort on the Last Name column from the People table?
Thanks for any help on this subject...at worst, I will have to use the view link method to get the job accomplished, but it would be "cooler" if this would work!
Jeremy.Steve, thanks for your quick response to my question.
To answer your questions, I was trying to create the Multi-entity View Object to give me more flexibility when working with my User table, and my People view. The flexibility I desired was that I would be able to sort my Users based on attributes in the People view. This is not possible when the there is only one Entity in my VO, and the People view data are all transient attributes, because they are not in the SQL statement.
Ultimately, after working with one of my colleagues, we decided to use the approach that you mentioned by creating a read-only VO with the SQL query we want to display to the user (contains both User and People data fields), and then use a different ViewObject when performing other actions on the User Table (such as inserts/updates/deletes). By using the setWhereClauseParam() method in the handleLifeCycle() for the JSP page, we should be able to navigate between the different View Objects, so that the user does not see any difference.
Thanks! Oh, and by the way, I have read your article you included before, and I have used it many times before to tune my View Objects! Thanks! -
How to add row in multiple view object based on common entity object.
Hi ,
I have
Jdeveloper version - 10.1.3.3.0
Oracle Database - 11g R2
I have a situation where i have to show data from one table in three adf tables on jsf page depending on a flag value in a column in table. For this purpose i have done the following steps
a) Created an entity object on the database table .
b) Created three view objects on this entity object and edited the view object's SQL and included the where clause
WHERE A.USER_PERSONAL_NO = :P_USER_PERSONAL_NO AND
A.AUTH_TYPE = 'LF'
The auth_type cloumn decided in which view object the data will be shown
Now, when i query the data from database by executing the query of these view objects the data is shown correctly in all three view objects. Till here there seems every thing ok
Now , i have to provide the logic to add records in the adf tables for this i have provided add button in action facet of all three tables which are binded to methods in managed bean,
when i add a record in a adf table by add button the new row which is created is shown in all three tables . I cant understand why this is happening , please help me to solve this problem.
How can i make it possible so that the record appears only in that adf table in which the record is added.
The method for adding record is
Row rw = currentAM.getWfRecommAuths().createRow();
rw.setAttribute("UserPersonalNo",this.getQuery_personal_no().getValue());
rw.setAttribute("AuthPersonalNo","");
rw.setAttribute("AuthType","LX");
currentAM.getWfRecommAuths().last();
currentAM.getWfRecommAuths().insertRow(rw);
Please help , thanks in advance.Hi,
have a look at polymorphic view objects
http://download.oracle.com/docs/cd/E21764_01/web.1111/b31974/bcadvvo.htm#CEGDCCCB
Frank -
Best practice for linking fields from multiple entity objects
I am currently transitioning from PHP to ADF. I'm looking for the best practice for linking data from multiple entity objects.
Example:
EO 'REQUESTS' has fields: req_id, name, dt, his_stat_id, her_stat_id
EO 'STATUSES' has fields: stat_id, short_txt_descr
'REQUESTS' is linked to EO 'STATUSES' on: STATUSES.stat_id = REQUESTS.his_status_id
'REQUESTS' is also linked to EO 'STATUSES' on: STATUSES.stat_id = REQUESTS.her_status_id
REQUESTS.his_status_id is independent of REQUESTS.her_status_id
When I create a VO for REQUESTS, I want to display: REQUESTS.name, REQUESTS.dt, STATUSES.short_txt_descr (for his_stat_id), STATUS.short_txt_descr (for her_stat_id)
What is the best practice for accomplishing this? It appears I could do it a few different ways:
1. Create the REQUESTS VO with a LOV for his_stat_id and her_stat_id
2. Create the REQUESTS VO with the join to STATUSES performed within the query for the VO. This would require joining on the STATUSES EO twice (his_stat_id, her_stat_id)
3. I just started reading about View Links - would that somehow do what I'm looking for?
I also need to be able to update his_status_id and her_status_id through the by selecting a STATUSES.short_txt_descr from a dropdown.
Any suggestions on how to approach such a stupidly simple task?
Using jDeveloper 11.1.2.2.0 if that makes a difference in the solution.
Thanks ahead of time,
CJCJ,
I vote for solution 1 as it's just your use case. As you said you what to update the his_status_id and her_status_id through the by selecting a STATUSES.short_txt_descr by a drop down. This is exactly the LOV solution.
ViewLinks are used fro master detail navigation (which you don't do here) and Joining the data make it difficult to update (and you still need a LOV for the drop down box.
Timo -
How do I make a view object containing two entity objects updatable?
I have a view object that contains attributes from two entity objects. The query looks like this
SELECT AplCfgPartyEO.ID,
AplCfgPartyEO.ID_HRM_BRW_JOB,
HrmBrwJobEO.CREATED_BY,
HrmBrwJobEO.CREATION_DATE,
HrmBrwJobEO.ID AS ID1,
HrmBrwJobEO.ID_HRM_BAS_JOB_TYPE,
HrmBrwJobEO.JOB_NO,
HrmBrwJobEO.MODIFIED_BY,
HrmBrwJobEO.MODIFY_DATE,
HrmBrwJobEO.ORIGIN,
HrmBrwJobEO.PICTURE
FROM APL_CFG_PARTY AplCfgPartyEO, HRM_BRW_JOB HrmBrwJobEO
WHERE AplCfgPartyEO.ID_HRM_BRW_JOB = HrmBrwJobEO.ID
My problem is that I am only allowed to update the attributes from the AplCfgPartyEO entity object while the attributes from the HrmBrwJobEO entity object become read only. I want to be able to update all of the attributes how do I do that?If someone will read this later I can inform them that I am using Studio Edition Version 11.1.1.0.2 at the moment. Thanks Chris, your answer solved my problem but I was a little surprised though that it wasn´t updatable by default.
-
Extending view object which does not have any entity object associated with
Dear all
I am interested in extended on of the standard pages VO object in JDeveloper OA extension
the standard page is oracle/apps/pos/supplier/....suppSummaryPG
and one of the view which I am interested to extend is suppSummVO
the problem is that when I copy xml files and java files from apps server to
my local jdevelope folder , I am not able to open that suppSummVO, the changes which
I find from other VO object and this(suppSummVO) object is that, this VO does not have any
Entity Object associated with it and the only query is return on this VO , is it the reason that
I am not able to open it Jdeveloper, but the real issue is that how can I extends this type of VO
in my OAExtension.
Regard
NomanIts the same way of extending VO with EO's or without EO's.
Sometimes if the .class files arn't decompiled we get weird jbo errors. So use cavaj/jad to decompile those Impl.class, RowImpl.class files and keep them in the same folder as vo.xml in myprojects and try extending that VO.
Thanks,
Ravi -
Hi,
I am using JDeveloper 11.1.1.6
This is my issue; I have a viewObject which contains three (3) fields that I need to use in ALL my EntityObjects. I started by just creating a transient attributes and populating those 3 fields with a viewAccessor and then using them on my EO without problems. The thing is that for each EO I need to create those transient attributes and I believe that there have to be more effective and cleaner solutions.
What can I do to have those three attributes accessible and available for all the EO on my appModule? Those three attributes are coming from a query in DB and mostly contains information about the person who is logged in.
I wanted to implement a solution; something like an Entity Object (global) with those three attributes and the instantiating it in the rest of my EO and call something like myEO.getMyVariableOne, myEO.getMyVariableTwo and myEO.getMyVariableThree but that is not possible. So the other option is creating the view object and instantiating that viewObject on my EO.
But what do you think is the best practice???
Thanks in advance.Hi Again,
I forgot to say that all my EO extend MyCustomEOImpl. Do you think that is a good practice to import my VO (which I am just using to retrieve my fields and not for UI) and set the variables in MyCustomEOImpl so all my EO can access them via inheritance???
What other options would you guys recommend?
Thank you
Edited by: Alejandro T. Lanz on Nov 5, 2012 11:30 AM -
ADF: use of view link Accessor in Entity Object = always null?
Hi,
JClient 9.0.5.2, adf model.
I would like to use the view link accessor method in the master EO to retrieve detail EO values and the view link accessor method in the detail EO to retrieve master EO values.
Detail Rule:
In the detail EO an attribute is derived from an attribute of the master EO: detail attribute = master attribute.
Master Rule:
In the master EO an attribute is derived from the detail EO: master atribute set to 0 if detail EO exist else set to 0.
Tables:
Table Master => MasterEO => MasterVO
- masterPK (not updateable)
- masterField (not updateable)
- hasDetailsFlag
Table Detail => DetailEO => DetailVO
- detailPK (not updateable)
- masterPK => foreign key (not updateable)
- masterField (query only)
MasterDetailLink based on foreign key.
In link wizard I asked for the generation of following accessors in the source & destination Entity Objects:
In DetailEO accessor name: RetrieveFromMaster
In MasterEO accessor name: RetrieveFromDetail
In the DetailEO, I asked for the generation of the DetailEOImpl file, accessors and create method.
As wriiten in the file, before the create method:
** Add attribute defaulting logic in this method. **
I tought this is the place to retrieve the master attribute:
The code:
MasterVORowImpl masterVO = getRetrieveFromMaster();
if (masterVO == null)
System.out.println("MasterVORowImpl masterVO create NNNNNNNNNNNUUUUUUUULLLLLLLLLL");
The masterVO is always null?
I suppose I didn't understand something, my guest is that ViewObjects may not be used for default logic?
I know how to implement those rules in the database with triggers.
I think that the data I need for implementing those rules exist somewhere at the ADF level so retrieving the data from the db is not necessary?
Could somebody give some clues?
I didn't find a similar example in the Business Rules in BC4J document.
Your help will be appreciated
FredericHi,
Detail Rule, copy attribute value form master.
In DetailEOImpl:
protected void create(AttributeList attributeList)
setAttribute(MASTERFIELD,this.getMaster().getMasterField());
super.create(attributeList);
Master rule, set flag to 0 if no details else set to 1.
In the MasterEOImpl added method to check if detail row exists based on Row Iterator => no db retrieval?
This method also sets the flag accordingly:
protected void checkHasOtherDetails()
oracle.jbo.RowIterator ri = this.getRetrieveFromdetail();
ri.last();
// last() must be called else hasNext() returns true even on last delete ???
Number hasDetails = Constants.NUMBER_NO; // = 1
if (ri.hasNext() || ri.hasPrevious())
hasDetails = Constants.NUMBER_YES; // = 0
if (!getHasDetailsFlag().equals(hasDetails)) {
this.setHasDetailsFlag(hasDetails);
I call this method in the remove method of the detailEOImpl:
public void remove()
this.getRetrieeFromMaster().checkHasOtherDetails();
super.remove();
To set the flag I added follwoing code in the create method of the DetailEOImpl:
protected void create(AttributeList attributeList)
setAttribute(MASTERFIELD,this.getMaster().getMasterField());
**** ADDED ***
Number masterHasDetailsFlag = getRetrieveFromMaster().getHasDetailsFlag();
if (!masterHasDetailsFlag.equals(Constants.NUMBER_YES)) {
getRetrieveFromMaster().setHasDetailsFlag(Constants.NUMBER_YES));
super.create(attributeList);
One more question:
Is there a danger of calling last() on row iterators in create/update/remove methods of *Impl files?
=> current row changed => any effect on display in JPanel
Thanks
Frederic
PS All variable/method/class names have been manually renamed in this code so some small syntax problems may exist.
Maybe you are looking for
-
Tax code value is not flowing into the netprice of the PO
HI, Tax percentage are calculating correctly but the final value is refelected to my pricng procedure and adding on to the net price of the PO,what should I do to bring the tax value to NAVS condition of the pricing procedure. Regards Kantha
-
How do I get vhs tape into my mac and record it to make it into a dvd?
What cables/software are required, etc? I would greatly appreciate your help.
-
Hi, when do you use core, free and aggregated data types? Thanks in advance regards, Ramya Shenoy
-
Trying to connect to a MS-SQL 2005 database for shared services. The server is configured as Server1\gendev. The config utility says that it is an invalid host. I am able to connect to the server via ODBC. Is there an issue with the "\" in the name?
-
Latest Flash @ 11 July 2010 - Firefox.
Dear Adobe People, Firefox & Flash Having trawled through embedded player on BBC news sites doesn't open and several other similar threads, it's pretty clear that there's a major issue. I have the very same probs. I have uninstalled sequentially al