Вы находитесь на странице: 1из 27

Data Access Layer

( “Telosys-DAL” )

Laurent Guérin / V 1.8 / 2008 – November

( for Telosys 1.0.0 and + )

Telosys-DAL : The big principles


 Telosys-DAL goals :
 Provide an easy way to write and use standard “CRUD”
DAOs ( for single Value Objects and Lists )
 Let the programmer see the SQL code and control all
the operations
 Keep the SQL code and the “O/R mapping” in the Java
classes (when the code runs, it cannot be altered by
external files)
 Increase the productivity by providing
 a set of classes to encapsulate all the JDBC complexity
 external tools to generate the specific Java code required to
access a table
  you don’t have to write code to create DAO and Value
Objects !

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 2

Telosys 1
Telosys-DAL : Overview

Application Data Access Layer


dbconfig.xml
init()
Connection
getConnection() Manager

Telosys
« SqlConnection
« DAO » Provider »

SqlConnection
AgencyVO SqlConnection
AgencyDAO Pool

AgencyVOList
SqlConnection
Pool
SqlConnection
EmployeeVO EmployeeDAO
SqlConnection
EmployeeVOList Factory SqlConnection

Value Objects J2EE Server


SQLDataSource
DataSource

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 3

Configuration file “dbconfig.xml”


 dbconfig.xml example : maxId : 0 to 100
<databases maxId="4" defaultId="0" > defaultId : 0 if not set or invalid
id : 0 to maxId
<db id = "0" poolSize :
name = "MySQL - Test DB" . 0|1  factory (no pool )
driver = "com.mysql.jdbc.Driver" . > 1  pool
url = "jdbc:mysql://localhost:3306/test"
isolationLevel = "TRANSACTION_REPEATABLE_READ"
poolSize = "3" >
<property name="user" value="root" /> POOL [ 3 ]
<property name="password" value="" />
<metadata catalog="" schema="" table-name-pattern="%" table-types="TABLE VIEW" />
</db>

<db id = "1" name="DataSource MySQL" datasource="java:comp/env/jdbc/mydatasource" />

<db id = "2" Datasource (JNDI name)


name = "Oracle 10g"
driver = "oracle.jdbc.OracleDriver"
url = "jdbc:oracle:thin:@localhost:1521:XE"
isolationLevel = "TRANSACTION_READ_COMMITTED" Factory
poolSize = “0" > ( no pool )
<property name="user" value="tp" />
<property name="password" value="tp" />
<metadata catalog="" schema="TP" table-name-pattern="%" table-types="TABLE VIEW" />
</db>

</databases>

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 4

Telosys 2
Telosys-DAL : Initialization
 Telosys-DAL stand-alone :
//--- Telosys DAL initialization with dbconfig file path
private static final String DB_CONFIG = CONF_DIR + "dbconfig.xml" ;
TelosysDAL.init(DB_CONFIG);

 Telosys-DAL with Telosys framework :


 Define the dbconfig file in the telosys.properties
DbConfFile = C:/Eclipse301/workspace/Telosys/conf/dbconfig.xml
DbConfFile = ./dbconfig.xml

 Init Telosys framework, then Telosys-DAL


//--- 1) Telosys global initialization
Telosys.init(..., ...);
//--- 2) Telosys DAL initialization
TelosysDAL.init();

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 5

Telosys-DAL : Connections management


ConnectionManager ConnectionProvider
<< class >> << interface >>
. init ( String dbconfigFile ) java.sql.
. getConnection()
. getDefaultDatabase() * . getName()
Connection
. getNumberOfDatabases() << interface >>
. getConnection()
. getConnection(int base)
. getSession()
. getSession(int base)

SqlDataSource
SqlConnectionProvider getConnection :
get from DataSource

javax.sql.DataSource
SqlConnection SqlConnection 1 Pool
Factory Pool ( Vector )
getConnection : getConnection :
create a new get from pool * SqlConnection
connection << class >>

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 6

Telosys 3
Telosys-DAL : Connections management
 How to get a Connection :
//--- Connection from Default Database
Connection c1 = ConnectionManager.getConnection();

//--- Connection from Database 1


Connection c2 = ConnectionManager.getConnection(1);

 How to release a Connection :


