Database vs Serialization

Dear Experts
I am planning to do an Accounting Package for a Corporation and someone in our organization (who is great fan of serializations) is telling the higher ups that database is a wrong way to go. Serialization would be fast and cheap. I am a die hard database fanatic and i know that doing serializations would be like reinventing the wheel and security and reporting would be an issue. Please can someone suggest (there are likely to be 10000 Transactions in a year) a way to go!
Thanks and Best Regards
Manish

Biggest benefit of serialization: Instead of depending on the 'database guys', we can create new data types when we need them. (in some instances, that means: to hell with standards.) So we can add new 'columns' (fields) on the fly, maybe from a table source.
From a run time view, it can be a whole lot faster thatn extracting data from a DBl.
Serialization has the secondary benefits of allowing someone to create administration, security, backup and recovery, validation and constraint tools from scratch.
Sheer frustration for people who want to create ad-hoc, or defined, query systems. Popular tools don't work. In general, any data extract and any data manipulation depends on the original, and usually, ad-hoc spec.
Serialization is a great way of creating job security.
Been there ... thought it was wonderful. Until I couldn't get promoted (or a vacation) because I was the only one who was able to keep the system running. Even with docco.

Similar Messages

  • Using database to serialize an object

    I am confused as to the simplest way to serialize an object (actually a simple JavaBean) to a database through jdbc. What classes do I extend and what methods do I overwrite? There are no transient data involved.

    If you expect to serialize a complex java object directly to a Relational database, it would not be possible. There are no data types which can directly hold 'objects'.
    If you want to serialize a java object, and want to store it as text in a database, it would be possible. For this you can serialize the object first to a file may be, and then copy the contents of file to the database text filed.
    although doing this, in my opinion, makes no sense.
    Usually when you are serializing object data to a relational database you first map the data to equivalant Relational data ... A table or few colums of a table may represent your object.

  • Performance optimization during database selection.

    hi gurus,
    pls any explain about this...
    Strong knowledge of performance optimization during database selection.
    regards,
    praveen

    Hi Praveen,
    Performance Notes 
    1.Keep the Result Set Small 
    You should aim to keep the result set small. This reduces both the amount of memory used in the database system and the network load when transferring data to the application server. To reduce the size of your result sets, use the WHERE and HAVING clauses.
    Using the WHERE Clause
    Whenever you access a database table, you should use a WHERE clause in the corresponding Open SQL statement. Even if a program containing a SELECT statement with no WHERE clause performs well in tests, it may slow down rapidly in your production system, where the data volume increases daily. You should only dispense with the WHERE clause in exceptional cases where you really need the entire contents of the database table every time the statement is executed.
    When you use the WHERE clause, the database system optimizes the access and only transfers the required data. You should never transfer unwanted data to the application server and then filter it using ABAP statements.
    Using the HAVING Clause
    After selecting the required lines in the WHERE clause, the system then processes the GROUP BY clause, if one exists, and summarizes the database lines selected. The HAVING clause allows you to restrict the grouped lines, and in particular, the aggregate expressions, by applying further conditions.
    Effect
    If you use the WHERE and HAVING clauses correctly:
    •     There are no more physical I/Os in the database than necessary
    •     No unwanted data is stored in the database cache (it could otherwise displace data that is actually required)
    •     The CPU usage of the database host is minimize
    •     The network load is reduced, since only the data that is required by the application is transferred to the application server.
      Minimize the Amount of Data Transferred 
    Data is transferred between the database system and the application server in blocks. Each block is up to 32 KB in size (the precise size depends on your network communication hardware). Administration information is transported in the blocks as well as the data.
    To minimize the network load, you should transfer as few blocks as possible. Open SQL allows you to do this as follows:
    Restrict the Number of Lines
    If you only want to read a certain number of lines in a SELECT statement, use the UP TO <n> ROWS addition in the FROM clause. This tells the database system only to transfer <n> lines back to the application server. This is more efficient than transferring more lines than necessary back to the application server and then discarding them in your ABAP program.
    If you expect your WHERE clause to return a large number of duplicate entries, you can use the DISTINCT addition in the SELECT clause.
    Restrict the Number of Columns
    You should only read the columns from a database table that you actually need in the program. To do this, list the columns in the SELECT clause. Note here that the INTO CORRESPONDING FIELDS addition in the INTO clause is only efficient with large volumes of data, otherwise the runtime required to compare the names is too great. For small amounts of data, use a list of variables in the INTO clause.
    Do not use * to select all columns unless you really need them. However, if you list individual columns, you may have to adjust the program if the structure of the database table is changed in the ABAP Dictionary. If you specify the database table dynamically, you must always read all of its columns.
    Use Aggregate Functions
    If you only want to use data for calculations, it is often more efficient to use the aggregate functions of the SELECT clause than to read the individual entries from the database and perform the calculations in the ABAP program.
    Aggregate functions allow you to find out the number of values and find the sum, average, minimum, and maximum values.
    Following an aggregate expression, only its result is transferred from the database.
    Data Transfer when Changing Table Lines
    When you use the UPDATE statement to change lines in the table, you should use the WHERE clause to specify the relevant lines, and then SET statements to change only the required columns.
    When you use a work area to overwrite table lines, too much data is often transferred. Furthermore, this method requires an extra SELECT statement to fill the work area. Minimize the Number of Data Transfers 
    In every Open SQL statement, data is transferred between the application server and the database system. Furthermore, the database system has to construct or reopen the appropriate administration data for each database access. You can therefore minimize the load on the network and the database system by minimizing the number of times you access the database.
    Multiple Operations Instead of Single Operations
    When you change data using INSERT, UPDATE, and DELETE, use internal tables instead of single entries. If you read data using SELECT, it is worth using multiple operations if you want to process the data more than once, other wise, a simple select loop is more efficient.
    Avoid Repeated Access
    As a rule you should read a given set of data once only in your program, and using a single access. Avoid accessing the same data more than once (for example, SELECT before an UPDATE).
    Avoid Nested SELECT Loops
    A simple SELECT loop is a single database access whose result is passed to the ABAP program line by line. Nested SELECT loops mean that the number of accesses in the inner loop is multiplied by the number of accesses in the outer loop. You should therefore only use nested SELECT loops if the selection in the outer loop contains very few lines.
    However, using combinations of data from different database tables is more the rule than the exception in the relational data model. You can use the following techniques to avoid nested SELECT statements:
    ABAP Dictionary Views
    You can define joins between database tables statically and systemwide as views in the ABAP Dictionary. ABAP Dictionary views can be used by all ABAP programs. One of their advantages is that fields that are common to both tables (join fields) are only transferred once from the database to the application server.
    Views in the ABAP Dictionary are implemented as inner joins. If the inner table contains no lines that correspond to lines in the outer table, no data is transferred. This is not always the desired result. For example, when you read data from a text table, you want to include lines in the selection even if the corresponding text does not exist in the required language. If you want to include all of the data from the outer table, you can program a left outer join in ABAP.
    The links between the tables in the view are created and optimized by the database system. Like database tables, you can buffer views on the application server. The same buffering rules apply to views as to tables. In other words, it is most appropriate for views that you use mostly to read data. This reduces the network load and the amount of physical I/O in the database.
    Joins in the FROM Clause
    You can read data from more than one database table in a single SELECT statement by using inner or left outer joins in the FROM clause.
    The disadvantage of using joins is that redundant data is read from the hierarchically-superior table if there is a 1:N relationship between the outer and inner tables. This can considerably increase the amount of data transferred from the database to the application server. Therefore, when you program a join, you should ensure that the SELECT clause contains a list of only the columns that you really need. Furthermore, joins bypass the table buffer and read directly from the database. For this reason, you should use an ABAP Dictionary view instead of a join if you only want to read the data.
    The runtime of a join statement is heavily dependent on the database optimizer, especially when it contains more than two database tables. However, joins are nearly always quicker than using nested SELECT statements.
    Subqueries in the WHERE and HAVING Clauses
    Another way of accessing more than one database table in the same Open SQL statement is to use subqueries in the WHERE or HAVING clause. The data from a subquery is not transferred to the application server. Instead, it is used to evaluate conditions in the database system. This is a simple and effective way of programming complex database operations.
    Using Internal Tables
    It is also possible to avoid nested SELECT loops by placing the selection from the outer loop in an internal table and then running the inner selection once only using the FOR ALL ENTRIES addition. This technique stems from the time before joins were allowed in the FROM clause. On the other hand, it does prevent redundant data from being transferred from the database.
    Using a Cursor to Read Data
    A further method is to decouple the INTO clause from the SELECT statement by opening a cursor using OPEN CURSOR and reading data line by line using FETCH NEXT CURSOR. You must open a new cursor for each nested loop. In this case, you must ensure yourself that the correct lines are read from the database tables in the correct order. This usually requires a foreign key relationship between the database tables, and that they are sorted by the foreign key. Minimize the Search Overhead 
    You minimize the size of the result set by using the WHERE and HAVING clauses. To increase the efficiency of these clauses, you should formulate them to fit with the database table indexes.
    Database Indexes
    Indexes speed up data selection from the database. They consist of selected fields of a table, of which a copy is then made in sorted order. If you specify the index fields correctly in a condition in the WHERE or HAVING clause, the system only searches part of the index (index range scan).
    The primary index is always created automatically in the R/3 System. It consists of the primary key fields of the database table. This means that for each combination of fields in the index, there is a maximum of one line in the table. This kind of index is also known as UNIQUE.
    If you cannot use the primary index to determine the result set because, for example, none of the primary index fields occur in the WHERE or HAVING clause, the system searches through the entire table (full table scan). For this case, you can create secondary indexes, which can restrict the number of table entries searched to form the result set.
    You specify the fields of secondary indexes using the ABAP Dictionary. You can also determine whether the index is unique or not. However, you should not create secondary indexes to cover all possible combinations of fields.
    Only create one if you select data by fields that are not contained in another index, and the performance is very poor. Furthermore, you should only create secondary indexes for database tables from which you mainly read, since indexes have to be updated each time the database table is changed. As a rule, secondary indexes should not contain more than four fields, and you should not have more than five indexes for a single database table.
    If a table has more than five indexes, you run the risk of the optimizer choosing the wrong one for a particular operation. For this reason, you should avoid indexes with overlapping contents.
    Secondary indexes should contain columns that you use frequently in a selection, and that are as highly selective as possible. The fewer table entries that can be selected by a certain column, the higher that column’s selectivity. Place the most selective fields at the beginning of the index. Your secondary index should be so selective that each index entry corresponds to at most five percent of the table entries. If this is not the case, it is not worth creating the index. You should also avoid creating indexes for fields that are not always filled, where their value is initial for most entries in the table.
    If all of the columns in the SELECT clause are contained in the index, the system does not have to search the actual table data after reading from the index. If you have a SELECT clause with very few columns, you can improve performance dramatically by including these columns in a secondary index.
    Formulating Conditions for Indexes
    You should bear in mind the following when formulating conditions for the WHERE and HAVING clauses so that the system can use a database index and does not have to use a full table scan.
    Check for Equality and Link Using AND
    The database index search is particularly efficient if you check all index fields for equality (= or EQ) and link the expressions using AND.
    Use Positive Conditions
    The database system only supports queries that describe the result in positive terms, for example, EQ or LIKE. It does not support negative expressions like NE or NOT LIKE.
    If possible, avoid using the NOT operator in the WHERE clause, because it is not supported by database indexes; invert the logical expression instead.
    Using OR
    The optimizer usually stops working when an OR expression occurs in the condition. This means that the columns checked using OR are not included in the index search. An exception to this are OR expressions at the outside of conditions. You should try to reformulate conditions that apply OR expressions to columns relevant to the index, for example, into an IN condition.
    Using Part of the Index
    If you construct an index from several columns, the system can still use it even if you only specify a few of the columns in a condition. However, in this case, the sequence of the columns in the index is important. A column can only be used in the index search if all of the columns before it in the index definition have also been specified in the condition.
    Checking for Null Values
    The IS NULL condition can cause problems with indexes. Some database systems do not store null values in the index structure. Consequently, this field cannot be used in the index.
    Avoid Complex Conditions
    Avoid complex conditions, since the statements have to be broken down into their individual components by the database system. 
    Reduce the Database Load 
    Unlike application servers and presentation servers, there is only one database server in your system. You should therefore aim to reduce the database load as much as possible. You can use the following methods:
    Buffer Tables on the Application Server
    You can considerably reduce the time required to access data by buffering it in the application server table buffer. Reading a single entry from table T001 can take between 8 and 600 milliseconds, while reading it from the table buffer takes 0.2 - 1 milliseconds.
    Whether a table can be buffered or not depends its technical attributes in the ABAP Dictionary. There are three buffering types:
    •     Resident buffering (100%) The first time the table is accessed, its entire contents are loaded in the table buffer.
    •     Generic buffering In this case, you need to specify a generic key (some of the key fields) in the technical settings of the table in the ABAP Dictionary. The table contents are then divided into generic areas. When you access data with one of the generic keys, the whole generic area is loaded into the table buffer. Client-specific tables are often buffered generically by client.
    •     Partial buffering (single entry) Only single entries are read from the database and stored in the table buffer.
    When you read from buffered tables, the following happens:
    1.     An ABAP program requests data from a buffered table.
    2.     The ABAP processor interprets the Open SQL statement. If the table is defined as a buffered table in the ABAP Dictionary, the ABAP processor checks in the local buffer on the application server to see if the table (or part of it) has already been buffered.
    3.     If the table has not yet been buffered, the request is passed on to the database. If the data exists in the buffer, it is sent to the program.
    4.     The database server passes the data to the application server, which places it in the table buffer.
    5.     The data is passed to the program.
    When you change a buffered table, the following happens:
    1.     The database table is changed and the buffer on the application server is updated. The database interface logs the update statement in the table DDLOG. If the system has more than one application server, the buffer on the other servers is not updated at once.
    2.     All application servers periodically read the contents of table DDLOG, and delete the corresponding contents from their buffers where necessary. The granularity depends on the buffering type. The table buffers in a distributed system are generally synchronized every 60 seconds (parameter: rsdisp/bufreftime).
    3.     Within this period, users on non-synchronized application servers will read old data. The data is not recognized as obsolete until the next buffer synchronization. The next time it is accessed, it is re-read from the database.
    You should buffer the following types of tables:
    •     Tables that are read very frequently
    •     Tables that are changed very infrequently
    •     Relatively small tables (few lines, few columns, or short columns)
    •     Tables where delayed update is acceptable.
    Once you have buffered a table, take care not to use any Open SQL statements that bypass the buffer.
    The SELECT statement bypasses the buffer when you use any of the following:
    •     The BYPASSING BUFFER addition in the FROM clause
    •     The DISTINCT addition in the SELECT clause
    •     Aggregate expressions in the SELECT clause
    •     Joins in the FROM clause
    •     The IS NULL condition in the WHERE clause
    •     Subqueries in the WHERE clause
    •     The ORDER BY clause
    •     The GROUP BY clause
    •     The FOR UPDATE addition
    Furthermore, all Native SQL statements bypass the buffer.
    Avoid Reading Data Repeatedly
    If you avoid reading the same data repeatedly, you both reduce the number of database accesses and reduce the load on the database. Furthermore, a "dirty read" may occur with database tables other than Oracle. This means that the second time you read data from a database table, it may be different from the data read the first time. To ensure that the data in your program is consistent, you should read it once only and then store it in an internal table.
    Sort Data in Your ABAP Programs
    The ORDER BY clause in the SELECT statement is not necessarily optimized by the database system or executed with the correct index. This can result in increased runtime costs. You should only use ORDER BY if the database sort uses the same index with which the table is read. To find out which index the system uses, use SQL Trace in the ABAP Workbench Performance Trace. If the indexes are not the same, it is more efficient to read the data into an internal table or extract and sort it in the ABAP program using the SORT statement.
    Use Logical Databases
    SAP supplies logical databases for all applications. A logical database is an ABAP program that decouples Open SQL statements from application programs. They are optimized for the best possible database performance. However, it is important that you use the right logical database. The hierarchy of the data you want to read must reflect the structure of the logical database, otherwise, they can have a negative effect on performance. For example, if you want to read data from a table right at the bottom of the hierarchy of the logical database, it has to read at least the key fields of all tables above it in the hierarchy. In this case, it is more efficient to use a SELECT statement.
    Work Processes 
    Work processes execute the individual dialog steps in R/3 applications. The next two sections describe firstly the structure of a work process, and secondly the different types of work process in the R/3 System.
    Structure of a Work Process
    Work processes execute the dialog steps of application programs. They are components of an application server. The following diagram shows the components of a work process:
    Each work process contains two software processors and a database interface.
    Screen Processor
    In R/3 application programming, there is a difference between user interaction and processing logic. From a programming point of view, user interaction is controlled by screens. As well as the actual input mask, a screen also consists of flow logic. The screen flow logic controls a large part of the user interaction. The R/3 Basis system contains a special language for programming screen flow logic. The screen processor executes the screen flow logic. Via the dispatcher, it takes over the responsibility for communication between the work process and the SAPgui, calls modules in the flow logic, and ensures that the field contents are transferred from the screen to the flow logic.
    ABAP Processor
    The actual processing logic of an application program is written in ABAP - SAP’s own programming language. The ABAP processor executes the processing logic of the application program, and communicates with the database interface. The screen processor tells the ABAP processor which module of the screen flow logic should be processed next. The following screen illustrates the interaction between the screen and the ABAP processors when an application program is running.
    Database Interface
    The database interface provides the following services:
    •     Establishing and terminating connections between the work process and the database.
    •     Access to database tables
    •     Access to R/3 Repository objects (ABAP programs, screens and so on)
    •     Access to catalog information (ABAP Dictionary)
    •     Controlling transactions (commit and rollback handling)
    •     Table buffer administration on the application server.
    The following diagram shows the individual components of the database interface:
    The diagram shows that there are two different ways of accessing databases: Open SQL and Native SQL.
    Open SQL statements are a subset of Standard SQL that is fully integrated in ABAP. They allow you to access data irrespective of the database system that the R/3 installation is using. Open SQL consists of the Data Manipulation Language (DML) part of Standard SQL; in other words, it allows you to read (SELECT) and change (INSERT, UPDATE, DELETE) data. The tasks of the Data Definition Language (DDL) and Data Control Language (DCL) parts of Standard SQL are performed in the R/3 System by the ABAP Dictionary and the authorization system. These provide a unified range of functions, irrespective of database, and also contain functions beyond those offered by the various database systems.
    Open SQL also goes beyond Standard SQL to provide statements that, in conjunction with other ABAP constructions, can simplify or speed up database access. It also allows you to buffer certain tables on the application server, saving excessive database access. In this case, the database interface is responsible for comparing the buffer with the database. Buffers are partly stored in the working memory of the current work process, and partly in the shared memory for all work processes on an application server. Where an R/3 System is distributed across more than one application server, the data in the various buffers is synchronized at set intervals by the buffer management. When buffering the database, you must remember that data in the buffer is not always up to date. For this reason, you should only use the buffer for data which does not often change.
    Native SQL is only loosely integrated into ABAP, and allows access to all of the functions contained in the programming interface of the respective database system. Unlike Open SQL statements, Native SQL statements are not checked and converted, but instead are sent directly to the database system. Programs that use Native SQL are specific to the database system for which they were written. R/3 applications contain as little Native SQL as possible. In fact, it is only used in a few Basis components (for example, to create or change table definitions in the ABAP Dictionary).
    The database-dependent layer in the diagram serves to hide the differences between database systems from the rest of the database interface. You choose the appropriate layer when you install the Basis system. Thanks to the standardization of SQL, the differences in the syntax of statements are very slight. However, the semantics and behavior of the statements have not been fully standardized, and the differences in these areas can be greater. When you use Native SQL, the function of the database-dependent layer is minimal.
    Types of Work Process
    Although all work processes contain the components described above, they can still be divided into different types. The type of a work process determines the kind of task for which it is responsible in the application server. It does not specify a particular set of technical attributes. The individual tasks are distributed to the work processes by the dispatcher.
    Before you start your R/3 System, you determine how many work processes it will have, and what their types will be. The dispatcher starts the work processes and only assigns them tasks that correspond to their type. This means that you can distribute work process types to optimize the use of the resources on your application servers.
    The following diagram shows again the structure of an application server, but this time, includes the various possible work process types:
    The various work processes are described briefly below. Other parts of this documentation describe the individual components of the application server and the R/3 System in more detail.
    Dialog Work Process
    Dialog work processes deal with requests from an active user to execute dialog steps.
    Update Work Process
    Update work processes execute database update requests. Update requests are part of an SAP LUW that bundle the database operations resulting from the dialog in a database LUW for processing in the background.
    Background Work Process
    Background work processes process programs that can be executed without user interaction (background jobs).
    Enqueue Work Process
    The enqueue work process administers a lock table in the shared memory area. The lock table contains the logical database locks for the R/3 System and is an important part of the SAP LUW concept. In an R/3 System, you may only have one lock table. You may therefore also only have one application server with enqueue work processes.
    Spool Work Process
    The spool work process passes sequential datasets to a printer or to optical archiving. Each application server may contain several spool work process.
    The services offered by an application server are determined by the types of its work processes. One application server may, of course, have more than one function. For example, it may be both a dialog server and the enqueue server, if it has several dialog work processes and an enqueue work process.
    You can use the system administration functions to switch a work process between dialog and background modes while the system is still running. This allows you, for example, to switch an R/3 System between day and night operation, where you have more dialog than background work processes during the day, and the other way around during the night.
    ABAP Application Server 
    R/3 programs run on application servers. They are an important component of the R/3 System. The following sections describe application servers in more detail.
    Structure of an ABAP Application Server
    The application layer of an R/3 System is made up of the application servers and the message server. Application programs in an R/3 System are run on application servers. The application servers communicate with the presentation components, the database, and also with each other, using the message server.
    The following diagram shows the structure of an application server:
    The individual components are:
    Work Processes
    An application server contains work processes, which are components that can run an application. Work processes are components that are able to execute an application (that is, one dialog step each). Each work process is linked to a memory area containing the context of the application being run. The context contains the current data for the application program. This needs to be available in each dialog step. Further information about the different types of work process is contained later on in this documentation.
    Dispatcher
    Each application server contains a dispatcher. The dispatcher is the link between the work processes and the users logged onto the application server. Its task is to receive requests for dialog steps from the SAP GUI and direct them to a free work process. In the same way, it directs screen output resulting from the dialog step back to the appropriate user.
    Gateway
    Each application server contains a gateway. This is the interface for the R/3 communication protocols (RFC, CPI/C). It can communicate with other application servers in the same R/3 System, with other R/3 Systems, with R/2 Systems, or with non-SAP systems.
    The application server structure as described here aids the performance and scalability of the entire R/3 System. The fixed number of work processes and dispatching of dialog steps leads to optimal memory use, since it means that certain components and the memory areas of a work process are application-independent and reusable. The fact that the individual work processes work independently makes them suitable for a multi-processor architecture. The methods used in the dispatcher to distribute tasks to work processes are discussed more closely in the section Dispatching Dialog Steps.
    Shared Memory
    All of the work processes on an application server use a common main memory area called shared memory to save contexts or to buffer constant data locally.
    The resources that all work processes use (such as programs and table contents) are contained in shared memory. Memory management in the R/3 System ensures that the work processes always address the correct context, that is the data relevant to the current state of the program that is running.  A mapping process projects the required context for a dialog step from shared memory into the address of the relevant work process. This reduces the actual copying to a minimum.
    Local buffering of data in the shared memory of the application server reduces the number of database reads required. This reduces access times for application programs considerably. For optimal use of the buffer, you can concentrate individual applications (financial accounting, logistics, human resources) into separate application server groups.
    Database Connection
    When you start up an R/3 System, each application server registers its work processes with the database layer, and receives a single dedicated channel for each. While the system is running, each work process is a user (client) of the database system (server). You cannot change the work process registration while the system is running. Neither can you reassign a database channel from one work process to another. For this reason, a work process can only make database changes within a single database logical unit of work (LUW). A database LUW is an inseparable sequence of database operations. This has important consequences for the programming model explained below.
    Dispatching Dialog Steps
    The number of users logged onto an application server is often many times greater than the number of available work processes. Furthermore, it is not restricted by the R/3 system architecture. Furthermore, each user can run several applications at once. The dispatcher has the important task of distributing all dialog steps among the work processes on the application server.
    The following diagram is an example of how this might happen:
           1.      The dispatcher receives the request to execute a dialog step from user 1 and directs it to work process 1, which happens to be free. The work process addresses the context of the application program (in shared memory) and executes the dialog step. It then becomes free again.
           2.      The dispatcher receives the request to execute a dialog step from user 2 and directs it to work process 1, which is now free again. The work process executes the dialog step as in step 1.
           3.      While work process 1 is still working, the dispatcher receives a further request from user 1 and directs it to work process 2, which is free.
           4.      After work processes 1 and 2 have finished processing their dialog steps, the dispatcher receives another request from user 1 and directs it to work process 1, which is free again.
           5.      While work process 1 is still working, the dispatcher receives a further request from user 2 and directs it to work process 2, which is free.
    From this example, we can see that:
    •        A dialog step from a program is assigned to a single work process for execution.
    •        The individual dialog steps of a program can be executed on different work processes, and the program context must be addressed for each new work process.
    •        A work process can execute dialog steps of different programs from different users.
    The example does not show that the dispatcher tries to distribute the requests to the work processes such that the same work process is used as often as possible for the successive dialog steps in an application. This is useful, since it saves the program context having to be addressed each time a dialog step is executed.
    Dispatching and the Programming Model
    The separation of application and presentation layer made it necessary to split up application programs into dialog steps. This, and the fact that dialog steps are dispatched to individual work processes, has had important consequences for the programming model.
    As mentioned above, a work process can only make database changes within a single database logical unit of work (LUW). A database LUW is an inseparable sequence of database operations. The contents of the database must be consistent at its beginning and end. The beginning and end of a database LUW are defined by a commit command to the database system (database commit). During a database LUW, that is, between two database commits, the database system itself ensures consistency within the database. In other words, it takes over tasks such as locking database entries while they are being edited, or restoring the old data (rollback) if a step terminates in an error.
    A typical SAP application program extends over several screens and the corresponding dialog steps. The user requests database changes on the individual screens that should lead to the database being consistent once the screens have all been processed. However, the individual dialog steps run on different work processes, and a single work process can process dialog steps from other applications. It is clear that two or more independent applications whose dialog steps happen to be processed on the same work process cannot be allowed to work with the same database LUW.
    Consequently, a work process must open a separate database LUW for each dialog step. The work process sends a commit command (database commit) to the database at the end of each dialog step in which it makes database changes. These commit commands are called implicit database commits, since they are not explicitly written into the application program.
    These implicit database commits mean that a database LUW can be kept open for a maximum of one dialog step. This leads to a considerable reduction in database load, serialization, and deadlocks, and enables a large number of users to use the same system.
    However, the question now arises of how this method (1 dialog step = 1 database LUW) can be reconciled with the demand to make commits and rollbacks dependent on the logical flow of the application program instead of the technical distribution of dialog steps. Database update requests that depend on one another form logical units in the program that extend over more than one dialog step. The database changes associated with these logical units must be executed together and must also be able to be undone together.
    The SAP programming model contains a series of bundling techniques that allow you to group database updates together in logical units. The section of an R/3 application program that bundles a set of logically-associated database operations is called an SAP LUW. Unlike a database LUW, a SAP LUW includes all of the dialog steps in a logical unit, including the database update.
    Happy Reading...
    shibu

  • How to select the data efficiently from the table

    hi every one,
      i need some help in selecting data from FAGLFLEXA table.i have to select many amounts from different group of G/L accounts
    (groups are predefined here  which contains a set of g/L account no.).
    if i select every time for each group then it will be a performance issue, in order to avoid it what should i do, can any one suggest me a method or a smaple query so that i can perform the task efficiently.

    Hi ,
    1.select and keep the data in internal table
    2.avoid select inside loop ..endloop.
    3.try to use for all entries
    check the below details
    Hi Praveen,
    Performance Notes
    1.Keep the Result Set Small
    You should aim to keep the result set small. This reduces both the amount of memory used in the database system and the network load when transferring data to the application server. To reduce the size of your result sets, use the WHERE and HAVING clauses.
    Using the WHERE Clause
    Whenever you access a database table, you should use a WHERE clause in the corresponding Open SQL statement. Even if a program containing a SELECT statement with no WHERE clause performs well in tests, it may slow down rapidly in your production system, where the data volume increases daily. You should only dispense with the WHERE clause in exceptional cases where you really need the entire contents of the database table every time the statement is executed.
    When you use the WHERE clause, the database system optimizes the access and only transfers the required data. You should never transfer unwanted data to the application server and then filter it using ABAP statements.
    Using the HAVING Clause
    After selecting the required lines in the WHERE clause, the system then processes the GROUP BY clause, if one exists, and summarizes the database lines selected. The HAVING clause allows you to restrict the grouped lines, and in particular, the aggregate expressions, by applying further conditions.
    Effect
    If you use the WHERE and HAVING clauses correctly:
    • There are no more physical I/Os in the database than necessary
    • No unwanted data is stored in the database cache (it could otherwise displace data that is actually required)
    • The CPU usage of the database host is minimize
    • The network load is reduced, since only the data that is required by the application is transferred to the application server.
    Minimize the Amount of Data Transferred
    Data is transferred between the database system and the application server in blocks. Each block is up to 32 KB in size (the precise size depends on your network communication hardware). Administration information is transported in the blocks as well as the data.
    To minimize the network load, you should transfer as few blocks as possible. Open SQL allows you to do this as follows:
    Restrict the Number of Lines
    If you only want to read a certain number of lines in a SELECT statement, use the UP TO <n> ROWS addition in the FROM clause. This tells the database system only to transfer <n> lines back to the application server. This is more efficient than transferring more lines than necessary back to the application server and then discarding them in your ABAP program.
    If you expect your WHERE clause to return a large number of duplicate entries, you can use the DISTINCT addition in the SELECT clause.
    Restrict the Number of Columns
    You should only read the columns from a database table that you actually need in the program. To do this, list the columns in the SELECT clause. Note here that the INTO CORRESPONDING FIELDS addition in the INTO clause is only efficient with large volumes of data, otherwise the runtime required to compare the names is too great. For small amounts of data, use a list of variables in the INTO clause.
    Do not use * to select all columns unless you really need them. However, if you list individual columns, you may have to adjust the program if the structure of the database table is changed in the ABAP Dictionary. If you specify the database table dynamically, you must always read all of its columns.
    Use Aggregate Functions
    If you only want to use data for calculations, it is often more efficient to use the aggregate functions of the SELECT clause than to read the individual entries from the database and perform the calculations in the ABAP program.
    Aggregate functions allow you to find out the number of values and find the sum, average, minimum, and maximum values.
    Following an aggregate expression, only its result is transferred from the database.
    Data Transfer when Changing Table Lines
    When you use the UPDATE statement to change lines in the table, you should use the WHERE clause to specify the relevant lines, and then SET statements to change only the required columns.
    When you use a work area to overwrite table lines, too much data is often transferred. Furthermore, this method requires an extra SELECT statement to fill the work area. Minimize the Number of Data Transfers
    In every Open SQL statement, data is transferred between the application server and the database system. Furthermore, the database system has to construct or reopen the appropriate administration data for each database access. You can therefore minimize the load on the network and the database system by minimizing the number of times you access the database.
    Multiple Operations Instead of Single Operations
    When you change data using INSERT, UPDATE, and DELETE, use internal tables instead of single entries. If you read data using SELECT, it is worth using multiple operations if you want to process the data more than once, other wise, a simple select loop is more efficient.
    Avoid Repeated Access
    As a rule you should read a given set of data once only in your program, and using a single access. Avoid accessing the same data more than once (for example, SELECT before an UPDATE).
    Avoid Nested SELECT Loops
    A simple SELECT loop is a single database access whose result is passed to the ABAP program line by line. Nested SELECT loops mean that the number of accesses in the inner loop is multiplied by the number of accesses in the outer loop. You should therefore only use nested SELECT loops if the selection in the outer loop contains very few lines.
    However, using combinations of data from different database tables is more the rule than the exception in the relational data model. You can use the following techniques to avoid nested SELECT statements:
    ABAP Dictionary Views
    You can define joins between database tables statically and systemwide as views in the ABAP Dictionary. ABAP Dictionary views can be used by all ABAP programs. One of their advantages is that fields that are common to both tables (join fields) are only transferred once from the database to the application server.
    Views in the ABAP Dictionary are implemented as inner joins. If the inner table contains no lines that correspond to lines in the outer table, no data is transferred. This is not always the desired result. For example, when you read data from a text table, you want to include lines in the selection even if the corresponding text does not exist in the required language. If you want to include all of the data from the outer table, you can program a left outer join in ABAP.
    The links between the tables in the view are created and optimized by the database system. Like database tables, you can buffer views on the application server. The same buffering rules apply to views as to tables. In other words, it is most appropriate for views that you use mostly to read data. This reduces the network load and the amount of physical I/O in the database.
    Joins in the FROM Clause
    You can read data from more than one database table in a single SELECT statement by using inner or left outer joins in the FROM clause.
    The disadvantage of using joins is that redundant data is read from the hierarchically-superior table if there is a 1:N relationship between the outer and inner tables. This can considerably increase the amount of data transferred from the database to the application server. Therefore, when you program a join, you should ensure that the SELECT clause contains a list of only the columns that you really need. Furthermore, joins bypass the table buffer and read directly from the database. For this reason, you should use an ABAP Dictionary view instead of a join if you only want to read the data.
    The runtime of a join statement is heavily dependent on the database optimizer, especially when it contains more than two database tables. However, joins are nearly always quicker than using nested SELECT statements.
    Subqueries in the WHERE and HAVING Clauses
    Another way of accessing more than one database table in the same Open SQL statement is to use subqueries in the WHERE or HAVING clause. The data from a subquery is not transferred to the application server. Instead, it is used to evaluate conditions in the database system. This is a simple and effective way of programming complex database operations.
    Using Internal Tables
    It is also possible to avoid nested SELECT loops by placing the selection from the outer loop in an internal table and then running the inner selection once only using the FOR ALL ENTRIES addition. This technique stems from the time before joins were allowed in the FROM clause. On the other hand, it does prevent redundant data from being transferred from the database.
    Using a Cursor to Read Data
    A further method is to decouple the INTO clause from the SELECT statement by opening a cursor using OPEN CURSOR and reading data line by line using FETCH NEXT CURSOR. You must open a new cursor for each nested loop. In this case, you must ensure yourself that the correct lines are read from the database tables in the correct order. This usually requires a foreign key relationship between the database tables, and that they are sorted by the foreign key. Minimize the Search Overhead
    You minimize the size of the result set by using the WHERE and HAVING clauses. To increase the efficiency of these clauses, you should formulate them to fit with the database table indexes.
    Database Indexes
    Indexes speed up data selection from the database. They consist of selected fields of a table, of which a copy is then made in sorted order. If you specify the index fields correctly in a condition in the WHERE or HAVING clause, the system only searches part of the index (index range scan).
    The primary index is always created automatically in the R/3 System. It consists of the primary key fields of the database table. This means that for each combination of fields in the index, there is a maximum of one line in the table. This kind of index is also known as UNIQUE.
    If you cannot use the primary index to determine the result set because, for example, none of the primary index fields occur in the WHERE or HAVING clause, the system searches through the entire table (full table scan). For this case, you can create secondary indexes, which can restrict the number of table entries searched to form the result set.
    You specify the fields of secondary indexes using the ABAP Dictionary. You can also determine whether the index is unique or not. However, you should not create secondary indexes to cover all possible combinations of fields.
    Only create one if you select data by fields that are not contained in another index, and the performance is very poor. Furthermore, you should only create secondary indexes for database tables from which you mainly read, since indexes have to be updated each time the database table is changed. As a rule, secondary indexes should not contain more than four fields, and you should not have more than five indexes for a single database table.
    If a table has more than five indexes, you run the risk of the optimizer choosing the wrong one for a particular operation. For this reason, you should avoid indexes with overlapping contents.
    Secondary indexes should contain columns that you use frequently in a selection, and that are as highly selective as possible. The fewer table entries that can be selected by a certain column, the higher that column’s selectivity. Place the most selective fields at the beginning of the index. Your secondary index should be so selective that each index entry corresponds to at most five percent of the table entries. If this is not the case, it is not worth creating the index. You should also avoid creating indexes for fields that are not always filled, where their value is initial for most entries in the table.
    If all of the columns in the SELECT clause are contained in the index, the system does not have to search the actual table data after reading from the index. If you have a SELECT clause with very few columns, you can improve performance dramatically by including these columns in a secondary index.
    Formulating Conditions for Indexes
    You should bear in mind the following when formulating conditions for the WHERE and HAVING clauses so that the system can use a database index and does not have to use a full table scan.
    Check for Equality and Link Using AND
    The database index search is particularly efficient if you check all index fields for equality (= or EQ) and link the expressions using AND.
    Use Positive Conditions
    The database system only supports queries that describe the result in positive terms, for example, EQ or LIKE. It does not support negative expressions like NE or NOT LIKE.
    If possible, avoid using the NOT operator in the WHERE clause, because it is not supported by database indexes; invert the logical expression instead.
    Using OR
    The optimizer usually stops working when an OR expression occurs in the condition. This means that the columns checked using OR are not included in the index search. An exception to this are OR expressions at the outside of conditions. You should try to reformulate conditions that apply OR expressions to columns relevant to the index, for example, into an IN condition.
    Using Part of the Index
    If you construct an index from several columns, the system can still use it even if you only specify a few of the columns in a condition. However, in this case, the sequence of the columns in the index is important. A column can only be used in the index search if all of the columns before it in the index definition have also been specified in the condition.
    Checking for Null Values
    The IS NULL condition can cause problems with indexes. Some database systems do not store null values in the index structure. Consequently, this field cannot be used in the index.
    Avoid Complex Conditions
    Avoid complex conditions, since the statements have to be broken down into their individual components by the database system.
    Reduce the Database Load
    Unlike application servers and presentation servers, there is only one database server in your system. You should therefore aim to reduce the database load as much as possible. You can use the following methods:
    Buffer Tables on the Application Server
    You can considerably reduce the time required to access data by buffering it in the application server table buffer. Reading a single entry from table T001 can take between 8 and 600 milliseconds, while reading it from the table buffer takes 0.2 - 1 milliseconds.
    Whether a table can be buffered or not depends its technical attributes in the ABAP Dictionary. There are three buffering types:
    • Resident buffering (100%) The first time the table is accessed, its entire contents are loaded in the table buffer.
    • Generic buffering In this case, you need to specify a generic key (some of the key fields) in the technical settings of the table in the ABAP Dictionary. The table contents are then divided into generic areas. When you access data with one of the generic keys, the whole generic area is loaded into the table buffer. Client-specific tables are often buffered generically by client.
    • Partial buffering (single entry) Only single entries are read from the database and stored in the table buffer.
    When you read from buffered tables, the following happens:
    1. An ABAP program requests data from a buffered table.
    2. The ABAP processor interprets the Open SQL statement. If the table is defined as a buffered table in the ABAP Dictionary, the ABAP processor checks in the local buffer on the application server to see if the table (or part of it) has already been buffered.
    3. If the table has not yet been buffered, the request is passed on to the database. If the data exists in the buffer, it is sent to the program.
    4. The database server passes the data to the application server, which places it in the table buffer.
    5. The data is passed to the program.
    When you change a buffered table, the following happens:
    1. The database table is changed and the buffer on the application server is updated. The database interface logs the update statement in the table DDLOG. If the system has more than one application server, the buffer on the other servers is not updated at once.
    2. All application servers periodically read the contents of table DDLOG, and delete the corresponding contents from their buffers where necessary. The granularity depends on the buffering type. The table buffers in a distributed system are generally synchronized every 60 seconds (parameter: rsdisp/bufreftime).
    3. Within this period, users on non-synchronized application servers will read old data. The data is not recognized as obsolete until the next buffer synchronization. The next time it is accessed, it is re-read from the database.
    You should buffer the following types of tables:
    • Tables that are read very frequently
    • Tables that are changed very infrequently
    • Relatively small tables (few lines, few columns, or short columns)
    • Tables where delayed update is acceptable.
    Once you have buffered a table, take care not to use any Open SQL statements that bypass the buffer.
    The SELECT statement bypasses the buffer when you use any of the following:
    • The BYPASSING BUFFER addition in the FROM clause
    • The DISTINCT addition in the SELECT clause
    • Aggregate expressions in the SELECT clause
    • Joins in the FROM clause
    • The IS NULL condition in the WHERE clause
    • Subqueries in the WHERE clause
    • The ORDER BY clause
    • The GROUP BY clause
    • The FOR UPDATE addition
    Furthermore, all Native SQL statements bypass the buffer.
    Avoid Reading Data Repeatedly
    If you avoid reading the same data repeatedly, you both reduce the number of database accesses and reduce the load on the database. Furthermore, a "dirty read" may occur with database tables other than Oracle. This means that the second time you read data from a database table, it may be different from the data read the first time. To ensure that the data in your program is consistent, you should read it once only and then store it in an internal table.
    Sort Data in Your ABAP Programs
    The ORDER BY clause in the SELECT statement is not necessarily optimized by the database system or executed with the correct index. This can result in increased runtime costs. You should only use ORDER BY if the database sort uses the same index with which the table is read. To find out which index the system uses, use SQL Trace in the ABAP Workbench Performance Trace. If the indexes are not the same, it is more efficient to read the data into an internal table or extract and sort it in the ABAP program using the SORT statement.
    Use Logical Databases
    SAP supplies logical databases for all applications. A logical database is an ABAP program that decouples Open SQL statements from application programs. They are optimized for the best possible database performance. However, it is important that you use the right logical database. The hierarchy of the data you want to read must reflect the structure of the logical database, otherwise, they can have a negative effect on performance. For example, if you want to read data from a table right at the bottom of the hierarchy of the logical database, it has to read at least the key fields of all tables above it in the hierarchy. In this case, it is more efficient to use a SELECT statement.
    Work Processes
    Work processes execute the individual dialog steps in R/3 applications. The next two sections describe firstly the structure of a work process, and secondly the different types of work process in the R/3 System.
    Structure of a Work Process
    Work processes execute the dialog steps of application programs. They are components of an application server. The following diagram shows the components of a work process:
    Each work process contains two software processors and a database interface.
    Screen Processor
    In R/3 application programming, there is a difference between user interaction and processing logic. From a programming point of view, user interaction is controlled by screens. As well as the actual input mask, a screen also consists of flow logic. The screen flow logic controls a large part of the user interaction. The R/3 Basis system contains a special language for programming screen flow logic. The screen processor executes the screen flow logic. Via the dispatcher, it takes over the responsibility for communication between the work process and the SAPgui, calls modules in the flow logic, and ensures that the field contents are transferred from the screen to the flow logic.
    ABAP Processor
    The actual processing logic of an application program is written in ABAP - SAP’s own programming language. The ABAP processor executes the processing logic of the application program, and communicates with the database interface. The screen processor tells the ABAP processor which module of the screen flow logic should be processed next. The following screen illustrates the interaction between the screen and the ABAP processors when an application program is running.
    Database Interface
    The database interface provides the following services:
    • Establishing and terminating connections between the work process and the database.
    • Access to database tables
    • Access to R/3 Repository objects (ABAP programs, screens and so on)
    • Access to catalog information (ABAP Dictionary)
    • Controlling transactions (commit and rollback handling)
    • Table buffer administration on the application server.
    The following diagram shows the individual components of the database interface:
    The diagram shows that there are two different ways of accessing databases: Open SQL and Native SQL.
    Open SQL statements are a subset of Standard SQL that is fully integrated in ABAP. They allow you to access data irrespective of the database system that the R/3 installation is using. Open SQL consists of the Data Manipulation Language (DML) part of Standard SQL; in other words, it allows you to read (SELECT) and change (INSERT, UPDATE, DELETE) data. The tasks of the Data Definition Language (DDL) and Data Control Language (DCL) parts of Standard SQL are performed in the R/3 System by the ABAP Dictionary and the authorization system. These provide a unified range of functions, irrespective of database, and also contain functions beyond those offered by the various database systems.
    Open SQL also goes beyond Standard SQL to provide statements that, in conjunction with other ABAP constructions, can simplify or speed up database access. It also allows you to buffer certain tables on the application server, saving excessive database access. In this case, the database interface is responsible for comparing the buffer with the database. Buffers are partly stored in the working memory of the current work process, and partly in the shared memory for all work processes on an application server. Where an R/3 System is distributed across more than one application server, the data in the various buffers is synchronized at set intervals by the buffer management. When buffering the database, you must remember that data in the buffer is not always up to date. For this reason, you should only use the buffer for data which does not often change.
    Native SQL is only loosely integrated into ABAP, and allows access to all of the functions contained in the programming interface of the respective database system. Unlike Open SQL statements, Native SQL statements are not checked and converted, but instead are sent directly to the database system. Programs that use Native SQL are specific to the database system for which they were written. R/3 applications contain as little Native SQL as possible. In fact, it is only used in a few Basis components (for example, to create or change table definitions in the ABAP Dictionary).
    The database-dependent layer in the diagram serves to hide the differences between database systems from the rest of the database interface. You choose the appropriate layer when you install the Basis system. Thanks to the standardization of SQL, the differences in the syntax of statements are very slight. However, the semantics and behavior of the statements have not been fully standardized, and the differences in these areas can be greater. When you use Native SQL, the function of the database-dependent layer is minimal.
    Types of Work Process
    Although all work processes contain the components described above, they can still be divided into different types. The type of a work process determines the kind of task for which it is responsible in the application server. It does not specify a particular set of technical attributes. The individual tasks are distributed to the work processes by the dispatcher.
    Before you start your R/3 System, you determine how many work processes it will have, and what their types will be. The dispatcher starts the work processes and only assigns them tasks that correspond to their type. This means that you can distribute work process types to optimize the use of the resources on your application servers.
    The following diagram shows again the structure of an application server, but this time, includes the various possible work process types:
    The various work processes are described briefly below. Other parts of this documentation describe the individual components of the application server and the R/3 System in more detail.
    Dialog Work Process
    Dialog work processes deal with requests from an active user to execute dialog steps.
    Update Work Process
    Update work processes execute database update requests. Update requests are part of an SAP LUW that bundle the database operations resulting from the dialog in a database LUW for processing in the background.
    Background Work Process
    Background work processes process programs that can be executed without user interaction (background jobs).
    Enqueue Work Process
    The enqueue work process administers a lock table in the shared memory area. The lock table contains the logical database locks for the R/3 System and is an important part of the SAP LUW concept. In an R/3 System, you may only have one lock table. You may therefore also only have one application server with enqueue work processes.
    Spool Work Process
    The spool work process passes sequential datasets to a printer or to optical archiving. Each application server may contain several spool work process.
    The services offered by an application server are determined by the types of its work processes. One application server may, of course, have more than one function. For example, it may be both a dialog server and the enqueue server, if it has several dialog work processes and an enqueue work process.
    You can use the system administration functions to switch a work process between dialog and background modes while the system is still running. This allows you, for example, to switch an R/3 System between day and night operation, where you have more dialog than background work processes during the day, and the other way around during the night.
    ABAP Application Server
    R/3 programs run on application servers. They are an important component of the R/3 System. The following sections describe application servers in more detail.
    Structure of an ABAP Application Server
    The application layer of an R/3 System is made up of the application servers and the message server. Application programs in an R/3 System are run on application servers. The application servers communicate with the presentation components, the database, and also with each other, using the message server.
    The following diagram shows the structure of an application server:
    The individual components are:
    Work Processes
    An application server contains work processes, which are components that can run an application. Work processes are components that are able to execute an application (that is, one dialog step each). Each work process is linked to a memory area containing the context of the application being run. The context contains the current data for the application program. This needs to be available in each dialog step. Further information about the different types of work process is contained later on in this documentation.
    Dispatcher
    Each application server contains a dispatcher. The dispatcher is the link between the work processes and the users logged onto the application server. Its task is to receive requests for dialog steps from the SAP GUI and direct them to a free work process. In the same way, it directs screen output resulting from the dialog step back to the appropriate user.
    Gateway
    Each application server contains a gateway. This is the interface for the R/3 communication protocols (RFC, CPI/C). It can communicate with other application servers in the same R/3 System, with other R/3 Systems, with R/2 Systems, or with non-SAP systems.
    The application server structure as described here aids the performance and scalability of the entire R/3 System. The fixed number of work processes and dispatching of dialog steps leads to optimal memory use, since it means that certain components and the memory areas of a work process are application-independent and reusable. The fact that the individual work processes work independently makes them suitable for a multi-processor architecture. The methods used in the dispatcher to distribute tasks to work processes are discussed more closely in the section Dispatching Dialog Steps.
    Shared Memory
    All of the work processes on an application server use a common main memory area called shared memory to save contexts or to buffer constant data locally.
    The resources that all work processes use (such as programs and table contents) are contained in shared memory. Memory management in the R/3 System ensures that the work processes always address the correct context, that is the data relevant to the current state of the program that is running. A mapping process projects the required context for a dialog step from shared memory into the address of the relevant work process. This reduces the actual copying to a minimum.
    Local buffering of data in the shared memory of the application server reduces the number of database reads required. This reduces access times for application programs considerably. For optimal use of the buffer, you can concentrate individual applications (financial accounting, logistics, human resources) into separate application server groups.
    Database Connection
    When you start up an R/3 System, each application server registers its work processes with the database layer, and receives a single dedicated channel for each. While the system is running, each work process is a user (client) of the database system (server). You cannot change the work process registration while the system is running. Neither can you reassign a database channel from one work process to another. For this reason, a work process can only make database changes within a single database logical unit of work (LUW). A database LUW is an inseparable sequence of database operations. This has important consequences for the programming model explained below.
    Dispatching Dialog Steps
    The number of users logged onto an application server is often many times greater than the number of available work processes. Furthermore, it is not restricted by the R/3 system architecture. Furthermore, each user can run several applications at once. The dispatcher has the important task of distributing all dialog steps among the work processes on the application server.
    The following diagram is an example of how this might happen:
    1. The dispatcher receives the request to execute a dialog step from user 1 and directs it to work process 1, which happens to be free. The work process addresses the context of the application program (in shared memory) and executes the dialog step. It then becomes free again.
    2. The dispatcher receives the request to execute a dialog step from user 2 and directs it to work process 1, which is now free again. The work process executes the dialog step as in step 1.
    3. While work process 1 is still working, the dispatcher receives a further request from user 1 and directs it to work process 2, which is free.
    4. After work processes 1 and 2 have finished processing their dialog steps, the dispatcher receives another request from user 1 and directs it to work process 1, which is free again.
    5. While work process 1 is still working, the dispatcher receives a further request from user 2 and directs it to work process 2, which is free.
    From this example, we can see that:
    • A dialog step from a program is assigned to a single work process for execution.
    • The individual dialog steps of a program can be executed on different work processes, and the program context must be addressed for each new work process.
    • A work process can execute dialog steps of different programs from different users.
    The example does not show that the dispatcher tries to distribute the requests to the work processes such that the same work process is used as often as possible for the successive dialog steps in an application. This is useful, since it saves the program context having to be addressed each time a dialog step is executed.
    Dispatching and the Programming Model
    The separation of application and presentation layer made it necessary to split up application programs into dialog steps. This, and the fact that dialog steps are dispatched to individual work processes, has had important consequences for the programming model.
    As mentioned above, a work process can only make database changes within a single database logical unit of work (LUW). A database LUW is an inseparable sequence of database operations. The contents of the database must be consistent at its beginning and end. The beginning and end of a database LUW are defined by a commit command to the database system (database commit). During a database LUW, that is, between two database commits, the database system itself ensures consistency within the database. In other words, it takes over tasks such as locking database entries while they are being edited, or restoring the old data (rollback) if a step terminates in an error.
    A typical SAP application program extends over several screens and the corresponding dialog steps. The user requests database changes on the individual screens that should lead to the database being consistent once the screens have all been processed. However, the individual dialog steps run on different work processes, and a single work process can process dialog steps from other applications. It is clear that two or more independent applications whose dialog steps happen to be processed on the same work process cannot be allowed to work with the same database LUW.
    Consequently, a work process must open a separate database LUW for each dialog step. The work process sends a commit command (database commit) to the database at the end of each dialog step in which it makes database changes. These commit commands are called implicit database commits, since they are not explicitly written into the application program.
    These implicit database commits mean that a database LUW can be kept open for a maximum of one dialog step. This leads to a considerable reduction in database load, serialization, and deadlocks, and enables a large number of users to use the same system.
    However, the question now arises of how this method (1 dialog step = 1 database LUW) can be reconciled with the demand to make commits and rollbacks dependent on the logical flow of the application program instead of the technical distribution of dialog steps. Database update requests that depend on one another form logical units in the program that extend over more than one dialog step. The database changes associated with these logical units must be executed together and must also be able to be undone together.
    The SAP programming model contains a series of bundling techniques that allow you to group database updates together in logical units. The section of an R/3 application program that bundles a set of logically-associated database operations is called an SAP LUW. Unlike a database LUW, a SAP LUW includes all of the dialog steps in a logical unit, including the database update.
    Happy Reading...
    shibu

  • Finding the right Collection

    Hello,
    I am preparing a small, local database (Collection + Serialization)
    I want to choose the right Collection.
    I have patients which are recognized by ID which is the key,
    but I would like to sort the Database's elements by one of the field which is in the VALUE (by name)
    I am accessing Collection values by ID of course.
    (during search, deleting, updating elements)
    I am looking for some kind of structure
    that has two keys. (key1, key2, value)
    or maybe (keys[2], value) ?
    Is it possible?
    Any suggestions? ;))

    If however you need to traverse the keys in a
    sorted order then TreeMap is better alternative.
    This senetence convinced me to choose TreeMap in both
    cases.
    So you mean, that I have to make one Object:
    Person p = new Person();and add it twice?Exactly. You will have only on Object.
    Map by_name = new TreeMap(Name, p);
    Map by_ID = new TreeMap(ID, p);and then use the Map that I need?
    Still questions to come:
    What about the matter of those two fields: Name,
    ID?
    I mean I need them too, so for instance if I use the
    Name key
    I will not have the access to the ID key,
    so shall I add it to the Person class anyway?I would have imagined that the ID would already be a member of the Person class, given that you need it for more than lookups. Another option would be to make the second map relate names to IDs. This would mean doing an extra lookup when you search by name, of course.
    Both of them?Both of what, now?
    and how to make a map allow multiple value's per key?
    (need them for Name key)
    //add
    List persons = (List) namesToPersons.get(name);
    if (persons == null)
        persons = new ArrayList();
        namesToPersons.put(name, persons);
    persons.add(newPerson);Got the idea?

  • Problem updating JTree via RMI

    I'm programming an Instant Messenger application in Java using RMI extensively. Much like most IM applications, my IM clients display a "buddy list" window upon successful authentication with the server. I have reached a huge stumbling block at this point. My Buddylist JFrame contains a JTree that is used to display the status of the user's buddies (i.e. online, offline). I am able to populate the JTree without any problems BEFORE the JFrame is displayed by using the DefaultTreeModel's insertNodeInto() method. But the problem I'm having is that, once the Buddylist is displayed to the user, I can't successfully update the JTree to reflect changing user status. For example, let's say a user with the screename "qwerty" logs in to the server. Now "qwerty" sees his Buddylist pop up on screen. His Buddylist contains 1 user (for simplicity's sake) with screename "foo". "foo" is currently not logged into the system so "foo" is shown in the Buddylist as a child of node Offline. But right now, let's say that "foo" logs into the system. "qwerty's" Buddylist should be updated to reflect the fact that "foo" just signed in by removing "foo" as a child node of Offline and adding a new node to Online called "foo".
    I currently have this functionality implemented as an RMI callback method on the server side. When "foo" logs in, the server calls the method fireBuddyLoggedOnEvent() with "foo" as the argument. Because "qwerty" is already logged in, and both users are each other's buddy, the statement
         c.getCallback().buddySignedOn(screenname);
    will be executed on the client side. Unfortunately, even though this code is successfully executed remotely, "qwerty's" Buddylist's JTree does not update to show that "foo" is now online. My only suspicion is that this is due to the fact that the Buddylist is already visible and this somehow affects its ability to be updated (remember that I have no problem populating the tree BEFORE it's visible). However, I've weeded out this possibility by creating a test frame in which its JTree is successfully updated, but in response to an ActionEvent in response to a button click. Of course, this test case was not an RMI application and does not come with the complexities of RMI. Please help me resolve this issue as it's preventing me from proceeding with my project.
    ~BTW, sorry for the poor code formatting. I added all the code in wordpad and pasted it in here, which stripped the formatting.
    * Frame that allows the user to enter information to
    * be used to login to the server.
    public class LoginFrame extends JFrame {
         signonButton.addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent e) {
                   if (!screenameTextField.getText().equals("") &&
                   !passwordTextField.getPassword().equals("")) {
                        try {
                             serverInter = (ServerInter) Naming.lookup(serverName);
                             String username = screenameTextField.getText();
                             String password = String.valueOf(passwordTextField.getPassword());
                             int connectionID = serverInter.connect(username, password);
                             System.out.println("authenticate successful");
                             dispose();
                             Buddylist buddyList = new Buddylist(username, connectionID);
                             // Registers the buddylist with the server so that
                             // the server can remotely call methods on the
                             // Buddylist.
                             serverInter.registerCallback(buddyList, connectionID);
                             return;
                             } catch (Exception e1) {
                                  JOptionPane.showMessageDialog(LoginFrame.this, e1.getMessage(),
                                            "Connection Error", JOptionPane.ERROR_MESSAGE);
                                  passwordTextField.setText("");
                                  signonButton.setEnabled(false);
                                  e1.printStackTrace();
         public static void main(String[] args) {
              new LoginFrame();
    public class Buddylist extends JFrame implements BuddylistInter {
         public Buddylist(String username, int connectionID) {
              try {
                   serverInter = (ServerInter) Naming.lookup(serverName);
                   this.username = username;
                   this.connectionID = connectionID;
                   this.setTitle(username + "'s BuddyList");
                   initialize();
                   } catch (Exception e) {
                        e.printStackTrace();
         * Method of interest. Note that this method uses a DynamicTree
         * object as included in the Sun tutorial on JTree's
         * (located at http://www.iam.ubc.ca/guides/javatut99/uiswing/components/tree.html#dynamic).
         * Don't worry too much about where the node is getting added
         * but rather, that i wish to verify that an arbitrary node
         * can successfully be inserted into the tree during this
         * remote method call
         public void buddySignedOn(String screenname) throws RemoteException {
              // should add screename at some location in the tree
              // but doesn't!
              treePanel.addObject(screename);
    * Oversimplified interface for the Buddylist that is intended
    * to be used to allow callbacks to the clientside.
    public interface BuddylistInter extends Remote {
         public void buddySignedOn(String screenname) throws RemoteException;
    * Another oversimplified interface that is to be
    * implemented by the server so that the client can
    * call remote server methods.
    public interface ServerInter extends java.rmi.Remote {
         // "Registers" the given Buddylist with this server to allow
         // remote callbacks on the Buddylist.
         public void registerCallback(Buddylist buddylist, int connectionID)
                             throws RemoteException;
    public class Server extends UnicastRemoteObject implements ServerInter {
         private Vector loggedInUsers = new Vector();
         // Note that this method assumes that a Connection object
         // representing the Buddylist with connectionID was added
         // to the loggedInUsers list during authentication.
         public void registerCallback(Buddylist buddylist, int connectionID) throws RemoteException {          
              int index = loggedInUsers.indexOf(new Connection(connectionID));
              Connection c = (Connection) loggedInUsers.get(index);
              c.setCallback(buddylist);
         // Method that's called whenever a client successfully
         // connects to this server object.
         // screename is the name of the user that successfully
         // logged in.
         private void fireBuddyLoggedOnEvent(String screenname) {
              // Examines each logged in client to determine whether
              // or not that client should be notified of screename's
              // newly logged in status.
              for (int i = 0; i < loggedInUsers.size(); i++) {
                   Connection c = (Connection) loggedInUsers.get(i);
                   if (database1.areBuddies(screenname, c.getUsername())) {
                        try {
                             // getCallback() returns a reference to
                             // the Buddylist that was registered
                             // with this server. At this point,
                             // the server attempts to notify the
                             // client that one of his "buddies" has
                             // just logged into the server.
                             c.getCallback().buddySignedOn(screenname);
                        } catch (RemoteException e) {
                             e.printStackTrace();
    }

    Ok, I deleted all .class files, recomplied, and rmic'd, and I still get the IllegalArgumentException. So I've decided to just post all the code here because I don't want to make an assumption that all the code is correct. Thanks for helping me out with this very stressful problem.
    * Created on Nov 13, 2006
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.rmi.Naming;
    import java.rmi.NotBoundException;
    import java.rmi.RemoteException;
    import java.rmi.server.UnicastRemoteObject;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JPanel;
    import javax.swing.JSeparator;
    import javax.swing.SwingUtilities;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class Buddylist extends JFrame implements BuddylistInter {
         private String serverName = "//Broom:" + "5001" + "/IMServer";
         private DynamicTree treePanel = null;
         private String onlineString = "Online";
         private String offlineString = "Offline";
         private DefaultMutableTreeNode onlineNode = null;
         private DefaultMutableTreeNode offlineNode = null;
         private ImageUpdater imageUpdater = null;
         private javax.swing.JPanel jContentPane = null;
         private ServerInter serverInter = null;
         private String username = null;
         // A connectionID of -1 indicates that this Buddylist
         // has not yet received a valid id from the server.
         private int connectionID = -1;
         private JMenuBar jJMenuBar = null;
         private JMenu jMenu = null;
         private JMenu jMenu1 = null;
         private JMenu jMenu2 = null;
         private JPanel imagePanel = null;
         private JSeparator jSeparator1 = null;
         public Buddylist(String username, int connectionID) {
             try {
                   serverInter = (ServerInter) Naming.lookup(serverName);
                   this.username = username;
                   this.connectionID = connectionID;
                   this.setTitle(username + "'s BuddyList");
                   imageUpdater = new ImageChooser(this);
                   initialize();
                    * This statement is causing an IllegalArgumentException
                    * to be thrown! I've tried inserting it at the beginning
                    * of the constructor and that doesn't help.
                   UnicastRemoteObject.exportObject(this);
              } catch (MalformedURLException e) {
                   e.printStackTrace();
              } catch (RemoteException e) {
                   e.printStackTrace();
              } catch (NotBoundException e) {
                   e.printStackTrace();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
              this.setJMenuBar(getJJMenuBar());
              this.setPreferredSize(new java.awt.Dimension(196,466));
              this.setMinimumSize(new java.awt.Dimension(150,439));
              this.setSize(196, 466);
              this.setContentPane(getJContentPane());
              this.setLocationRelativeTo(null);
              this.setVisible(true);
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private javax.swing.JPanel getJContentPane() {
              if(jContentPane == null) {
                   jContentPane = new javax.swing.JPanel();
                   jContentPane.setLayout(null);
                   jContentPane.add(getImagePanel(), null);
                   jContentPane.add(getJSeparator1(), null);
                   jContentPane.add(getTreePanel(), null);
              return jContentPane;
         private DynamicTree getTreePanel() {
              if (treePanel == null) {
                   treePanel = new DynamicTree();
                   onlineNode = treePanel.addObject(null, onlineString);
                   offlineNode = treePanel.addObject(null, offlineString);
                   treePanel.setBounds(6, 138, 177, 196);
                   populateTree();
                   return treePanel;
              return null;
         private void populateTree() {
              try {
                   String [] buddies = serverInter.getBuddyList(this.username);
                   for (int i = 0; i < buddies.length; i++) {
                        try {
                             if (serverInter.isBuddyOnline(buddies)) {
                                  treePanel.addObject(onlineNode, buddies[i]);
                             else {
                                  treePanel.addObject(offlineNode, buddies[i]);
                        } catch (RemoteException e1) {
                             e1.printStackTrace();
              } catch (RemoteException e) {
                   e.printStackTrace();
         * This method initializes jJMenuBar     
         * @return javax.swing.JMenuBar     
         private JMenuBar getJJMenuBar() {
              if (jJMenuBar == null) {
                   jJMenuBar = new JMenuBar();
                   jJMenuBar.add(getJMenu());
                   jJMenuBar.add(getJMenu1());
                   jJMenuBar.add(getJMenu2());
              return jJMenuBar;
         * This method initializes jMenu     
         * @return javax.swing.JMenu     
         private JMenu getJMenu() {
              if (jMenu == null) {
                   jMenu = new JMenu();
                   jMenu.setText("My IM");
              return jMenu;
         * This method initializes jMenu1     
         * @return javax.swing.JMenu     
         private JMenu getJMenu1() {
              if (jMenu1 == null) {
                   jMenu1 = new JMenu();
                   jMenu1.setText("People");
              return jMenu1;
         * This method initializes jMenu2     
         * @return javax.swing.JMenu     
         private JMenu getJMenu2() {
              if (jMenu2 == null) {
                   jMenu2 = new JMenu();
                   jMenu2.setText("Help");
              return jMenu2;
         * This method initializes imagePanel     
         * @return javax.swing.JPanel     
         private JPanel getImagePanel() {
              if (imagePanel == null) {
                   imagePanel = new JPanel();
                   imagePanel.setBounds(6, 2, 176, 125);
                   try {
                        BufferedImage bi =
                             ImageIO.read(
                                       getClass().getClassLoader().getResourceAsStream("images/cute_dog.jpg"));
                        Image scaled = bi.getScaledInstance(
                                  imagePanel.getWidth(), imagePanel.getHeight(), BufferedImage.SCALE_FAST);
                        final JLabel imageLabel = new JLabel(new ImageIcon(scaled));
                        imageLabel.setToolTipText("Double click to change image");
                        imagePanel.add(imageLabel, imageLabel.getName());
                        imageLabel.addMouseListener(new java.awt.event.MouseAdapter() {
                             public void mouseClicked(java.awt.event.MouseEvent e) {
                                  if (e.getClickCount() == 2) {
                                       Image selected = imageUpdater.getSelectedImage();
                                       if (selected != null) {
                                            BufferedImage bi = (BufferedImage) selected;
                                            Image scaled = bi.getScaledInstance(
                                                      imageLabel.getWidth(), imageLabel.getHeight(), BufferedImage.SCALE_DEFAULT);
                                            imageLabel.setIcon(new ImageIcon(scaled));
                   } catch (IOException e) {
                        e.printStackTrace();
              return imagePanel;
         * This method initializes jSeparator1     
         * @return javax.swing.JSeparator     
         private JSeparator getJSeparator1() {
              if (jSeparator1 == null) {
                   jSeparator1 = new JSeparator();
                   jSeparator1.setBounds(6, 132, 176, 1);
              return jSeparator1;
         public void buddySignedOn(String screenname) throws RemoteException {
              final String temp = screenname;
              Runnable addBuddy = new Runnable() {
                   public void run() {
                        treePanel.addObject(onlineNode, temp);
              SwingUtilities.invokeLater(addBuddy);
         public void buddySignedOff(String screenname) throws RemoteException {
              // TODO Auto-generated method stub
         public boolean equals(Object o) {
              Buddylist buddylist = (Buddylist) o;
              return connectionID == buddylist.connectionID;
         public int hashCode() {
              return connectionID;
    } // @jve:decl-index=0:visual-constraint="10,11"
    * Created on Nov 4, 2006
    import java.rmi.Remote;
    import java.rmi.RemoteException;
    public interface BuddylistInter extends Remote {
         public void buddySignedOn(String screenname) throws RemoteException;
         public void buddySignedOff(String screenname) throws RemoteException;
    * Created on Oct 14, 2006
    * Models a single endpoint of a connection between machines.
    * @author Josh Feldman
    public class Connection {
         private String username;
         private final int connectionID;
         private Buddylist callback = null;
         public Connection(String username, int connectionID) {
              this.username = username;
              this.connectionID = connectionID;
         public Connection(int connectionID) {
              this.connectionID = connectionID;
         public String getUsername() {
              return username;
         public int getConnectionID() {
              return connectionID;
         public void setCallback(Buddylist buddylist) {
              this.callback = buddylist;
         public Buddylist getCallback() {
              return callback;
         public boolean equals(Object o) {     
              Connection otherConnection = (Connection) o;
              if (otherConnection.getConnectionID() == this.connectionID) {
                   return true;
              else {
                   return false;
         public int hashCode() {
              return connectionID;
    * Created on Nov 4, 2006
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.Serializable;
    import java.util.Properties;
    public class Database implements Serializable{
         private final String regex = ";";
         private Properties db = null;
         private String dbPath = "buddies.txt";
         public Database() throws IOException {
              db = new Properties();
              File buddiesFile = new File(dbPath);
              if (!buddiesFile.canRead()) {
                   throw new IOException("Can't read database!");
              try {
                   FileInputStream fis = new FileInputStream(buddiesFile);
                   db.load(fis);
                   System.out.println("database loaded from file");
              } catch (IOException e) {
                   e.printStackTrace();
                   System.err.println("Can't load the database! Exiting program...");
                   System.exit(0);
          * called when a user adds/deletes a user from the buddylist
         public void changeBuddyList() {
              //TODO
         public boolean doesUserExist(String username) {
              System.out.println(db.getProperty(username));
              return db.getProperty(username) != null;
         public String getPassword(String username) {
              String temp = db.getProperty(username);
              String [] split = temp.split(regex);
              if (split.length == 2)
                   return split[0];
              else {
                   return null;
         public String getBuddies(String username) {
              String temp = db.getProperty(username);
              if (temp == null)
                   return null;
              String [] split = temp.split(regex);
              if (split.length != 2)
                   return null;
              else {
                   return split[1];
          * Determines whether screename1 is a buddy of screename2
          * @return
         public boolean areBuddies(String screename1, String screename2) {
              String [] buddies = getUserBuddies(screename2);
              if (buddies == null) {
                   return false;
              else {
                   for (int i = 0; i < buddies.length; i++) {
                        if (buddies.equals(screename1)) {
                             return true;
              return false;
         public String [] getUserBuddies(String username) {
              System.out.println("in db getUserBuddies: username = " + username);
              String temp = db.getProperty(username);
              if (temp == null)
                   return null;
              String [] split = temp.split(regex);
              if (split.length != 2)
                   return null;
              else {
                   return split[1].split(",");
    import java.awt.GridLayout;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.MutableTreeNode;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeSelectionModel;
    // Note that this is not my code but rather code taken
    // from java Sun tutorial
    public class DynamicTree extends JPanel {
        protected DefaultMutableTreeNode rootNode;
        protected DefaultTreeModel treeModel;
        protected JTree tree;
        public DynamicTree() {
            rootNode = new DefaultMutableTreeNode("Root Node");
            treeModel = new DefaultTreeModel(rootNode);
            treeModel.addTreeModelListener(new MyTreeModelListener());
            tree = new JTree(treeModel);
            tree.setRootVisible(false);
            tree.setEditable(false);
            tree.getSelectionModel().setSelectionMode
                    (TreeSelectionModel.SINGLE_TREE_SELECTION);
            tree.setShowsRootHandles(false);
            JScrollPane scrollPane = new JScrollPane(tree);
            setLayout(new GridLayout(1,0));
            add(scrollPane);
        /** Remove all nodes except the root node. */
        public void clear() {
            rootNode.removeAllChildren();
            treeModel.reload();
        /** Remove the currently selected node. */
        public void removeCurrentNode() {
            TreePath currentSelection = tree.getSelectionPath();
            if (currentSelection != null) {
                DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)
                             (currentSelection.getLastPathComponent());
                MutableTreeNode parent = (MutableTreeNode)(currentNode.getParent());
                if (parent != null) {
                    treeModel.removeNodeFromParent(currentNode);
                    return;
        public void removeObject(DefaultMutableTreeNode child) {
             treeModel.removeNodeFromParent(child);
    //         treeModel.reload();
        /** Add child to the currently selected node. */
        public DefaultMutableTreeNode addObject(Object child) {
            DefaultMutableTreeNode parentNode = null;
            TreePath parentPath = tree.getSelectionPath();
            if (parentPath == null) {
                parentNode = rootNode;
            } else {
                parentNode = (DefaultMutableTreeNode)
                             (parentPath.getLastPathComponent());
            return addObject(parentNode, child, true);
        public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
                                                Object child) {
            return addObject(parent, child, false);
        public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
                                                Object child,
                                                boolean shouldBeVisible) {
            DefaultMutableTreeNode childNode =
                    new DefaultMutableTreeNode(child);
            if (parent == null) {
                parent = rootNode;
            treeModel.insertNodeInto(childNode, parent,
                                     parent.getChildCount());
            // Make sure the user can see the lovely new node.
            if (shouldBeVisible) {
                tree.scrollPathToVisible(new TreePath(childNode.getPath()));
            return childNode;
        class MyTreeModelListener implements TreeModelListener {
            public void treeNodesChanged(TreeModelEvent e) {
                DefaultMutableTreeNode node;
                node = (DefaultMutableTreeNode)
                         (e.getTreePath().getLastPathComponent());
                 * If the event lists children, then the changed
                 * node is the child of the node we've already
                 * gotten.  Otherwise, the changed node and the
                 * specified node are the same.
                try {
                    int index = e.getChildIndices()[0];
                    node = (DefaultMutableTreeNode)
                           (node.getChildAt(index));
                } catch (NullPointerException exc) {}
                System.out.println("The user has finished editing the node.");
                System.out.println("New value: " + node.getUserObject());
            public void treeNodesInserted(TreeModelEvent e) {
            public void treeNodesRemoved(TreeModelEvent e) {
            public void treeStructureChanged(TreeModelEvent e) {
        public DefaultTreeModel getModel() {
             return treeModel;
    * Created on Sep 24, 2006
    import java.awt.Frame;
    import java.awt.Image;
    import javax.swing.JComponent;
    * Generic Dialog for allowing a user to browse
    * his filesystem for an image file. Dialog
    * displays a preview of the image (if it is in fact
    * displayable).
    * @author Josh Feldman
    public class ImageChooser extends JComponent implements ImageUpdater{
         private Frame parent = null;
         public ImageChooser(Frame parent) {
              super();
              this.parent = parent;
         public Image getSelectedImage() {
              ImageChooserDialog dialog = new ImageChooserDialog(parent);
              if (dialog.showDialog() == ImageChooserDialog.OK_OPTION) {
                   return dialog.getSelectedImage();
              return null;
    }  //  @jve:decl-index=0:visual-constraint="10,10"
    * Created on Sep 24, 2006
    import java.awt.Frame;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.JDialog;
    import javax.swing.ImageIcon;
    import javax.swing.JFileChooser;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JButton;
    * Class that displays a dialog that allows a user
    * to browse his/her filesystem for an image file
    * for selection.
    * @author Josh Feldman
    public class ImageChooserDialog extends JDialog {
         private Frame parent = null;
         private JFileChooser fileChooser = new JFileChooser();
         private int option;
         public final static int OK_OPTION = 1;
         public final static int CANCEL_OPTION = 2;
         private Image selectedImage = null;
         private javax.swing.JPanel jContentPane = null;
         private JPanel previewPanel = null;
         private JLabel jLabel = null;
         private JTextField filenameTextField = null;
         private JButton browseButton = null;
         private JButton cancelButton = null;
         private JButton okButton = null;
         private JLabel previewLabel = null;
          * This is the default constructor
         public ImageChooserDialog(Frame parent) {
              super();
              this.parent = parent;
              this.setTitle("Select Image");
              initialize();
         public ImageChooserDialog(Frame parent, String title) {
              super();
              this.parent = parent;
              this.setTitle(title);
              initialize();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setModal(true);
              this.setSize(377, 246);
              this.setContentPane(getJContentPane());
              this.setVisible(false);
              this.setLocationRelativeTo(parent);
              this.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        selectedImage = null;
                        option = CANCEL_OPTION;
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private javax.swing.JPanel getJContentPane() {
              if(jContentPane == null) {
                   jLabel = new JLabel();
                   jContentPane = new javax.swing.JPanel();
                   jContentPane.setLayout(null);
                   jLabel.setBounds(87, 192, 58, 10);
                   jLabel.setText("Preview");
                   jContentPane.add(getPreviewPanel(), null);
                   jContentPane.add(jLabel, null);
                   jContentPane.add(getFilenameTextField(), null);
                   jContentPane.add(getBrowseButton(), null);
                   jContentPane.add(getCancelButton(), null);
                   jContentPane.add(getOkButton(), null);
              return jContentPane;
          * This method initializes previewPanel     
          * @return javax.swing.JPanel     
         private JPanel getPreviewPanel() {
              if (previewPanel == null) {
                   previewPanel = new JPanel();
                   previewLabel = new JLabel();
                   previewPanel.setLayout(null);
                   previewPanel.setLocation(25, 62);
                   previewPanel.setSize(172, 125);
                   previewPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
                   previewLabel.setText("");
                   previewLabel.setLocation(2, 2);
                   previewLabel.setSize(172, 125);
                   previewPanel.add(previewLabel, null);
              return previewPanel;
          * This method initializes jTextField     
          * @return javax.swing.JTextField
         private JTextField getFilenameTextField() {
              if (filenameTextField == null) {
                   filenameTextField = new JTextField();
                   filenameTextField.setBounds(26, 17, 212, 23);
                   filenameTextField.setEditable(false);
              return filenameTextField;
          * This method initializes jButton     
          * @return javax.swing.JButton     
         private JButton getBrowseButton() {
              if (browseButton == null) {
                   browseButton = new JButton();
                   browseButton.setBounds(254, 18, 102, 21);
                   browseButton.setText("Browse");
                   browseButton.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) { 
                             ImageFilter imageFilter = new ImageFilter();
                             fileChooser.setFileFilter(imageFilter);
                             int value = fileChooser.showOpenDialog(ImageChooserDialog.this);
                             if (value == JFileChooser.APPROVE_OPTION) {
                                  File selected = fileChooser.getSelectedFile();
                                  if (selected.canRead()) {
                                       try {
                                            BufferedImage bi = ImageIO.read(selected);
                                            selectedImage = bi;
                                            Image scaled = bi.getScaledInstance(
                                                      previewPanel.getWidth(), previewPanel.getHeight(), BufferedImage.SCALE_FAST);
                                            ImageIcon imageIcon = new ImageIcon(scaled);
                                            previewLabel.setIcon(imageIcon);
                                            filenameTextField.setText(selected.getAbsolutePath());
                                       } catch (IOException e1) {
                                            previewLabel.setText("Preview unavailable...");
                                            selectedImage = null;
                                            e1.printStackTrace();
              return browseButton;
          * This method initializes jButton1     
          * @return javax.swing.JButton     
         private JButton getCancelButton() {
              if (cancelButton == null) {
                   cancelButton = new JButton();
                   cancelButton.setBounds(254, 122, 100, 24);
                   cancelButton.setText("Cancel");
                   cancelButton.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                             selectedImage = null;
                             option = CANCEL_OPTION;
                             ImageChooserDialog.this.dispose();
              return cancelButton;
          * This method initializes jButton2     
          * @return javax.swing.JButton     
         private JButton getOkButton() {
              if (okButton == null) {
                   okButton = new JButton();
                   okButton.setBounds(256, 159, 97, 24);
                   okButton.setText("OK");
                   okButton.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                             option = OK_OPTION;
                             ImageChooserDialog.this.dispose();
              return okButton;
          * Displays this chooser dialog.
          * @return - The user selected option
          *                (i.e. OK_OPTION, CANCEL_OPTION)
         public int showDialog() {
              this.setVisible(true);
              return option;
          * Returns the image chosen by the user.
          * @return
         public Image getSelectedImage() {
              return selectedImage;
    import java.io.File;
    import javax.swing.filechooser.FileFilter;
    public class ImageFilter extends FileFilter {
        //Accept all directories and all gif, jpg, tiff, or png files.
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            String extension = Utils.getExtension(f);
            if (extension != null) {
                if (extension.equals(Utils.tiff) ||
                    extension.equals(Utils.tif) ||
                    extension.equals(Utils.gif) ||
                    extension.equals(Utils.jpeg) ||
                    extension.equals(Utils.jpg) ||
                    extension.equals(Utils.png)) {
                        return true;
                } else {
                    return false;
            return false;
        //The description of this filter
        public String getDescription() {
            return "Just Images";
    * Created on Sep 24, 2006
    import java.awt.Image;
    * Contract that specifies how a class can update
    * the view in its graphical display.
    * @author Josh Feldman
    public interface ImageUpdater {
         public Image getSelectedImage();
    * Created on Nov 4, 2006
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.awt.event.KeyEvent;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.rmi.Naming;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.JTextField;
    public class LoginFrame extends JFrame {
         private String serverName = "//Broom:5001/IMServer";
         private ServerInter serverInter = null;
         // The icon to be used when this frame is minimized
         private Image icon;
         // The main image to be displayed on this frame
         private Image robotImage;
         private javax.swing.JPanel jContentPane = null;
         private JPanel imagePanel = null;
         private JLabel screenameLabel = null;
         private JTextField screenameTextField = null;
         private JPanel jPanel1 = null;
         private JLabel passwordLabel = null;
         private JPasswordField passwordTextField = null;
         private JButton signonButton = null;
         private JButton helpButton = null;
          * This is the default constructor
         public LoginFrame() {
              initialize();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
              this.setResizable(false);
              this.setSize(210, 368);
              this.setContentPane(getJContentPane());
              this.setTitle("Sign On");
              try {
                   this.setIconImage(ImageIO.read(new File("images/robby3.jpg")));
              } catch (IOException e) {
                   e.printStackTrace();
              this.setLocationRelativeTo(null);
              this.setVisible(true);
          * This method initializes jPanel     
          * @return javax.swing.JPanel     
         private JPanel getImagePanel() {
              if (imagePanel == null) {
                   imagePanel = new JPanel();
                   imagePanel.setBounds(7, 7, 190, 159);
                   imagePanel.setBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.gray,0));
                   try {
                        BufferedImage bi =
                             ImageIO.read(
                                       getClass().getClassLoader().getResourceAsStream("images/robby_big.bmp"));
                        Image scaled = bi.getScaledInstance(190, 169, BufferedImage.SCALE_FAST);
                        JLabel robotLabel = new JLabel(
                                  new ImageIcon(scaled));
                        imagePanel.add(robotLabel);
                   } catch (IOException e) {
                        e.printStackTrace();
              return imagePanel;
          * This method initializes jTextField     
          * @return javax.swing.JTextField     
         private JTextField getScreenameTextField() {
              if (screenameTextField == null) {
                   screenameTextField = new JTextField();
                   screenameTextField.setBounds(22, 208, 168, 20);
                   screenameTextField.addKeyListener(new java.awt.event.KeyAdapter() {  
                        public void keyTyped(java.awt.event.KeyEvent e) {
                             if (!isAllowedCharacter(e.getKeyChar())) {
                                  e.consume();
                                  Toolkit.getDefaultToolkit().beep();
                        public void keyPressed(java.awt.event.KeyEvent e) {
                             int keycode = e.getKeyCode();
                             if(keycode == KeyEvent.VK_ENTER && signonButton.isEnabled()) {
                                  signonButton.doClick();
                                  passwordTextField.setText("");
                             else if (keycode == KeyEvent.VK_ESCAPE) {
                                  dispose();
                                  System.exit(0);
                        public void keyReleased(java.awt.event.KeyEvent e) {
                             String screename = screenameTextField.getText();
                             char [] password = passwordTextField.getPassword();
                             if (screename.equals("") ||
                                       password.length <= 0) {
                                  signonButton.setEnabled(false);
                             else if (!screename.equals("") &&
                                       password.length > 0) {
                                  signonButton.setEnabled(true);
                             clearPasswordArray(password);
              return screenameTextField;
          * This method initializes jPanel1     
          * @return javax.swing.JPanel     
         private JPanel getJPanel1() {
              if (jPanel1 == null) {
                   jPanel1 = new JPanel();
                   jPanel1.setBounds(8, 173, 188, 1);
                   jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.gray,5));
              return jPanel1;
          * This method initializes jPasswordField     
          * @return javax.swing.JPasswordField     
         private JPasswordField getPasswordTextField() {
              if (passwordTextField == null) {
                   passwordTextField = new JPasswordField();
                   passwordTextField.setBounds(20, 259, 170, 20);
                   passwordTextField.addKeyListener(new java.awt.event.KeyAdapter() {
                        public void keyTyped(java.awt.event.KeyEvent e) {
                             if (!isAllowedCharacter(e.getKeyChar())) {
                                  e.consume();
                                  Toolkit.getDefaultToolkit().beep();
                        public void keyPressed(java.awt.event.KeyEvent e) {
                             int keycode = e.getKeyCode();
                             if(keycode == KeyEvent.VK_ENTER && signonButton.isEnabled()) {
                                  signonButton.doClick();
                                  passwordTextField.setText("");
                             else if (keycode == KeyEvent.VK_ESCAPE) {
                                  dispose();
                                  System.exit(0);
                        public void keyReleased(java.awt.event.KeyEvent e) {
                             String screename = screenameTextField.getText();
                             char [] password = passwordTextField.getPassword();
                             if (screename.equals("") ||
                                       password.length <= 0) {
                                  signonButton.setEnabled(false);
                             else if (!screename.equals("") &&
                                       password.length > 0) {
                                  signonButton.setEnabled(true);
                             clearPasswordArray(password);
              return passwordTextField;
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private javax.swing.JPanel getJContentPane() {
              if(jContentPane == null) {
                   passwordLabel = new JLabel();
                   screenameLabel = new JLabel();
                   jContentPane = new javax.swing.JPanel();
                   jContentPane.setLayout(null);
                   screenameLabel.setBounds(22, 182, 132, 20);
                   screenameLabel.setText("Screename");
                   screenameLabel.setEnabled(true);
                   screenameLabel.setFont(new java.awt.Font("Century Gothic", java.awt.Font.BOLD, 12));
                   passwordLabel.setBounds(21, 238, 135, 17);
                   passwordLabel.setText("Password");
                   jContentPane.add(getImagePanel(), null);
                   jContentPane.add(screenameLabel, null);
                   jContentPane.add(getScreenameTextField(), null);
                   jContentPane.add(getJPanel1(), null);
                   jCon                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             

  • Patterns for JavaBean and GUI interaction

    Forgive the newbie feel to this question.
    I have a number of JavaBeans-compliant classes for several entities that will end up persisted. I can use any of a number of technologies to persist these to a database or serialize to disk. If, now, I want to add a GUI for interaction with these beans, it seems there are at least a couple of ways to go. The first is to encapsulate the code for doing so in the bean itself, perhaps extending JComponent. The second is to make a "view" for each Bean that uses multiple PropertyChangeListeners(?) to/from the Bean to maintain state within the bean. The latter seems to separate the model from the view better.
    I am curious from a design point-of-view how best to go about solving this generic problem. I have done similar things in other languages with varying degrees of satisfaction with the resulting maintainability of the resulting product. So, I am aiming for something that balances complexity with maintainability and flexibility (to change a view or to change the underlying model).
    Thanks
    Sean

    Well, thanks for your reply. My program is kind of large to be entered online.
    In any case, I tried again with the synchronized keyword for the method that accesses the shared member (between the two threads) and things look good now and I do not see the problem I was seeing earlier.
    One question I have is w.r.t the usage of the synchronized keyword - can this be used for methods as well as members of a class ?
    I mean for example, if I have a static variable declared in a class and this static needs to be accessed outside the declaring class in a different thread, then should this static member be declared as synchronized too?
    Thanks.

  • Concurrency handling

    I have scenario, when i click on a link i should lock that page so that the current user can only access the records in the page. If the same record is accessed by someother user at the same time then for the other user it should throw a message saying " the record is locked by user 1 cannot access this record.
    my query:
    1) Now, when the user clicks on the link, i will temporarily lock the user at the table level .ie. when he/she clicks the link then i will put the entry in the table, so when someother user access the record at the same time , i will check for the lock value at the table if lock flag is true, then i will throw the message saying "user is locked" if not , i will allow the person to access the page. Say if the user, closes the browser or navigate to some other menu how do i release the lock from the table?.Is putting a lock at the table level is a ideal solution? or is there anyother way to implement this scenario? Kindly guide.

    There are lots of different approaches; which one is right for you depends on the scale of concurrency and your other design decisions.
    For example, if you're using a J2EE application server and can guarantee that no other application needs to check the lock, then you can create a data access object and do your locking in that. When a user session expires, the application can be notified and then perform the unlock, (and of course, all the locks are cleared when the application restarts). Notification is handled via a HttpSessionListener:
    http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpSessionListener.html
    Another approach is to not lock at all and rely on the database for serialization. The suitability of this approach often depends on what sort of data you're updating, and your willingness to code your transactions appropriately.

  • Clustering some general questions:

    1. Can dbIsShared be set to false if clustering is used?
              2. Why does Weblogic not automatically provide failover for entity
              beans? Many other servers including WebSphere and iPlanet provide
              that. In other words I would like to be able to set up a clustered
              environment without having to change any code.
              

    dan benanav wrote:
              >
              > see inline comments
              >
              > Rob Woollen wrote:
              >
              > > I'm not sure I follow you here. If you want pessimistic concurrency in
              > > a cluster, set the isolation level in the database to serializable.
              > >
              >
              > Setting the isolation level to serializable does not cause blocking (at least in Oracle). It
              > would be helpful if you read up on that to get a better > >understanding of what I am saying.
              I'm very familiar with Oracle, and you are correct it will not cause
              blocking. I should have been clearer in my response.
              > Setting the mode to serializable will only cause an exception to be generated if a transaction
              > attempts to update a row that was updated by another transaction that started after the current
              > transaction.
              >
              > Bottom line is, and I am sure about this, setting the isolation level in the database does not
              > yield the same effect as pessimistic concurrency (it does not block).
              >
              > Oracle is obviously one of the major database vendors so one would expect that there is a way to
              > have the account entity bean work with that.
              >
              > So can you offer a solution?
              >
              If you design your application to only work with pessimistic locks in
              the EJB container, then your design is flawed. You are depending on
              container internal behavior for your application to work. It certainly
              won't be portable to other J2EE platforms.
              Depending on serializable behavior for your transactions is fine, and
              that's what setting the transaction's isolation level will do.
              Can you give us some more information on why you require a global
              pessimistic lock in a cluster? I am interested in why this is needed in
              your application.
              -- Rob
              > dan
              >
              > >
              > > Robert was offering another solution which is to use optimistic
              > > concurrency. You could read the data in a single transaction and then
              > > do the conditional update in a second transaction.
              >
              > With a clustered system there is no choice but to use optimistic concurrency (from the entity
              > bean point of view).
              >
              > >
              > >
              > > -- Rob
              > >
              > > dan benanav wrote:
              > > >
              > > > The way you suggest is not the best approach, nor does it provide the same benefits as
              > > > pessimistic concurrency. It can also be done automatically (without a timestamp, etc.. )
              > > > by setting the mode to transaction_serializable. (If Oracle is being used). Your approach
              > > > makes the programming on the client side more complicated. You will need to catch the
              > > > exception and try again until you succeed.
              > > >
              > > > What we really want is to block somehow. How would you do that? Perhaps people have been
              > > > doing this in the client/server world. I would like to see how it would be handled with
              > > > entity beans. I am not convinced there is an easy way to do it.
              > > >
              > > > dan
              > > >
              > > > Robert Patrick wrote:
              > > >
              > > > >
              > > > > There are several ways to do this. People have been solving these problems for years
              > > > > in the client/server world. This is just one possible way of doing it...
              > > > >
              > > > > public int balance;
              > > > > public int oldBalance;
              > > > >
              > > > > public void ejbLoad()
              > > > > {
              > > > > balance = read from database;
              > > > > oldBalance = balance;
              > > > > }
              > > > >
              > > > > public void ejbStore()
              > > > > {
              > > > > // probably should use a version number or timestamp rather than the balance field
              > > > > // to detect if the bean has changed since the data was loaded...
              > > > > //
              > > > > update accounts set balance = :balance where accoutNumber = :accountNumber and
              > > > > balance = :oldBalance;
              > > > > if (numRowsAffected == 0) {
              > > > > ejbContext.setRollbackOnly();
              > > > > throw new ConcurrentModificationException("account was modified by someone
              > > > > else");
              > > > > }
              > > > > }
              > > > >
              > > > > public deposit(int amount)
              > > > > {
              > > > > balance += amount;
              > > > > }
              > > > >
              > > > > Hope this helps,
              > > > > Robert
              

  • How to serialize a object to DataBase?

    A feasible way is that serialize the object to a file and then store this file to database. But I want to achieve it directly. How could I do?

         * Convert a serializable object to a byte array.
         * @param serializable Object to convert.
         * @return Byte array or null if failed.
         * @throws IOException on error.
        static public byte[] toByteArray(Serializable serializable) throws IOException {
            byte[] result = null;
            if (serializable != null) {
                ObjectOutputStream oos = null;
                try {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    oos = new ObjectOutputStream(baos);
                    oos.writeObject(serializable);
                    result = baos.toByteArray();
                } finally {
                    if (oos != null) {
                        oos.flush();
                        oos.close();
            }//else: input unavailbel
            return result;
        }//toByteArray()
    byte[] ba = toByteArray(mySerializableObject);
    ByteArrayInputStream bais = new ByteArrayInputStream(ba);
    preparedStatement.setBinaryStream("BINDATA", bais, ba.length)

  • Serialization Back to Database

    Hi Every one, I am facing a little problem here that i cant seem to get past.
    I have done Serialization on my Database, i can Read the File into a Text Area. inside my View. I am using MVC in my program. What i am having a problem with is Trying to get this Object that i had Created with Serialization Into my Database as a Backup
    My Database Table is made up with the following
    ID (Int)
    FirstName (text)
    LastName (text)
    Address (text)
    PhoneNumber (int)
    bytes (blob)
    WRITE_OBJECT_SQL_PATIENT =
                             connection1.prepareStatement("INSERT INTO Patient(Id,FirstName,LastName,Address,PhoneNumber,bytes)" +
                                       "VALUES(?,?,?,?,?,?)");
         public ArrayList<Person> writeJavaObject(ActionEvent evt)
              ArrayList<Person> results = null; // ArrayList <Person>
              ResultSet resultSet = null; // ResultSet Set to Null
              try
                   // executeQuery returns ResultSet containing matching entries
                   resultSet = WRITE_OBJECT_SQL_PATIENT.executeQuery(); //ResultSet equals SelectAllPeople & Execute The Query Above
                   results = new ArrayList< Person >(); // Placing Entries into ArrayList
                   WRITE_OBJECT_SQL_PATIENT.setString( 1,"Patientid");
                   WRITE_OBJECT_SQL_PATIENT.setString( 2, "FirstName" );
                   WRITE_OBJECT_SQL_PATIENT.setString( 3, "LastName" );
                   WRITE_OBJECT_SQL_PATIENT.setString( 4, "Address" );
                   WRITE_OBJECT_SQL_PATIENT.setString( 5, "PhoneNumber" );
                   WRITE_OBJECT_SQL_PATIENT.setObject( 6, "object" );
              } // end try
              catch ( SQLException sqlException )
                   sqlException.printStackTrace();
                   close();
              } // end catch
              return results;
         }This is a Method that is calling the above code but i am getting Can not issue data manipulation statements with executeQuery().
         public static void LOADITEMactionPerformed(ActionEvent evt)
              results -
                            DBSQLQueries.writeJavaObject(evt);
         }

    I doubt that design will be usable over time. As an example of why - because data model entities are not always mappable in one to one relationships.
    And given that it looks like the connection/statement scope is outside the method it probably isn't thread safe either. And perhaps leaking connections.
    Other than that your question is a bit hard to understand. I can only suppose that when you attempt the write that it fails but you don't specify how. In other words you do not supply the exception and stack trace.
    But as a guess you are not using an updatable query.

  • Serialization big object(100k--2M) into MYSQL database

    Hi all !
    I have a big object need to be persisted into MYSQL database in my application.
    I use two method to meet this request
    1 ---- the object implement interface Serializable, but there is serializationVersionID is not same Exception
    sometimes.
    2 ---- Use XMLEncoder to save my object, the XMLEncoder generate the object XML text about 200k -- 3 M
    , but another problem occur :
    when I call flush method of XMLEncoder, my application will full ocuppy CPU time, and memory usage will increase to 90M, sometimes will ocurr "Not enough memory" Error.
    Why?
    can some one help me?
    Thanks in advanced

    1. You are modifying the signature of one or more of your classes that alters the (system generated) serializationVersionUID and then recompiling. You can declare this for yourself to get control to some extent. See the serialization spec for details.
    2. Your object graph is very large, which might be a problem using native or xml formats. Again, the specification details ways in which you can control the serialized form of your objects.
    On the information you've provided there's not much more that can be said.

  • Serialize object to MSQL database

    Hi
    Is it possible to serialize object to MSQL database instaed of file/Store?
    Please guide me...
    Thank you very much in advance
    PSL

    Somebody please throw some idea...Thank you very much

  • Serialization vs Database?

    Hi,�
    I'm a J2EE developer with some "desktop type" questions. I recently started to branch out and develop some small scale desktop apps. Anyway, here is the question "In a Nutshell":
    What is the "best" way to persist data on a desktop/mobile application?
    For example, lets take a simple application that has only two objects, "User" and "GroceryList" where User contains a GroceryList.
    Being a "J2EE guy" I am familiar with multiple RDBMS', EJB3, etc etc, but wouldn't object serialization be better here? Why would it be beneficial to tie my app to the DB? Or maybe there is a third solution I am totally missing?
    Just looking for some feedback and wondering how this is normally done.
    Kevin

    Kevin_Cloutier wrote:
    Hi,
    I'm a J2EE developer with some "desktop type" questions. I recently started to branch out and develop some small scale desktop apps. Anyway, here is the question "In a Nutshell":
    What is the "best" way to persist data on a desktop/mobile application?"best" is always a scalable and relative term. How much data do you have?
    >
    For example, lets take a simple application that has only two objects, "User" and "GroceryList" where User contains a GroceryList.
    Being a "J2EE guy" I am familiar with multiple RDBMS', EJB3, etc etc, but wouldn't object serialization be better here? Why would it be beneficial to tie my app to the DB? Or maybe there is a third solution I am totally missing?IMO: it is fairly silly to tie an application into a DB for small amounts of data. When you approach a less manageable volume of data, then you enter the realm of needing a DB.
    Rule of thumb--unless your Grocery List is going to read like the contents of a Safeway Super Store, then why would you even consider it for say 100 items?

  • Serialization of an Object containing an opened database connection

    Hi everyone,
    My question is simple:
    If you serialize an object containing an active databse connection, will it be de-serialized with that connection active and ready to use?

    First of all, lets look at the purpose. what is that
    making you write an object which hold the Connection
    object to a network or to the file.
    First check the condition. The conditions for
    serialization are
    1) Connection object should not be declared as
    transiant.
    2) And it should not be as static.
    It the above conditions are meet then the it is
    serializable.
    Now the obejct holding the connection object is
    written to the file or over the n/w.
    Reading
    Case 1 ) You read from the file at the server end no
    issues. You can reconstruct the Connection object and
    use it.
    case 2) If you are writing to the n/w , your client
    is some where in Aus and the java server the db
    server are in US. Java Server being public and db
    server being local to the Java Server , how you
    would use the connection object to execute the querys
    on that DB.
    Think about this :).Hi,
    Are n't you missing the whole point here? What you've said above is valid , of course, but then your readObject/writeObject methods would take care of restoring the connection object (from wherever) if such an implementation is taken up. IMHO, such an implementation is not practical in the first place, and if it's required in your project, it's bad design.
    Regards
    Hrishikesh

Maybe you are looking for

  • Where can I find information about exceptions and errors?

    I'm new to Java and sometimes run into errors that I don't understand. Is there a list of common errors somewhere that I could look at to at least get a general idea of what's causing my problem? for instance: I'm writing a little program where the u

  • Remove Gradient in Table of Contents

    I saw a post about this here: http://forums.adobe.com/message/3012047?tstart=2 but the "possible answer" wasn't helpful at all. I am working with Captivate 5. I have tried everything I can think of (unchecking gradient, changing all the possible back

  • You Tube not playing video on Firefox with Adobe Flash after latest update

    You Tube and other sites are not playing video on Firefox with Adobe Flash after latest update for both. Adobe Flash is working on other sites but not You tube and those sites that may have embedded You Tube videos, I'm not sure. Adobe Flash does not

  • How to select english movie in french version of itunes?

    This WE, I rent a movie of 2009, but I only find it in french version ( I am using itunes in french). How can I have access to old english movie?

  • TaskMetadata.getUri is deprecated

    Hey guys what about show to all oracle bpel developers how they can get uri from tasks. Method oracle.bpel.services.workflow.metadata.taskmetadata.model.TaskMetadata.getUri() is deprecated I know but there isnt documentation in all whole universe in