Excellent O-R mapping tools-toplink Introduction

Source: Internet
Author: User
Tags connection reset
Toplink is the first Java object link sustainability architecture. Its original webgain product is now acquired by Oracle and repackaged as Oracle AS toplink. Toplink provides a highly flexible and efficient mechanism for storing Java objects and Enterprise Java components (ejbs) in relational database tables. Toplink provides developers with excellent performance and selection, and can work with any database, any application server, any development toolkit set and process, and any J2EE architecture. This article uses toplink 3.5, which is widely used in the industry, as a reference version to briefly describe how to use toplink. This article is not a step by step getting started tutorial, but focuses on some basic concepts of toplink and summarizes some usage points, we can also look into the use of toplink and its design principles.

1. Connect to the database

Create a login object
Project. getlogin ()
New databaselogin ()
Specifying database and driver information
// Project. getlogin (). useoracle ();
Project. getlogin (). setdriverclass (Oracle. JDBC. Driver. oracledriver. Class );
Project. getlogin (). setconnectionstring ("JDBC: oracle: thin @ dbserver: 1521: orc1 ")
Setting Login Parameters
Project. getlogin (). setusername ("Scott ");
Project. getlogin (). setpassword ("tiger ");
Instance code 1
Databaselogin. setlicensepath ("C: // program files // common files // webgain shared //")
Project project = new myproject ();
Project. getlogin (). setusername ("userid ");
Project. getlogin (). setpassword ("passwd ");
Databasesession session = project. createdatabasesession ();
Session. login ();
Instance Code 2
Databaselogin. setlicensepath (...);
Databaselogin login = new databaselogin ();
Login. set...
...
Project project = new project (LOGIN );
Databasesession session = project. createdatabasesession ();
Session. login ();

Ii. Use of databasesession

An application must create a databasesession, which stores the following content:
1. A project and databaselogin instance (storing database logon and configuration information)
2. A databaseaccessor instance (which encapsulates JDBC connections and processes database access)
3. descriptors of all persistent classes of the application
4. map as a cache object
The databasesession instance must be created by the project instance, and the project object must be initialized by the correct database configuration parameters, such as JDBC driver and db url.
Register Descriptors (before login, login can also be registered but should be different from any registered descriptor)
Databasesession. adddescriptors (vector) or databasesession. adddescriptor (descriptor)
Connect to database
Databasesession. login (). After the connection, you can use this session to access the database and use "query framework"
Cache
You can use initializeidentitymaps () to refresh the cache. Note: Make sure that the objects in the cache are not used before use.
Log out of the database
Databasesession. logout (). You do not need to register descriptors when logging on again.

The following code specifies the exception handling process of databasesession:

Session. setexceptionhandler (New exceptionhandler (){
Public handleexception (runtimeexception ex ){
If (ex instanceof databaseexception) & (ex. getmessage (). Equals ("Connection reset by peer ")){
Ex. getaccessor (). reestablishconnection (ex. getsession ());
Return ex.getsession(cmd.exe cutequery (ex. getquery ());
}
}
});

Iii. Complete instance code using toplink
  1. ImportToplink. Public. Sessions .*;
  2. Databaselogin. setlicensepath ("");
  3. Databaselogin logininfo =NewDatabaselogin ();
  4. Logininfo. usejdbcodbcbridge ();
  5. Logininfo. usesqlserver ();
  6. Logininfo. setdatasourcename ("dbserver ");
  7. Logininfo. setusername ("");
  8. Logininfo. setpassword ("");
  9. Project project =NewProject (logininfo );
  10. Databasesession session = project. createdatabasesession ();
  11. Session. adddescriptors (This. Buildalldescriptors ());
  12. Try{
  13. Session. login ();
  14. }Catch(Databaseexception exception ){
  15. Throw New Runtimeexception("Database error occurred at login:" + exception. getmessage ());
  16. System. Out. println ("Login Failed .");
  17. }
  18. ...
  19. Session. logout ();
Iv. query framework)

Directly call the methods provided by the databasesession object to perform query and update operations. Unitofwork is used during the update operation to provide optimized performance.

Sample Code

  1. Employee Employee = (employee) Session. readobject (employee.Class,
  2. NewExpressionbuilder (). Get ("lastname"). Equals ("Smith "));
  3. Vector employees = session. readallobjects (employee.Class,
  4. NewExpressionbuilder (). Get ("salary"). greaterthan ("1000 "));
5. Use expression

Toplink provides an expression-Based Query mechanism. toplink translates these expressions into SQL statements and then converts the query results to objects for return.