Connection c1 = ConnectionManager.getConnection();
c1.close();

if the connection comes from …


 a pool  it is recycled ( in the Telosys pool )
 a factory  it is closed
 a datasource  managed by the DataSource

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 7

DAL – V.O. ( Value Objects )


 The data exchange between the Data Access
Layer and the other layers is done with
“VO” ( “Value Object” ), also known
as “DTO” ( “Data Transfer Object” )
 For each “VO”, 2 Java classes are required :
 The VO itself
 A specific list of this type of VO (with strong type
checking methods )
 Example : to managed “Employees” we need …
 “EmployeeVO.java” ( the VO )
 “EmployeeVOList.java” ( the list of “EmployeeVO” )

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 8

Telosys 4
DAL – V.O. ( Value Objects )
« Employee » example :
GenericVOList Standard « DataList » provided

Telosys
. getList() by Telosys
. size()
. isEmpty()
. clear() LinkedList

extends « GenericVOList » no inheritance

EmployeeVOList EmployeeVO
Specific méthods to
encapsulate the . EmployeeVO add() . getXxxx() Value Object
generic methods of . add( EmployeeVO ) . setXxxx()
DataList . insert ( index, EmployeeVO ) . isXxxx() for entity
. replace ( index, EmployeeVO ) . toString() « Employee »
. remove ( index )
Standard template,
. remove (EmployeeVO )
but no interface
. EmployeeVO get( index ) Standard accessors,
implementation
. EmployeeVO getFirst() for each attribute
because of the strong
. EmployeeVO getNext()
type methods

List of « EmployeeVO »
Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 9

DAL – D.A.O. ( Data Access Objects )


 The DAO provides methods to manipulate
 A single entity : the Value Object
 A list of entity corresponding to a specific Query
 The Value Objects List
 The DAO works with other classes :
 1 Value Object ( VO )
 1 Value Objects List ( VOList )
 0 .. N Query (providing a VOList )

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 10

Telosys 5
DAL – D.A.O. ( Data Access Objects )
 The DAO operations to manipulate a single V.O.

 load (try to load a VO using its primary key)


 save (save a VO by SQL insert or update )
 delete (delete a VO using its primary key )
 insert ( try to insert the VO )
 insertKeyGen ( insert with key generation )
 update ( try to update the VO )
 exists ( check if the VO exists in the database )

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 11

DAL – D.A.O. ( Data Access Objects )


 The DAO operations to manipulate SQL Queries
and V.O. lists
 createQuery ( create a SQL query to be used afterwards )
 loadList ( load a list as the result of a Query )
 saveList ( save a list by a “SQL delete” using the Query criteria
& “n SQL insert” for all the items of the list)
 deleteList ( delete the list using the Query criteria )
 count ( do a “select count(*) ..” using the Query criteria )
 List elements management ( without Query ) :
 updateList ( update all the items of the list )
VOList
 insertList ( insert all the items of the list ) or
List
 deleteList ( delete all the items of the list )

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 12

Telosys 6
DAL – D.A.O. ( Data Access Objects )
 DAO with or without Connections ?
Each operation of a DAO has 4 signatures
Examples :
 dao.save( myVO );
DB id

works with the default database ID ( cf dbconfig.xml )


 dao.save( myVO, base_id );

works with the given database ID ( “int” )

 dao.save( myVO, connection );


Connection

works with the given standard JDBC “Connection”


 dao.save( myVO, database_session );
works with the given “DatabaseSession” object
( a “DatabaseSession” is a Telosys object which encapsulate a
connection, useful for “Screen Managers” )
Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 13

DAL – D.A.O. ( Data Access Objects )


 With logical DB id ( without “Connection” )
 The DAO uses the “ConnectionManager”
to get a connection ( ConnectionManager.getConnection(); )

 Each insert, update or delete is commited automatically


 The connection is closed (recycled if it belongs to a
pool ) after each operation
  The programmer never see the Connection object

 With “Connection” or “DatabaseSession”


 The connection management is the programmer’s
responsibility
 The DAO doesn’t commit anything
 And doesn’t close the connection
Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 14

Telosys 7
How to use D.A.O.

How to get a DAO instance


 A DAO is thread-safe
=> its instance can be shared an reused

 1/ Using the default DAO constructor


