Using Toplink API to persist data to database
My requirement is to persist data to the database (oracle) using Toplink Java API approach.
I have a basic setup program, but its not solving the purpose.
Kindly let me know where I am missing.
package sample;
import oracle.toplink.essentials.descriptors.ClassDescriptor;
import oracle.toplink.essentials.descriptors.RelationalDescriptor;
import oracle.toplink.essentials.internal.sessions.DatabaseSessionImpl;
import oracle.toplink.essentials.mappings.DirectToFieldMapping;
import oracle.toplink.essentials.queryframework.DatabaseQuery;
import oracle.toplink.essentials.sessions.Login;
import oracle.toplink.essentials.sessions.UnitOfWork;
public class EmployeeProject extends oracle.toplink.essentials.sessions.Project
private ClassDescriptor classDescriptor;
public EmployeeProject()
applyPROJECT();
applyLOGIN();
classDescriptor = buildEmployeeDescriptor();
addDescriptor(classDescriptor);
System.out.println("classDescriptor.getMappings(): " + classDescriptor.getMappings());
protected void applyPROJECT(){
setName("Employee");
protected void applyLOGIN()
oracle.toplink.essentials.sessions.DatabaseLogin login = new oracle.toplink.essentials.sessions.DatabaseLogin();
login.setDriverClassName("oracle.jdbc.OracleDriver");
login.setConnectionString("jdbc:oracle:thin:ptyagi-pc.idc.oracle.com:1521:orcl");
login.setUserName("system");
login.setPassword("orcl");
// Configuration Properties
setDatasourceLogin((Login)login);
// SECTION: DESCRIPTOR
public ClassDescriptor buildEmployeeDescriptor() {
RelationalDescriptor descriptor = new RelationalDescriptor();
// specify the class to be made persistent
descriptor.setJavaClass(sample.Employee.class);
// specify the tables to be used and primary key
descriptor.addTableName("EMP1");
descriptor.addPrimaryKeyFieldName("EMP1.ID");
// Descriptor Properties
descriptor.useSoftCacheWeakIdentityMap();
descriptor.setIdentityMapSize(100);
descriptor.setAlias("Employee");
// Mappings
DirectToFieldMapping idMapping = new DirectToFieldMapping();
idMapping.setAttributeName("id");
idMapping.setFieldName("EMP1.ID");
descriptor.addMapping(idMapping);
DirectToFieldMapping nameMapping = new DirectToFieldMapping();
nameMapping.setAttributeName("name");
nameMapping.setFieldName("EMP1.NAME");
descriptor.addMapping(nameMapping);
DirectToFieldMapping salMapping = new DirectToFieldMapping();
salMapping.setAttributeName("salary");
salMapping.setFieldName("EMP1.SALARY");
descriptor.addMapping(salMapping);
return descriptor;
public static void main(String [] args) {
EmployeeProject empProj = new EmployeeProject();
Employee emp = new Employee();
emp.setID(1);
emp.setName("Pulkita");
emp.setSalary(100);
DatabaseSessionImpl databaseSessionImpl = new DatabaseSessionImpl(empProj);
databaseSessionImpl.login();
databaseSessionImpl.beginTransaction();
UnitOfWork unitOfWork = databaseSessionImpl.acquireUnitOfWork();
unitOfWork.registerNewObject(emp);
unitOfWork.commit();
}
The issue is with the line:
databaseSessionImpl.beginTransaction();Since you began the transaction yourself you must also commit it. The easiest solution is to remove the above line and allow the UnitOfWork to begin and commit the transaction itself.
Doug
Similar Messages
-
Calling an Oracle stored procedure using Toplink API - Please help
Hi,
We are evaluating Toplink as a possible data access layer in large service-oriented application. The ability to call db stored procedures from within business object layer is crucial for our architechture.
I am trying to follow toplink application developer's guide examples on how to call stored procedures using toplink.
I have the folling java code:
call.setProcedureName("PR_ROMAN_TEST");
call.addNamedArgument("IN_PARAM");
call.addNamedOutputArgument("OUT_PARAM");
ValueReadQuery query = new ValueReadQuery();
query.setCall(call);
query.addArgument("IN_PARAM");
Vector params = new Vector();
params.addElement(new Integer(5));
Number result = (Number) session.executeQuery(query, params);
This generates the following SQL statement:
BEGIN PR_ROMAN_TEST(IN_PARAM=>5, OUT_PARAM=>?); END;
An attempt to execute it causes a
java.sql.SQLException: Invalid column index.
As I understand it, this exception is thrown because of the "?" in place of the out-parameter value holder.
The SQL statement that I would want toplink to generate and execute should look like:
DECLARE result number; BEGIN PR_ROMAN_TEST(IN_PARAM=>5, OUT_PARAM=>result); END;
, but how do I achieve it and how do I capture the return value, all using toplink api?
Please help
Thank you in advance,
RomanI read the conversation above. I am running into a similar kind of problem. I get the following error.
<an exponent (**)> <> or != or ~= >= <= <> and or like between || The symbol "." was subs Error Code: 6550Local Exception Stack: Exception [TOPLINK-4002] (OracleAS TopLink - 10g (9.0.4.5) (Build 040930)): oracle.toplink.exceptions.DatabaseException Exception Description: java.sql.SQLException: ORA-06550: line 1, column 38: PLS-00103: Encountered the symbol "NAME" when expecting one of the following:. ( ) , * @ % &' | = - + < / > at in is mod not range rem =>.. <an exponent (**)> <> or != or ~= >= <= <> and or like as between from using || The symbol "." was substituted for "NAME" to continue.ORA-06550: line 1, column 55: PLS-00103: Encountered the symbol "ID" when expecting one of the following:. ( ) , * @ % &' | = - + < / > at in is mod not range rem =>.. <an exponent (**)> <> or != or ~= >= <= <> and or like between || The symbol "." was subs Internal Exception: java.sql.SQLException: ORA-06550: line 1, column 38:PLS-00103: Encountered the symbol "NAME" when expecting one of the following . ( ) , * @ % &' | = - + < / > at in is mod not range rem =>.. <an exponent (**)> <> or != or ~= >= <= <> and or like as between from using || The symbol "." was substituted for "NAME" to continue.ORA-06550: line 1, column 55:PLS-00103: Encountered the symbol "ID" when expecting one of the following: . ( ) , * @ % &' | = - + < / > at in is mod not range rem =>.. <an exponent (**)> <> or != or ~= >= <= <> and or like between || The symbol "." was subs Error Code: 6550 at oracle.toplink.exceptions.DatabaseException.sqlException(DatabaseException.java:227)
at oracle.toplink.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:733)
at oracle.toplink.internal.databaseaccess.DatabasePlatform.executeStoredProcedureCall(DatabasePlatform.java:1605)
at oracle.toplink.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:649)
at oracle.toplink.threetier.ServerSession.executeCall(ServerSession.java:506)at oracle.toplink.internal.queryframework.CallQueryMechanism.executeCall(CallQueryMechanism.java:131)
at oracle.toplink.internal.queryframework.CallQueryMechanism.executeCall(CallQueryMechanism.java:115)
at oracle.toplink.internal.queryframework.CallQueryMechanism.executeSelectCall(CallQueryMechanism.java:194)
at oracle.toplink.internal.queryframework.CallQueryMechanism.executeSelect(CallQueryMechanism.java:175)
at oracle.toplink.queryframework.DirectReadQuery.executeNonCursor(DirectReadQuery.java:65)
at oracle.toplink.queryframework.DataReadQuery.execute(DataReadQuery.java:73)
at oracle.toplink.queryframework.ValueReadQuery.execute(ValueReadQuery.java:59)
at oracle.toplink.queryframework.DatabaseQuery.execute(DatabaseQuery.java:493)
at oracle.toplink.queryframework.ReadQuery.execute(ReadQuery.java:125)
at oracle.toplink.publicinterface.Session.internalExecuteQuery(Session.java:1958)
at oracle.toplink.threetier.ServerSession.internalExecuteQuery(ServerSession.java:629)
at oracle.toplink.threetier.ClientSession.internalExecuteQuery(ClientSession.java:392)
at oracle.toplink.publicinterface.Session.executeQuery(Session.java:1086)
at oracle.toplink.publicinterface.UnitOfWork.internalExecuteQuery(UnitOfWork.java:2246)
at oracle.toplink.publicinterface.Session.executeQuery(Session.java:1086)
at oracle.toplink.publicinterface.Session.executeQuery(Session.java:1055)
at com.eplinc.common.persistence.toplink.TopLinkTemplate$2.readFromSession(TopLinkTemplate.java:181)
at com.eplinc.common.persistence.toplink.SessionReadCallback.doInTopLink(SessionReadCallback.java:59)
at com.eplinc.common.persistence.toplink.TopLinkTemplate.execute(TopLinkTemplate.java:110)
at com.eplinc.common.persistence.toplink.TopLinkTemplate.executeQuery(TopLinkTemplate.java:178)
at com.eplinc.common.persistence.toplink.TopLinkTemplate.executeQuery(TopLinkTemplate.java:172)
at com.epl.outletteller.dao.toplink.TopLinkOIDGeneratorDAO.generateId(TopLinkOIDGeneratorDAO.java:45)
The call I am making is as follows :
public long generateId(String name, long outletId) throws DataAccessException {
TopLinkTemplate tlTemplate = new TopLinkTemplate();
StoredProcedureCall call = new StoredProcedureCall();
call.setProcedureName("AUTONUM.GET_NEXT_VALUE");
call.addNamedArgument("autonum name");
call.addNamedArgument("outlet id");
call.addNamedOutputArgument("OUTPUT_1");
ValueReadQuery query = new ValueReadQuery();
query.setCall(call);
query.addArgument("autonum name");
query.addArgument("outlet id");
Object[] parameters = new Object[2];
parameters[0] = name;
parameters[1] = Long.toString(outletId);
Number uniqueNumber = (Number)tlTemplate.executeQuery(query,parameters);
return uniqueNumber.longValue();
This is my Table AUTONUM_SETTING
AUTONUM_NAME AUTONUM_TYPE START_VAL END_VAL INCREMENT_VALUE
TRAN_NUM GLOBAL 1 999999 1
TRACE_NUM OUTLET 1 999999 1
Any help would be appreciated. Thanks -
How to do linguistic sort query using Toplink API
Hi,
I want to write a Toplink query using linguistic sort like the following SQL,
SELECT * from emp_name
where ename LIKE 'müller%'
ORDER BY NLSSORT(ename, 'NLS_SORT=german')
I got two questions:
(1) how to implement "ORDER BY NLSSORT(name, 'NLS_SORT=german')" using Toplink API.
(2) I built linguistic index,
CREATE INDEX nls_index ON emp_name (NLSSORT(ename, 'NLS_SORT = german'));
But SQL plan shows that LIKE clause does not use index. I wonder how to enforce query with LIKE clause to use such linguistic index.
Thanks for your help in advance.
-EvanLooks like we can not do an exact word search using Java API.
-
Using .csv file and adding data into database
hi,
i'm working on a project which shows all the share prices on a webpage from the FTSE100..
my problem is..i connect to yahoo.co.uk to get my share price information which is updated every 15mins..they return a .csv file to me...at the moment, i am just printing the information onto my website, but is there any way that i could store this information into a database if i needed the data to be used elsewhere...thanx for the help in advancebelow is my code which i used to get my info onto the web...i'd just like to know how i would use this to store the data into a database..
import java.net.*;
import java.io.*;
import java.lang.*;
import java.util.*;
public class SharePrice
private String line;
private int maxShares = 101;//maximun shares a user can have
private int details = 5;//five details, name,date,time,price,change.
public String [][] shareData = new String[maxShares][details];
public SharePrice(String [] shares) throws Exception
getShare(shares);
//returns a double array containing share data of each share as a seperate row in the array
public String [][] getShare(String [] sh) throws Exception
for(int i=0; i<sh.length; i++)
//if the entry is null we have reached the end of the array
if(sh!=null)
String share = sh[i];
//part of url of the resource
String address ="http://uk.finance.yahoo.com/d/quotes.csv?s=";
//adds the share tothe url so that particular shares data is retieved
address = address+share;
System.out.println(address);
try
//connection is created to the resource and input stream opened to read data
URL url = new URL(address);
BufferedReader in = new BufferedReader(
new InputStreamReader(
url.openStream()));
line = in.readLine();
in.close();
}catch(Exception e){System.err.println("Exception: " + e.getMessage());
e.printStackTrace();}
//the line of data retrieved is spli and placed in a single row of the array
//beause the each piece of data is seperated by commas it is easily seperated.
StringTokenizer t = new StringTokenizer(line, ",");
int count = t.countTokens();
System.out.println(" count= "+count);
while(t.hasMoreTokens())
for(int j=0; j<count; j++)
String s = t.nextToken();
shareData[i][j] = s;
return shareData; -
Help needed: clarifying the use of beans to pass data from database to JSP
Hi everyone,
I am sure you all get fed up with being asked this question as I can see it is asked a lot when googled, but the answers given have not cleared things up for me.
Anyway, I have a JSP page that contains a text box, submit button and a select box of size 10. The user enters a search string and the form submits the data and reloads the same page. From the code you can see the Name property of the bean is set.
<jsp:useBean id="vtm" class="FinalYearProject.Types.VtmType" scope="page" />
<jsp:setProperty name="vtm" property="NM" value="${param.NM}" />I then need to be able to use that name to query a postgresql database. I have a JDBCConnector class with the method:
public ResultSet searchTable(String NM ) throws SQLException {
String[] names = NM.split(" ");
NM = "";
for(int i = 0; i < names.length; i++) {
NM = names[i] + "%";
return stat.executeQuery("SELECT * FROM vtm WHERE nm ILIKE '" + NM + "';");
}This method however can be changed.
My question really is what is the best way for me to take the name, get the resultset and pass back the VtmType objects to the jsp so that I can populate my select box, and where should each part be handled i.e. the JSP page, the VtmType, the JDBCConnector.
I may be going about it completely the wrong way and using beans incorrectly, but I just cant seem to get my head around the problem.
Any help would be much appreciated,
Thanks.Hi,
Thanks for the help, I actually found some literature about the JSP Model 2 and realised that was what I needed to do. I have now re-written everything and it has made my life a lot eaiser, typically this was before I checked back on this post though!
Anyway, I now have JSP pages requesting Servlets which create beans and call classes that access the database. The servlet then forwards the beans and where necessary a small of html to another JSP. Like you have suggested.
One problem I have now however, is that the user needs to be logged in to access some of the pages. An error page with the correct message is displayed to the user when it is processed via the servlet.
//Servlet detects an error
request.setAttribute("errorMsg", "1");
gotoPage("/loginError.jsp", request, response);
//JSP detects which errorMsg to display
<c:set var="errorMsg" value="${requestScope.errorMsg}" />However, when the user does not sign in and clicks a link which is blocked the JSP forwards directly to the error JSP.
//Tests to see if user is logged in
<c:if test="${empty user.username}">
<jsp:forward page="/loginError.jsp">
<jsp:param name="errorMsg" value="3" />
</jsp:forward>
</c:if>The problem with this is that the only way I can see of checking the errorMsg type is with:
//JSP checks which errorMsg to display
<c:set var="errorMsg" value="${param.errorMsg}" />Which is different to how I determine the errorMsg from the Servlet. Is there a way of getting the errorMsg type that is the same for both actions?
Thanks. -
Hi Experts
I ahve migrated data of one database into another and need to check whether whole data is migrated successfully and correctly. I was thinking of using Excel Macros with VB APIs to extract all level 0 data into a tabular format and then compare. Is my approach correct?
Is there any other method to compare data between two databases?
I have never developed any API based application from scratch..and need some guidelines for the same. All sort of help welcomedA buddy of mine and poster to this board, Dave Farnsworth, has an Excel module that does exactly this in Excel -- he's almost got it ready for freebie release.
If you can wait a week or so (I know, I know, you can't) I'll have his add-in up on my blog.
Dave -- the pressure is on. See, a real world example just begging for your code. :)
I have used a beta version of the tool -- it is freaking awesome -- you define the two databases, do a retrieve in the first sheet and the tool does the retrieve of the second database and then identifies differences. It's very, very flexible and easy to use. Yes, I am a big fan.
Regards,
Cameron Lackpour -
Using a paramter to fetch data from database
Hello SAP,
Is there a way to use a parameter that takes in the employee ID and have it fetch from the database the employee name. Just to note, the tables that I am using in this report do not link to the employee table that contains the employee name. I just want to be able to use a parameter that can fetch me the name from the database dynamically so that it prints in the report header.
Is this possible?
Thanks in advance,
ZThanks for your responses all.
I tried what you've recommended. I tried but it didn't seem to work. Perhaps I misunderstood so please let me know if I did. I'll elaborate a bit more of what I'm looking to achieve.
I have a report that gives information that pertains to an employee. The three tables in the report have no reference to the employee table (meaning I cannot link the Emp ID field to any field of the three tables). We as the firm know based on coding within the three tables which employee the records within the report beloing to.
So basically, I want to be able to display the employee's full name in the Report Header by using a parameter. I want to enter the employee ID in the parameter field and have it display the employee name in the report header.
I tried to insert the Employee table in my report as the only "unlinked" table in my report. I tried to create a formula as:
@Employee Name
if {?Emp ID} = {Employee table. Emp ID} then
{Employee Name}
This resulted in as a null value when I inserted it into the report header.
I also tried creating a formula as such:
@Employee Name (2nd)
BeforeReadingRecords;
Global StringVar FullName;
if {?Emp ID} = {Employee table. Emp ID} then
FullName:={Employee Name};
This did not work either as the error message stated the field {Employee table.Emp ID} must be evaluated later.
If I'm heading in the wrong direction can someone steer me back into the right direction?
Sastry, if I need to use the Add Command feature to fetch the data, is there a way to dynamically insert the parameter value in the SQL so that only the record that you want to be brought back into your report comes back?
Thanks again to all!
Z
Edited by: Zack H on Jan 19, 2009 8:34 PM -
Using bmp to get the data from database
Hi!
I'm testing different clients ask for the same data by bmp. But when I use
WLS6.1 console to monitor the entity beans, the "Beans In Use Count" and the
"Cached Beans Current Count" for one entity bean keep increasing, though I'm
trying to retrieve the same data for several times. Entity beans can stay
in memory and be reused, right? Maybe I'm wrong. I'm confused by the
monitor console. Could anyone tell me the correct concept or the meaning of
the monitor indicates? Thanks a lot.
HattieIf db-is-shared is set to false and you are using a find by pk then it
should pull from cache.
Peace,
Cameron Purdy
Tangosol Inc.
<< Tangosol Server: How Weblogic applications are customized >>
<< Download now from http://www.tangosol.com/download.jsp >>
"Hattie" <[email protected]> wrote in message
news:3c056cfc$[email protected]..
Hi!
I'm testing different clients ask for the same data by bmp. But when Iuse
WLS6.1 console to monitor the entity beans, the "Beans In Use Count" andthe
"Cached Beans Current Count" for one entity bean keep increasing, thoughI'm
trying to retrieve the same data for several times. Entity beans can stay
in memory and be reused, right? Maybe I'm wrong. I'm confused by the
monitor console. Could anyone tell me the correct concept or the meaningof
the monitor indicates? Thanks a lot.
Hattie -
Using a form to submit data to database
I have a servlet and I am trying to implement a form in the page so that it will submit from a text box a string into the database. Here is my code.
java.util.Date d = new java.util.Date();
java.sql.Timestamp t = new java.sql.Timestamp(d.getTime());
String data = "";
out.println("<form method=get>");
out.println("Enter Data: ");
out.println("<input type=text name='data' >");
out.println("<input type=submit value=Submit>");
out.println("</form>");
// Insert Data
PreparedStatement pst = con.prepareStatement("INSERT INTO FOO (NAME,DATE_MODIFIED) VALUES(?,?)");
pst.setString(1, data);
pst.setTimestamp(2, t);
pst.executeUpdate();
I believe this is incorrect in the <form> code. I do not know how to INSERT the data that is submitted from the <form>.You need to separate the servlet code from the HTML code.
First you create an HTML page with the HTML form:
<form method="get" ACTION="myservletname">
Enter Data:
<input type=text name='data' >
<input type=submit value=Submit>
</form>
Then you create the servlet which will read the request object with the parameter called "data".
And then you input that value into a database.
Visit the servlet tutorials in the Sun site.
-AJD -
Problems with persistent data in Plugin
Hi everybody,
I'm currently working on an old plugin for the company i'm working. I never have done something with InDesign before so i guess that is one of the main problems ^^. The Plugin was originally developed for CS 2 and was first ported to CS3 and now to CS4. The code is neither commented nor is the person that wrote the plugin still available (hurray for me ^^). The new port is running, but it still misses a feature that was, at least in cs2, functional but never used so it didnt got ported.
The plugin uses preferences to store persistent data and according to that data highlight some text or dont highlight it. The problem i cant fix now, is that the plugin cant instanciate the preferences to store the data.I posted the first code that tries to get a new instance of the preferences and fails. I looked throught the sdk-sample, but they use a different way to get and set the preferences. So the main question is: Is it still possible to set/get preferences like the following, or do i need to do it somehow differenly?
bool16 dhPrintMarkUtils::GetTagShown()
IDocument* doc = Utils<ILayoutUIUtils>()->GetFrontDocument();
if (doc != nil)
InterfacePtr<IDHPrintMarkPrefs> iPrefs(doc->GetDocWorkSpace(), UseDefaultIID());
if (iPrefs != nil)
return iPrefs->GetTagShown();
return kFalse;
The Preferencesclass is as follows:
#include "VCPluginHeaders.h"
// Interfaces:
#include "IPMStream.h"
//General:
#include "CPMUnknown.h"
// Project:
#include "dhPrintMarkID.h"
#include "dhPrintMarkPrefs.h"
class dhPrintMarkPrefs : public CPMUnknown<IDHPrintMarkPrefs>
public:
dhPrintMarkPrefs(IPMUnknown* boss);
virtual ~dhPrintMarkPrefs();
virtual bool16 GetTagShown ();
virtual void SetTagShown (bool16 tagHilited);
virtual void ReadWrite(IPMStream* s, ImplementationID prop);
private:
bool16 fTagHilited;
I dont quite know what else is relevant, so if you could please drop a note what else i should provide, i will glady post it.
Thank you very, very much for answers! (I'm kinda desperate on this topic ^^).
Grettings,
DaishyHi again,
First of all, thanks for your tips! Unfortunately it still isnt working :/
I tried reimplementing a new preferences class (i attached the source to it, so it wont take up that much space). I followed all your tipps and the sdksample (at least i hope so).I only try to read the preferences so far, not change it or write it. The following function is called from a gui element
trying to check a checkbox based on the result the method is giving (true oder false). But i get the not created message.
Am i stil doing something wrong? Once again thanks for your help and time!
Edit: I tried uploading the files, but it seems thats not allowed. So i put them in a pastebin:
http://pastebin.com/m48eb9ca3
http://pastebin.com/m10fe4733
bool16 dhPrintMarkUtils::GetTagShown()
IDocument *doc = Utils<ILayoutUIUtils>()->GetFrontDocument();
if(doc != nil)
InterfacePtr<IdhPrintmarkPreferences> iPrefs2(doc->GetDocWorkSpace(), UseDefaultIID());
if(iPrefs2 != nil) CAlert::ErrorAlert("created");
else CAlert::ErrorAlert("not created");
To the ID.h i added:
DECLARE_PMID(kInterfaceIDSpace, IID_PREFERENCES, kDHPrintMarkPrefix + 7)
DECLARE_PMID(kImplementationIDSpace, kdhPrintmarkPreferencesImpl, kDHPrintMarkPrefix+23)
To the factorylist.h i added:
REGISTER_PMINTERFACE(dhPrintmarkPreferences, kdhPrintmarkPreferencesImpl)
To the .fr i added (on toplevel):
resource IgnoreTask(1)
kImplementationIDSpace,
kdhPrintmarkPreferencesImpl,
And to the resource ClassDescriptionTable(kSDKDefClassDescriptionTableResourceID) part:
AddIn
kWorkspaceBoss,
kInvalidClass,
IID_PREFERENCES, kdhPrintmarkPreferencesImpl, -
Help , How to get data from database using recordset with UI API
I want to get a data from database
when I want to create recordset i notice that UI API didn't has record set
so I created recordset using DI API (SAPbobscom.recordset and SAPbobscom.company)
======================================================
Dim oCompanyUI As SAPbouiCOM.Company <<UI API
Dim oRecSet As New SAPbobsCOM.Recordset << DI API
Dim oCompanyDI As New SAPbobsCOM.Company << DI API
'=====================================================
oCompanyDI.Connect
Set oRecSet = oCompanyDI.GetBusinessObject(BoRecordset)
oRecSet.DoQuery ("SELECT T0.CardCode, T0.CardName FROM OCRD T0")
SBO_Application.MessageBox oRecSet.Fields.Item(1).Value
======================================================
but I got an error it said "you are not connected to company"
I'm really don't have an idea about how to get a data from using UI API (exp I want to get a date or costumer code)
can someone help me please, I really need it
Thanksyou need a single sign on
Dim oDICompany As SAPbobsCOM.Company
Dim sCookie As String
Dim sConnStr As String
Dim ret As Integer
oDICompany = New SAPbobsCOM.Company
sCookie = oDICompany.GetContextCookie
sConnStr = SBO_Application.Company.GetConnectionContext(sCookie)
If oDICompany.Connected Then
oDICompany.Disconnect()
End If
ret = oDICompany.SetSboLoginContext(sConnStr)
If Not ret = 0 Then
SBO_Application.MessageBox("set Login Context failed!")
Exit Sub
End If
ret = oDICompany.Connect()
If Not ret = 0 Then
SBO_Application.MessageBox("Company Connect failed!")
End If -
How to persist data in the object n memory after fetching it once from database and use it with linq
Hi,
I have some data from the database around 8 to 10 records .
These records are interrelated and I need to show cascade drop down.
I want to get the records from the database using c#.
And then based on certain events on the page want to use linq over the same data without having to get the data from the data base again.
i.e
ProductName
Product Plan
Product type
Monthly
Annually
pordA
Gold
Individual
1
5
pordA
Gold
Spouse
2
6
pordA
Silver
Individual
3
7
pordA
Silver
Spouse
4
8
Prod B
Platinum
Individual
5
9
Prod B
Platinum
Spouse
6
10
Prod B
Gold
Individual
1
5
Prod B
Gold
Spouse
2
6
pordA
Silver
Individual
3
7
pordA
Silver
Spouse
4
8
pordA
Platinum
Individual
5
9
Now on page load I want product name in drop down.
Based on the productName selected i want to show Product Plan in another drop down and based on prduct plan want to show prduct type in drop down and then the annual and monthly in drop down.
I want to get all the records of prod A and then using linq to object load the drop downs instead of running query to database.
How can I keep the records available across the function calls.
Regards
VinodThis is mostly a ASP.NET question. You get better answers if you post it in ASP.NET forum.
This is my answer:
Session is not a suitable choice, since each user will have a duplicate of the data. Cache is a better option.
You can put something in Cache option and retrieve it from Cache similar to using Session. This is the manual method of caching and management of the cache content is on yourself.
public List<Product> GetAll()
List<Product> products = null;
if (Cache["Products"] == null)
DataSet data = RetrieveProducts();
products = ConvertProductsDataSetToObject(data);
Cache.Insert("Products", products, null, DateTime.Now.AddMinutes(30), TimeSpan.Zero);
else
products = (List<Product>)Cache["Products"];
return products;
When putting something in the cache, you should set its expire time. But one thing that is more important over this is to clear the cache when your data is changed in the data store (e.g. database).
public void UpdateProduct()
// update product in the database
// clear the cahce, so that the next request for Products, receives a fresh copy of the data
Cache["TestItem"] = null;
Other than using cache manually, there are also some helper funcationalities that manage cache automatically for you, based on the technology you use (ASP.NET Web Forms or ASP.NET MVC). For example in ASP.NET Web Forms you can ask ASP.NET Web Forms engine
to cache the output of a User Control automatocally by adding OutputCache directive to the user control. In ASP.NET MVC you can you [OutputCache] attribute and apply it to actions.
[OutputCache(Duration = 86400, Location = OutputCacheLocation.All)]
public ActionResult Index()
var model = ProductBL.GetAll();
return View(model);
Also, there is a concept named cache dependency, by which you can specify a dependency for the item being cached. When the condition is met, the cache automatically invalidates and clears.
There are three kinds of cache dependency:
Item dependency: make cached data dependent on another cached data
File dependency: make cached data dependent on a file
Sql dependency: make cached data dependent on the result of a SQL query -
Problem with stored procedure usage when Toplink api is used
In one of our applications we used the combination of JBoss4.0.2 application server, Oracle Toplink 10g (9.0.4.5), JDBC Driver Version is ..... 10.1.0.2.0, Database Product Version is Oracle9i Enterprise Edition Release 9.2.0.6.0, j2sdk1.4.2_08
We faced problem in the application when it is trying to call stored procedure using Oracle Toplink api
code snippet:
public ByteArrayOutputStream baos = new ByteArrayOutputStream();
public PrintStream pos = new PrintStream(baos);
public String delete(String Id)
String procedureName = "abc";
try
UnitOfWork uow = PersistenceManager.getCurrent().getUnitOfWork();
StoredProcedureCall call = new StoredProcedureCall();
call.setProcedureName(procedureName);
call.addUnamedArgumentValue(Id);
uow.executeNonSelectingCall(call);
uow.commit();
catch (Exception e)
message = e;
e.printStackTrace(pos);
message = message+ baos.toString();
return message;
Stack Trace:
Exception [TOPLINK-4002] (OracleAS TopLink - 10g (9.0.4.5) (Build 040930)): oracle.toplink.exceptions.DatabaseException Exception Description: java.sql.SQLException: ORA-06550: line 1, column 7: PLS-00201: identifier 'abc' must be declared ORA-06550: line 1, column 7: PL/SQL: Statement ignored Internal Exception: java.sql.SQLException: ORA-06550: line 1, column 7: PLS-00201: identifier 'abc' must be declared ORA-06550: line 1, column 7: PL/SQL: Statement ignored Error Code: 6550Local Exception Stack: Exception [TOPLINK-4002] (OracleAS TopLink - 10g (9.0.4.5) (Build 040930)): oracle.toplink.exceptions.DatabaseException Exception Description: java.sql.SQLException: ORA-06550: line 1, column 7: PLS-00201: identifier 'abc' must be declared ORA-06550: line 1, column 7: PL/SQL: Statement ignored Internal Exception: java.sql.SQLException: ORA-06550: line 1, column 7: PLS-00201: identifier 'DELETE_LOADED_RESULT_SET' must be declared ORA-06550: line 1, column 7: PL/SQL: Statement ignored Error Code: 6550 at oracle.toplink.exceptions.DatabaseException.sqlException(DatabaseException.java:227) at oracle.toplink.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:733) at oracle.toplink.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:781) at oracle.toplink.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:642) at oracle.toplink.publicinterface.UnitOfWork.executeCall(UnitOfWork.java:1400) at oracle.toplink.internal.queryframework.CallQueryMechanism.executeCall(CallQueryMechanism.java:131) at oracle.toplink.internal.queryframework.CallQueryMechanism.executeCall(CallQueryMechanism.java:115) at oracle.toplink.internal.queryframework.CallQueryMechanism.executeNoSelectCall(CallQueryMechanism.java:164) at oracle.toplink.internal.queryframework.CallQueryMechanism.executeNoSelect(CallQueryMechanism.java:143) at oracle.toplink.queryframework.DataModifyQuery.execute(DataModifyQuery.java:41) at oracle.toplink.queryframework.DatabaseQuery.execute(DatabaseQuery.java:493) at oracle.toplink.publicinterface.Session.internalExecuteQuery(Session.java:1958) at oracle.toplink.publicinterface.UnitOfWork.internalExecuteQuery(UnitOfWork.java:2236) at oracle.toplink.publicinterface.Session.executeQuery(Session.java:1086) at oracle.toplink.publicinterface.Session.executeQuery(Session.java:1038) at oracle.toplink.publicinterface.Session.executeNonSelectingCall(Session.java:816) at com.abc.de.fg.model.resultSet.ResultSetProvider.delete(ResultSetProvider.java:150) at
Could anyone please let me know what might be the problem in this case.Tried and couldn't reproduce the problem using 9.0.4.7.
Here's the code:
System.out.println("storedProcedureUnamedValueTest");
StoredProcedureCall call = new StoredProcedureCall();
String lastName = "Jones";
call.setProcedureName("STOREDPROCEDURE_IN");
call.addUnamedArgumentValue(lastName);
session.executeNonSelectingCall(call);stored procedure definition in data base:
CREATE OR REPLACE PROCEDURE "TEST_904"."STOREDPROCEDURE_IN" (
IN_PARAM VARCHAR2) AS
BEGIN
UPDATE EMPLOYEE SET F_NAME = 'Indiana' WHERE (L_NAME = IN_PARAM);
END;log:
storedProcedureUnamedValueTest
DatabaseSession(15)--Execute query DataModifyQuery()
DatabaseSession(15)--Connection(16)--BEGIN STOREDPROCEDURE_IN('Jones'); END;
DatabaseSession(15)--Connection(16)--reconnecting to external connection poolAndrei -
Cross Reference within external Database using XREF API
Hi Experts,
Can we do Cross Reference within external Database using XREF API uses JDBC to access the Oracle Database Stored Procedures in SAP PI? How to use a JNDI Data source to access the DB and how to do the Connection Pooling will be done by the SAP J2EE server? Kindly let me know step by step proceedings.
Regards
ArchanaHello Archana,
It can be done with a Lookup call in a mapping.
Here's a little article about the topic in the SAP wiki:
http://wiki.sdn.sap.com/wiki/display/XI/HowtouseCrossReferencewithinexternal+Database
With kind regards
Sebastian -
EJB 3.0 - JSF APPLICATION: DATA DOES NOT PERSIST TO THE DATABASE
Hi,
I am developing a JSF - EJB application and the data that I send from JSP Page through JSF Managed Bean --> Session Bean --> Java Persistence does not persist in database.
Here is my scenario ( Iam using JDeveloper IDE to create this application) -
SCENARIO START
The scenario consists of two web pages, one enlisting all the users stored in the database, the other contains a form for adding a user
1.) INDEX.JSP
2.) ADDUSER.JSP
Step 1: Create the USERS Table in database
CREATE TABLE users
user_id serial,
username varchar(255) NOT NULL,
first_name varchar(255),
last_name varchar(255),
password char(64) NOT NULL,
CONSTRAINT pk_users PRIMARY KEY (user_id)
Step 2: Add Database Connection To JDeveloper
Go to Database Connection Navigator and create a New Database Connection using the Wizard
Step 3: Create a New Application in JDeveloper and select JSF, EJB from Application Template
Step 4: ENTITY BEAN - In the EJB Node Right Click and Select EJB à New Entites from Table (JPA/EJB3.0)
Use The Wizard and create Entity Bean from Users Table which creates an Entity Bea POJO file as follows –
User.java -
package lux.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@NamedQuery(name = "User.findAll", query = "select o from User o")
@Table(name = "USERS")
public class User implements Serializable {
@Column(name="FIRST_NAME")
private String firstName;
@Column(name="LAST_NAME")
private String lastName;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String username;
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="users_seq_generator")
@SequenceGenerator(name="users_seq_generator", sequenceName="users_user_id_seq")
@Column(name="USER_ID", nullable = false)
private Long userId;
public User() {
public String getFirstName() {
return firstName;
public void setFirstName(String firstName) {
this.firstName = firstName;
public String getLastName() {
return lastName;
public void setLastName(String lastName) {
this.lastName = lastName;
public String getPassword() {
return password;
public void setPassword(String password) {
this.password = password;
public String getUsername() {
return username;
public void setUsername(String username) {
this.username = username;
public Long getUserId() {
return userId;
public void setUserId(Long userId) {
this.userId = userId;
Step 5: STATELESS SESSION BEAN - In the EJB Node Right Click and Select EJB à New Entites from Table (JPA/EJB3.0)
Again Right Click on Model and create Session Bean from Wizard which creates two files –
UserDAOBean.java – Stateless Session Bean
UserDAO.java – Local Interface
package lux.facade;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import lux.domain.User;
@Stateless(name="UserDAO")
public class UserDAOBean implements UserDAO {
@PersistenceContext(unitName="Model")
private EntityManager em;
public UserDAOBean() {
public User getUser(int UserId) {
User u = new User();
u = em.find(User.class, UserId);
return u;
public List<User> getAllUsers() {
Query q = em.createQuery("SELECT u FROM User u");
List<User> users = q.getResultList();
return users;
public void createUser(User u) {
String hashedPw = hashPassword(u.getPassword());
u.setPassword(hashedPw);
em.persist(u);
public void updateUser(User u) {
String hashedPw = hashPassword(u.getPassword());
u.setPassword(hashedPw);
em.merge(u);
public void deleteUser(User u) {
em.remove(u);
private String hashPassword(String password) {
StringBuilder sb = new StringBuilder();
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA");
byte[] bs;
bs = messageDigest.digest(password.getBytes());
for (int i = 0; i < bs.length; i++) {
String hexVal = Integer.toHexString(0xFF & bs);
if (hexVal.length() == 1) {
sb.append("0");
sb.append(hexVal);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(UserDAOBean.class.getName()).log(Level.SEVERE, null, ex);
return sb.toString();
Step 6: Create a Deployment file in the Model and Deploy this to a JAR file
Step 7: Now Right Click on View/Controller Node and create a Java File –
UserController.java -
package lux.controllers;
import javax.ejb.EJB;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import lux.domain.User;
import lux.facade.UserDAO;
public class UserController {
@EJB UserDAO userDao;
private User user;
private DataModel model;
public String createUser() {
this.user = new User();
return "create_new_user";
public String saveUser() {
String r = "success";
try {
userDao.createUser(user);
} catch (Exception e) {
e.printStackTrace();
r = "failed";
return r;
public DataModel getUsers() {
model = new ListDataModel(userDao.getAllUsers());
return model;
public User getUser() {
return user;
public void setUser(User user) {
this.user = user;
Step 8: Configure page flow in faces-config.xml
1. Create the JSP file adduser.jsp by right-clicking View-Controller
node and selecting New > JSP. Use the wizard to create JSF – JSP Page, fill in
File Name adduser.jsp, click Finish. -
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>New user</title>
</head>
<body>
<f:view>
<h:form>
<h:messages/>
<h:panelGrid columns="2">
<h:outputText value="Username"/>
<h:inputText
id="Username"
value="#{user.user.username}"
required="true"/>
<h:outputText value="First name"/>
<h:inputText
id="FirstName"
value="#{user.user.firstName}" />
<h:outputText value="Last name"/>
<h:inputText
id="LastName"
value="#{user.user.lastName}" />
<h:outputText value="Password" />
<h:inputSecret
id="Password"
value="#{user.user.password}"
required="true" />
<h:panelGroup/>
<h:commandButton
action="#{user.saveUser}"
value="Save"/>
</h:panelGrid>
</h:form>
</f:view>
</body>
</html>
2. Repeat the previous step for another JSP file failed.jsp.
3. On failed.jsp add the string
Save failed
Next we configure the page flow.
1. Open faces-config.xml.
2. Create index.jsp -
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Listing</title>
</head>
<body>
<f:view>
<h:form>
<h:outputText value="User Listing"/>
<h:commandLink action="#{user.createUser}" value="Create a user"/>
<h:dataTable value="#{user.user}"
var="dataTableItem" border="1" cellpadding="2" cellspacing="2">
<h:column>
<f:facet name="header">
<h:outputText value="Username"/>
</f:facet>
<h:outputText value="#{dataTableItem.username}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="First name"/>
</f:facet>
<h:outputText value="#{dataTableItem.firstName}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Last name"/>
</f:facet>
<h:outputText value="#{dataTableItem.lastName}" />
</h:column>
</h:dataTable>
</h:form>
</f:view>
</body>
</html>
3. Drag an arrow from index.jsp to adduser.jsp and replace the arrow’s label to create_new_user.
4. Repeat the previous step for failed, by dragging and arrow from adduser.jsp to failed.jsp renaming the label to f
ailed
5. Finally repeat the step for adduser.jsp, by dragging from adduser.jsp to index.jsp renaming the label to success.
This creates the following faces-config.xml file –
<?xml version='1.0' encoding='UTF-8'?>
<faces-config>
<managed-bean>
<managed-bean-name>user</managed-bean-name>
<managed-bean-class>lux.controllers.UserController</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>username</property-name>
<value>#{username}</value>
</managed-property>
<managed-property>
<property-name>firstName</property-name>
<value>#{firstName}</value>
</managed-property>
<managed-property>
<property-name>lastName</property-name>
<value>#{lastName}</value>
</managed-property>
<managed-property>
<property-name>password</property-name>
<value>#{password}</value>
</managed-property>
</managed-bean>
<navigation-rule>
<from-view-id>/index.jsp</from-view-id>
<navigation-case>
<from-outcome>create_new_user</from-outcome>
<to-view-id>/adduser.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/adduser.jsp</from-view-id>
<navigation-case>
<from-outcome>failed</from-outcome>
<to-view-id>/failed.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/index.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
Step 9: Create a Deployment file in the View-Controller and Deploy this to a WAR file
Step 10: Create a Deployment file in the View-Controller and create an EAR file and add Model’s JAR and View-Controller’s
WAR files to it.
Step 11: Run the JSP Files
SCENARIO END
Now, When I execute Index.jsp, it does not list values from database and when I click on Create User link, it takes me to adduser.jsp page. When I fill values in this page and click Save button, it takes me to Save Failed page and data does not persist to the database.
WHAT IS WRONG OUT HERE ???If you set a breakpoint in your createUser method - does this code get executed?
We have a couple of tutorials that might show you how to do this.
EJB/JSF with ADF-binding tutorial:
http://www.oracle.com/technology/obe/obe1013jdev/10131/ejb_and_jpa/master-detail_pagewith_ejb.htm
EJB/JSF without ADF binding:
http://www.oracle.com/technology/obe/JavaEE_tutorial_10131/index.htm
Maybe you are looking for
-
Dreamweaver HTML Code view too small since Mac OS X 10.6.3
Has anyone run into this issue, since I loaded Snow Leopard my HTML code files viewed in Dreamweaver are so small and hard to read. The CSS files are just fine and a normal size. I have not found a way to increase the size of the view and that featur
-
I have a HP M1005 MFP printer which i usually connect on windows 8 64 bit. I require multi-page scanning for making pdf documents. Can we perform multi-page scanning in HP M1005 MFP? Help appriciated. Thank You.
-
My i movie keeps closing and turning my screen black
For the past couple of weeks my imovie has been closing and turning my home screen/ desktop black. I have tried updating my computer ; that has not work, i have tried reinstalling the program i believe and that has also not work... Please Help i rea
-
Does anyone know how to silently install the audio console with the new vista drivers. The usual -r for .iss files does not work, and either has the myriad of other switches to try to get this software installed. Even when you run the setup seperatly
-
Until recently I could click on resent sites in the address bar drop down, but now it just reloads the current page (still shows icons and addresses for the sites I'm clicking on). I've tired clearing history and cache, is this a known bug?