1. Create an expression
Expression is always obtained through the. Get () method of expresson or expressionbuilder. expressionbuilder can be considered as a substitute for the queried object. Generally, the name is the name of the corresponding object.
An expressionbuilder instance is associated with a specific query. Do not use the same builder to generate multiple expressions.
2. subquery
Reportquery is used to obtain information about an object set, rather than the object itself. Common Methods:
Addattribute (string), addaverage (string), addcount (string), and so on.
1) Sample Code 1
Query employees with more than 5 managed employees

  1. Expressionbuilder EMP =NewExpressionbuilder ();
  2. Expressionbuilder managedemp =NewExpressionbuilder ();
  3. Reportquery subquery =NewReportquery (employee.Class, Managedemp );
  4. Subquery. addcount ();
  5. Subquery. addselectioncriteria (managedemp. Get ("manager"). Equals (EMP ));//?
  6. Expression exp = EMP. subquery (subquery). greaterthan (5 );

2) Sample Code 2
Query the employees who have the highest salaries in Ottawa.

  1. Expressionbuilder EMP =NewExpressionbuilder ();
  2. Expressionbuilder ottawaemp =NewExpressionbuilder ();
  3. Reportquery subquery =NewReportquery (employee.Class, Ottawaemp );
  4. Subquery. addmax ("salary ");
  5. Subquery. setselectioncriteria (ottawaemp. Get ("Address"). Get ("street"). Equals ("Ottawa "));
  6. Expression exp = EMP. Get ("salary"). Equals (subquery ).
  7. And (EMP. Get ("Address"). Get ("street"). Equals ("Ottawa "));

3. Parallel expressions
Parallel expression must have its own expressionbuilder, And the constructor of this builder must use a class as the parameter. Only the unique primary expressionbuilder exists. This primary builder uses the constructor with null parameters and its class will be obtained from the query.
1) instance code
Query all employees with the same lastname and gender
Expressionbuilder EMP = new expressionbuilder (); // master builder
Expressionbuilder spouse = new expressionbuilder (employee. Class); // parallel Builder
Expression exp = EMP. Get ("lastname"). Equal (spouse. Get ("lastname") // thoughts on Object-based model
. And (EMP. Get ("spouse"). Equal (spouse. Get ("spouse "))
. And (EMP. notequal (spouse ));
4. parameterized expressions and finders
1) parameterized expression example

  1. // Construct the expression used for the query. Note that the parameter with a firstname is used.
  2. Expressionbuilder EMP =NewExpressionbuilder ();
  3. Expression firstnameexpression =
  4. EMP. Get ("firstname"). Equal (EMP. getparameter ("firstname "));
  5. // Generate a readobjectquery object and set query reference classes, query conditions, and parameters
  6. Readobjectquery query =NewReadobjectquery ();
  7. Query. setreferenceclass (employee.Class);
  8. Query. setselectioncriteria (firstnameexpression );
  9. Query. setargument ("firstname ");
  10. // Query
  11. Vector v =NewVector ();
  12. V. addelement ("Sarah ");
  13. Employee E = (employee) Session. excutequery (query, V );

2) nested parameterized expression example

  1. Expressionbuilder EMP =NewExpressionbuilder ();
  2. Expression addressexpression;
  3. // Generate nested parameterized expressions
  4. Addressexpression = EMP. Get ("Address"). Get ("city"). Equal (
  5. EMP. getparameter ("employee"). Get ("address"). Get ("city "));// Nested expression
  6. Readobjectquery query =NewReadobjectquery (employee.Class);
  7. Query. setselectioncriteria (addressexpression );
  8. Query. addargument ("employee ");//?
  9. // Set parameters and execute the query
  10. Vector v =NewVector ();
  11. V. addelement (employee );
  12. Employee E = (employee) Session. excutequery (query, V );

Java developers need to use relational databases for sustainability. Using toplink eliminates the inherent risks involved in the construction of a persistent layer. Toplink can handle almost any persistence situation. Toplink provides a persistent infrastructure that allows developers to integrate data from multiple architectures (including EJB (CMP and BMP), conventional Java objects, Servlets, JSP, session beans, and message-driven beans) are integrated. Toplink allows Java applications to access data stored in relational databases as objects, greatly improving the efficiency of developers. Toplink also has the ability to improve application performance by minimizing the database hit rate and network traffic and optimizing the use of JDBC and database. Toplink creates a metadata "descriptor" (ing) set to implement the above features. These metadata descriptors define how to store objects in a specific database mode. Toplink uses these mappings to dynamically generate the required SQL statements at runtime. These metadata descriptors (mappings) are independent of languages and databases, and developers can modify them without the need to recompile the classes they represent.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.