EmployeeDAO dao = new EmployeeDAO();

 2/ Using a DAO provider if any (since v 1.0.0)


Employee bean = new Employee();
DAOProvider provider = TelosysDAL.getDAOProvider();
EmployeeDAO dao ;
dao = (EmployeeDAO) provider.getDAO(bean); // by bean instance
dao = (EmployeeDAO) provider.getDAO(bean,3); // same but for DB 3
dao = (EmployeeDAO) provider.getDAO(Employee.class); // by bean class
dao = (EmployeeDAO) provider.getDAO(Employee.class,3); // same for DB 3

( the dynamic DAO registries can be defined in the


files dbconfig.xml and telosys.properties )
Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 16

Telosys 8
DAO management

 DAO description :
 String s = dao.describe()
 The returned string contains
 the DAO Java Class
 the DAO target TABLE
 the set of SQL requests for standard operations :
SELECT, INSERT, UPDATE, DELETE
 Other methods …
 String dao.getTableName()
 Class dao.getEntityBeanClass()
 SqlRequests dao.getSqlRequests()

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 17

DAO & Entities (VO)

Telosys 9
DAO : load an entity by PK
 Set the Primary Key
 vo.setId(“IdValue”);
 Try to load the entity
 dao.load(vo);
 SQL request :
 Select … from … where …
 Return code ( int ) :
 1 – Found and loaded ( VO attributes are populated )
 0 – Not found ( no change on the VO )

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 19

DAO : load with lock

 Lock the record with a “SELECT FOR UPDATE” :


 dao.load(vo, “FOR UPDATE” );
 NB:
 Database specific => any string can be used !
 Use string constants !

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 20

Telosys 10
DAO : check the existence of an entity
 Set the Primary Key
 vo.setId(“IdValue”);
 Check existence
 if ( dao.exists(vo) )
 boolean b = dao.exists(vo)
 SQL request :
 Select count where …
 Return code ( boolean )
 True : the entity exists
 False : the entity doesn’t exist

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 21

DAO : update an entity


 Set the VO attributes
 vo.setId(“IdValue”);
 vo.setOther(…);
 Update
 dao.update(vo);
 SQL request :
 Update table set … where …
 Return code ( int )
 The standard JDBC return value (the number of rows
affected).
 For an entity ( with a unique Key ) :
 1 – Entity updated ( entity found and updated )
 0 – Entity not updated ( entity not found )
Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 22

Telosys 11
DAO : insert an entity
 Set the VO attributes
 vo.setId(“IdValue”);
 vo.setOther(…);
 Insert
 dao.insert(vo);
 SQL request :
 Insert into … (…) values (…)
 Return code ( int )
 The standard JDBC return value (the number of rows
affected).
 For an entity ( with a unique Key ) :
 1 – Successful insert ( entity inserted )
 else : never happen  Exception
Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 23

DAO : insert with key generation


 Set the VO attributes Key
 vo.setAttrib1(..); attribute
is useless
 vo.setAttrib2(..);
 Insert
 Long key = dao.insertKeyGen(vo);
 Set the Key attribute in the VO instance
 vo.setId( key.intValue() );
 SQL request :
 Insert into … (…) values (…)
 Return code :
 The generated key wrapped in a Long object
( or null if none )
Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 24

Telosys 12
DAO : delete an entity
 Set the Primary Key
 vo.setId(“IdValue”);
 Delete
 dao.delete(vo);
 SQL request :
 Delete from … where …
 Return code ( int )
 The standard JDBC return value (the number of rows
affected).
 For an entity ( with a unique Key ) :
 1 – Entity deleted ( entity found and deleted )
 0 – Entity not deleted ( entity not found )

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 25

DAO : save an entity


 Set the VO attributes
 vo.setId(“IdValue”);
 vo.setOther(…);
 Save
 dao.save(vo);
 SQL requests :
 Select count from … where …
 if the enity exists
  Update
 else
  Insert

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 26

Telosys 13
DAO : save an entity
 Return code ( int )
 The standard JDBC return value (the number of rows
affected).
 For an entity ( with a unique Key ) :
 Always 1 :
 entity inserted  1 row affected

 or

 entity updated  1 row affected

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 27

