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
- ImportToplink. Public. Sessions .*;
- Databaselogin. setlicensepath ("");
- Databaselogin logininfo =NewDatabaselogin ();
- Logininfo. usejdbcodbcbridge ();
- Logininfo. usesqlserver ();
- Logininfo. setdatasourcename ("dbserver ");
- Logininfo. setusername ("");
- Logininfo. setpassword ("");
- Project project =NewProject (logininfo );
- Databasesession session = project. createdatabasesession ();
- Session. adddescriptors (This. Buildalldescriptors ());
- Try{
- Session. login ();
- }Catch(Databaseexception exception ){
- Throw New Runtimeexception("Database error occurred at login:" + exception. getmessage ());
- System. Out. println ("Login Failed .");
- }
- ...
- 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
- Employee Employee = (employee) Session. readobject (employee.Class,
- NewExpressionbuilder (). Get ("lastname"). Equals ("Smith "));
- Vector employees = session. readallobjects (employee.Class,
- 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
- Expressionbuilder EMP =NewExpressionbuilder ();
- Expressionbuilder managedemp =NewExpressionbuilder ();
- Reportquery subquery =NewReportquery (employee.Class, Managedemp );
- Subquery. addcount ();
- Subquery. addselectioncriteria (managedemp. Get ("manager"). Equals (EMP ));//?
- Expression exp = EMP. subquery (subquery). greaterthan (5 );
2) Sample Code 2
Query the employees who have the highest salaries in Ottawa.
- Expressionbuilder EMP =NewExpressionbuilder ();
- Expressionbuilder ottawaemp =NewExpressionbuilder ();
- Reportquery subquery =NewReportquery (employee.Class, Ottawaemp );
- Subquery. addmax ("salary ");
- Subquery. setselectioncriteria (ottawaemp. Get ("Address"). Get ("street"). Equals ("Ottawa "));
- Expression exp = EMP. Get ("salary"). Equals (subquery ).
- 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
- // Construct the expression used for the query. Note that the parameter with a firstname is used.
- Expressionbuilder EMP =NewExpressionbuilder ();
- Expression firstnameexpression =
- EMP. Get ("firstname"). Equal (EMP. getparameter ("firstname "));
- // Generate a readobjectquery object and set query reference classes, query conditions, and parameters
- Readobjectquery query =NewReadobjectquery ();
- Query. setreferenceclass (employee.Class);
- Query. setselectioncriteria (firstnameexpression );
- Query. setargument ("firstname ");
- // Query
- Vector v =NewVector ();
- V. addelement ("Sarah ");
- Employee E = (employee) Session. excutequery (query, V );
2) nested parameterized expression example
- Expressionbuilder EMP =NewExpressionbuilder ();
- Expression addressexpression;
- // Generate nested parameterized expressions
- Addressexpression = EMP. Get ("Address"). Get ("city"). Equal (
- EMP. getparameter ("employee"). Get ("address"). Get ("city "));// Nested expression
- Readobjectquery query =NewReadobjectquery (employee.Class);
- Query. setselectioncriteria (addressexpression );
- Query. addargument ("employee ");//?
- // Set parameters and execute the query
- Vector v =NewVector ();
- V. addelement (employee );
- 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.