DAL – Exceptions
 TelosysException try
 Use a standard {
// DAO operations
“try catch” block  }
catch ( TelosysException ex )
{
...
}

 What can happen ?


 Duplicate key on “insert”
 Other standard JDBC exceptions :
 the table has changed => the DAO is not up to date
 an integrity rule is violated
 etc…

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 28

Telosys 14
D.A.O. & Lists (VOList)

DAO and ListQueries


 A VOList is loaded by using a DAO and a
ListQuery
 A ListQuery holds
 3 SQL requests with the same “WHERE” clause :
 Select … from … WHERE …
 Select count form … WHERE …
 Delete form … WHERE …
 The parameters to set in the “WHERE” clause
 Lifecycle :
 1/ created by the DAO
 2/ customized with the specific parameters
 3/ passed to the DAO methods to managed VOLists

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 30

Telosys 15
DAO and ListQuery model
DAO ListQuery
<< interface >>
. createQuery() . setParameter(int,int)
. createQuery() creates
. setParameter(int,long)
. createQuery() . setParameter(int,short)
. createQuery() . setParameter(int,Object)
. createQueryAll() uses
. createQueryAll() . getSqlCount()
. getSqlSelect()
. getSqlDelete()

uses

Criteria
Criterion
.
.
*

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 31

DAO : Query for all the entities of a table


 How to load ALL the entities of a table
//--- Create the DAO
EmployeDAO dao = new EmployeDAO();
//--- Create the VOList
EmployeVOList list = new EmployeVOList();

//--- Define a query


ListQuery query = dao.createQueryAll(); // ALL (no WHERE clause)

//--- Load the list using the query


dao.loadList(query, list);

//--- Print the list size


System.out.println("List size = " + list.size());
//--- Print all the VO of the list
Iterator iter = list.iterator() ;
int i = 0 ;
while ( iter.hasNext() )
{
System.out.println(" . " + (i++) + " : " + iter.next() );
}

ListQuery query = dao.createQueryAll( “order by name” );

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 32

Telosys 16
DAO : Query with static criteria
 Query with “ static criteria ” without parameters :
ListQuery query = dao.createQuery( "Matricule > 7000" );
ListQuery query = dao.createQuery( "Matricule > 7000" ,
"order by matricule" );

//--- Load the list using the query


dao.loadList(query, list);

 Query with “ static criteria ” with parameters :


ListQuery query = dao.createQuery( "Matricule > ? and Matricule < ? " );
ListQuery query = dao.createQuery( "Matricule > ? and Matricule < ? ",
"order by matricule" );

query.setParameter( 1, 100 ); // First parameter value


query.setParameter( 2, 200 ); // Second parameter value Param. index :
from 1 to N
//--- Load the list using the query
dao.loadList(query, list);

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 33

DAO : Query with dynamic criteria


 Define the list of criteria :
Criterion [] SQL_CRITERIA =
{
new Criterion( "nom like ?" , ParamType.STRING ), /* 1 */
new Criterion( "prenom like ?" , ParamType.STRING ), /* 2 */
new Criterion( "Matricule > ?" , ParamType.INTEGER ), /* 3 */
new Criterion( "Matricule < ?" , ParamType.INTEGER ) /* 4 */
};
Criteria crit = new Criteria (SQL_CRITERIA, "and" );

 At request time, choose the criteria to use :


crit.doNotUse(1);
crit.doNotUse(2);
crit.useWithValue(3, "10");
crit.useWithValue(4, "900");

 Then, create the query :


ListQuery query = dao.createQuery(crit, "order by Matricule");

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 34

Telosys 17
DAO & ListQuery : limitations
 A DAO works with only one table
 DAO + ListQuery can only retrieve data from a
single table ( a list of VO/records load form the
table )
 To retrieve data with complexes requests…
 see “DataSet”

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 35

DAO : List persistence


 The DAO supports global list persistence,
based on a query criteria :
 dao.deleteList( query )
 Delete all the occurrences corresponding to the query
criteria
 dao.saveList( query, list)
 Save the new list content by removing all the existing
items then inserting the new list items :
 Delete all the occurrences corresponding to the query criteria
 Insert all the occurrences of the list parameter
 NB :
 be sure that there’s no risk of integrity violation when
using a global “delete” for a list
Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 36

Telosys 18
DAO : List persistence
 Bulk insert/update/delete :
 dao.insertList(list)
 dao.updateList(list)
 dao.deleteList(list)
 Insert, update or delete all the elements of the
given list ( VOList or standard java.util.List )

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 37

D.A.O. & Sequences

Telosys 19
Sequence DAO
 A “Sequence DAO” is a specific type of DAO
dedicated to the SEQUENCES

 It provides the standard “NEXT VAL”


and “CURR VAL” operations

 Sequence DAO are available for …


 Oracle
 PostgreSQL
 MySQL ( sequence simulation with tables )

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 39

Sequence DAO
 How to create and use a “Sequence DAO” …

SequenceDAO seq = new SequenceDAO( "request_id_seq", SequenceDAO.POSTGRESQL);

//--- With the default DataBase SequenceDAO.POSTGRESQL


long val = seq.nextVal(); SequenceDAO.ORACLE
SequenceDAO.MYSQL
//--- With a specific DataBase ID
long val = seq.nextVal(DbId);

//--- With a connection


long val = seq.nextVal(c);
long val = seq.currVal(c); NB :
//--- With a DB Session
currVal  only with
long val = seq.nextVal(s); a connection
long val = seq.currVal(s);

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 40

Telosys 20
Sequence DAO
 Best practice :
 create a class for each sequence

public class EmpIdSeqDAO extends SequenceDAO


{
public EmpIdSeqDAO()
{
super( "EmpId" , ORACLE);
}
}

//--- Use an existing Sequence DAO


EmpIdSeqDAO empIdSeq = new EmpIdSeqDAO();
System.out.println("nextVal : " + empIdSeq.nextVal() );

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 41

DataSet

Telosys 21
DataSet
 A “DataSet” is a set of “DataRow” ( 0..N rows )
 A “DataRow” is a set of “Object” ( 0..N cells )
 => a DataSet is like a TABLE
with ROWS and COLUMNS
 A “DataSet” is “abstract” and its content can be
loaded from different sources.
 The “source” of the DataSet is defined in a
“DataSet definition”

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 43

DataSet
 Principle
 Step 1 : “define it” ( constructor + definition )
 DataSet ds = new XXXXXX(…);
 Step 2 : “load or reload it”
 ds.load() Origin types for SQLDataSet :
- Connection
 ds.load ( origin ) - DatabaseSession
- Integer ( Database Id )
 Step 3 : “use it”
ds.load();
for ( int i = 1 ; i <= ds.getRowCount() ; i++ )
{
DataRow dr = ds.getDataRow(i);
System.out.println(" ROW = [" + dr.toString() + "] ");
String s = dr.getString(1));
Date d = dr.getDate(3));
int i = dr.getInt(4));
}

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 44

Telosys 22
DataSet : how to fetch data
for ( int i = 1 ; i <= ds.getRowCount() ; i++ ) From 1 to MAX
{
DataRow dr = ds.getDataRow(i);
System.out.println(" dr.toString() = [" + dr.toString() + "] ");
String s = dr.getString(1));
Date d = dr.getDate(3));
int i = dr.getInt(4));
}

Iterator iter = ds.iterator();


while ( iter.hasNext() )
{
DataRow dr = (DataRow)iter.next();
System.out.println(" dr = [" + dr + "] ");
}

Object o = ds.getObject(2,3); // ( Row, Col ) Row : 1 to MAX


String s = ds.getString(2,3); // ( Row, Col ) Col : 1 to MAX
float f = ds.getFloat(2,3); // ( Row, Col )

if ( ds.isEmpty() )

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 45

DataSet : how to sort rows


 Once the DataSet is loaded, it can be sorted by
column
ds.sort ( 2 ) ; Sort column 2
ds.sort ( 2, "ASC" ) ; Sort column 2 in ascending order
ds.sort ( 2, "DESC" ) ; Sort column 2 in descending order

ds.sortIgnoreCase ( 2 ) ;
ds.sortIgnoreCase ( 2, "ASC" ) ;
ds.sortIgnoreCase ( 2, "DESC" ) ;

if ( ds.isSorted ( 2 ) )
if ( ds.isSortedInAscendingOrder() )
if ( ds.isSortedInDescendingOrder() )

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 46

Telosys 23
SQLDataSet

SQLDataSet
 A “SQLDataSet” is an extension (subclass)
of "DataSet"
 It can be loaded from a relational database,
using a definition based on a SQL request
 The definition for a SQLDataSet is held by an
instance of SQLDataSetDefinition

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 48

Telosys 24
SQLDataSet and relational DB
 Use case 1 : Basic SQLDataSet (no parameter)
//--- DataSet without SQL parameters
SQLDataSetDefinition def = new SQLDataSetDefinition(
"select name, manager, agency",
"from employee" , No parameter in criteria :
null , no "where clause"
"order by name" ); or static "where clause"

SQLDataSetDefinition def2 = new SQLDataSetDefinition(


"select name, manager, agency from employee where agency > 10" );

//--- Set a specific Database ID


def.setDatabaseId(2);

//--- Create the DataSet with the definition


SQLDataSet ds = new SQLDataSet( def );

//--- Load the DataSet using the Database specified in the definition
ds.load() ;

//--- Examples with the load(Object) method :


ds.load(new Integer(1)); // load using the given Database ID
ds.load(connection); // load using the given JDBC Connection
ds.load(dbSession); // load using the given DatabaseSession

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 49

SQLDataSet and relational DB


 Use case 2 :
SQLDataSet with parameters ( static criteria )
//--- DataSet with one INTEGER parameter
int [] paramTypes = { ParamType.INTEGER } ; // One param ( INTEGER )

SQLDataSetDefinition def = new SQLDataSetDefinition(


"select name, manager, agency",
"from employee",
1 .. N fixed parameters
"where agency = ? ",
in the "where clause"
"order by name",
paramTypes ); // Array of param types

SQLDataSetDefinition def2 = new SQLDataSetDefinition(


"select name, manager, agency from employee where agency > ?",
paramTypes );

//--- Set the parameter values


String paramValues[] = { "1" }; // Array of param value(s)

//--- Create the DataSet with the Definition


SQLDataSet ds = new SQLDataSet( def, paramValues );

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 50

Telosys 25
SQLDataSet and relational DB
 Use case 3 : SQLDataSet with “dynamic criteria”
SQLDataSetDefinition def = new SQLDataSetDefinition(
"select name, manager, agency",
"from employee",
null, No "where clause" ( dynamic )
"order by name"); If "where clause", dynamic criteria will be added

//--- Define the dynamic criteria


Criterion[] SQL_CRITERIA = {
new Criterion("name like ?", ParamType.STRING), /* 1 */
new Criterion("manager like ?", ParamType.STRING), /* 2 */
new Criterion("agency > ?", ParamType.INTEGER), /* 3 */
new Criterion("agency < ?", ParamType.INTEGER) /* 4 */
};
Criteria crit = new Criteria(SQL_CRITERIA, "and");
//--- Set dynamically the useful criteria
crit.useWithValue(1, "ZO%");
crit.doNotUse(2);
crit.doNotUse(3);
crit.useWithValue(4, "7000");

//--- Create the DataSet with the Definition


SQLDataSet ds = new SQLDataSet( def, crit );

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 51

SQLDataSet use cases


 DataSet are useful for …
  Complex SQL request :
the SQLDataSetDefinition support
 Joins between different tables
 Additional SQL clauses :
 Order by
 Group by
 …
  Search services :
complex criteria combination with “Dynamic
Criteria”

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 52

Telosys 26
Other SQLDataSet capabilities
 Use the SQLDataSet definition for "count"
 int n = ds.count() ;
Execute a "select count(*)" with the dataset definition criteria
 Load a "page" (a subset of the request result)
 Define the number of lines per page :
 def.setLinesPerPage(100); // default = 20
 Load a page :
 ds.loadPage(2);
The SQL request is executed, only the expected rows are
retrieved from the JDBC ResultSet
 boolean b = ds.endOfResultSet();
To know if the last row of the ResultSet has been loaded
 Retrieve the SQL request :
 String sql = ds.getSqlRequest();

Telosys framework - D.A.L. ( Laurent Guérin / ver 1.8 ) 53

THE END

Telosys 27

Вам также может понравиться