application servers & web servers faqs

40
1) What is an Application Server? To use computers, users need certain software to be present on those computers. These software are known as applications. Common examples of Applications are Microsoft Word, Lotus 1-2-3, CodeWarrior, etc. A server is a huge, powerful computer into which users can login and access the resources provided by the server. Thus, an application server is a computer which allows users to login and work with certain applications on the server itself, without having to install those applications on the user's home machine. 2) How do I benefit from using the Application Server? Earlier, the only way to run applications on your home computer was to first "INSTALL" them. To do that, you would need to purchase licensed copies of the software. For applications like CodeWarrior or MATLAB, the cost would be almost $100 each. Earlier students had only two alternatives: 1. Work only on-campus by coming to the ME Learning Resource Center. OR 2. Spend a load of money to buy the software needed and install it at home. The Application Server gives you a third alternative. You can now work from home, and run CodeWarrior and MATLAB without having to install it. All you do is login into the ME Application Server, and choose the application you want to run. 3) Sounds great. How do I go about using the Application Server? To use the application server, you need the following things:

Upload: api-3716512

Post on 10-Apr-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Application Servers & Web Servers Faqs

1) What is an Application Server?

To use computers, users need certain software to be present on those computers. These software are known as applications. Common examples of Applications are Microsoft Word, Lotus 1-2-3, CodeWarrior, etc.

A server is a huge, powerful computer into which users can login and access the resources provided by the server.

Thus, an application server is a computer which allows users to login and work with certain applications on the server itself, without having to install those applications on the user's home machine.

2) How do I benefit from using the Application Server?

Earlier, the only way to run applications on your home computer was to first "INSTALL" them. To do that, you would need to purchase licensed copies of the software. For applications like CodeWarrior or MATLAB, the cost would be almost $100 each. Earlier students had only two alternatives:1. Work only on-campus by coming to the ME Learning Resource Center.OR2. Spend a load of money to buy the software needed and install it at home.

The Application Server gives you a third alternative. You can now work from home, and run CodeWarrior and MATLAB without having to install it. All you do is login into the ME Application Server, and choose the application you want to run.

3) Sounds great. How do I go about using the Application Server?To use the application server, you need the following things:

1. A reasonably fast Internet connection from your home computer.2. A College of Engineering Windows Active Directory login account (see Q5 if you are not sure about this)3. The AppServer client installed on your computer. This is the only thing that you will actually need to install on your computer, and it is available for free download.

For details on the installation and configuration of the AppServer client, see the following link:http://me205serv.me.utexas.edu/AppServer_Windows.htm (windows)Instructions for Mac (OSX only)Instructions for Mac (9.x,8.x)

4) What was that in the previous question about a ME LRC account? Don't tell me there's another username and password to be remembered for this course...

Page 2: Application Servers & Web Servers Faqs

Yes. To access the Application Server, (or anything to do with the ME LRC), you need a ME LRC account. This will stay with you through the course of your studies in the Department, long after you finish this course.

5) Do I already have a College of Engineering Windows Active Directory login account? How do I get it if I don't already have it?

Are you using the computers in the Learning Resource Center in ETC 3.128? If yes, the username and password that you used to log in there are what you need.

If not, please follow the following link:

https://utdirect.utexas.edu/engine/adrequest.WBX

and apply online for your account. You should get your account within 48 hrs after applying.

6) What username and password do I use to access the Application Server?

See the previous questions. You need a login account to access the Application Server.

7) Where do I create new C project files when I work with the application server?

When you're working with the application server, it might be a good idea to save the C project files and program files in the Z: drive, especially if you are using dial-up internet connection. Creating and running programs on your local computer using the application server will be slower than saving the files in the Z: drive.

8) I have saved the C program files in the Z: drive. But I am having trouble transferring the files to my local computer, so that I can send the programs to have them graded. How do I attach the C files to the email now?

Once you have finished working on your programs and are ready to send them, you can then open the MAIN.C file in CodeWarrior. Then click on the FILE menu, then click on SAVE AS or SAVE A COPY AS and then save a copy of the C program file on your local computer, just to send it to us. Your computer's C: drive is mapped as V: drive. So when you are saving the files, be sure to select V: drive. Now you should be able to find the file on your local computer and be able to attch it to the email.

9) I saved the new C project files on the Desktop. But when I look in my Desktop I can't find the files or folders. What have I done wrong?

You have not done anything wrong. When you are working with CodeWarrior or Matlab using the applicatoin server, the Desktop it shows is the dektop on your Z: drive and not your local computer's. So when you saved the files, you had actually saved it on the server. This is why you can't find it on your computer's Desktop. To save a file on your

Page 3: Application Servers & Web Servers Faqs

computer, you'll have to choose the V: drive or the U: drive. The C: drive on your computer is mapped as V: drive and the D: drive on your computer is mapped as U: drive. So, save the files in V: drive and then you should be able to find it in your C: drive.

10) How are things affected when I save my files on my local computer as against saving them on the Z: drive?

Opening and running C program files on the Z; drive will be faster than working on your programs when you have them saved on your local computer. This is especially true if you have a slow internet connection.

11) There seem to be problems with the connection to the server, or the server seems to have have gone down. What do I do? Who do I contact?

The application server is run by the Computer Administration Group at the Mechanical Engineering Departmentt. One of the objectives of this course is to help students in ME understand whom to report to, the problems associated with the software in ME LRC and the application server. If you think you are having trouble connecting to the server or if the server has gone down, please contact the Computer Administration Group.

What is the difference between an application server and a Web server?

A Taking a big step back, a Web server serves pages for viewing in a Web browser, while an application server provides methods that client applications can call. A little more precisely, you can say that:

A Web server exclusively handles HTTP requests, whereas an application server serves business logic to application programs through any number of protocols.

Let's examine each in more detail.The Web server

A Web server handles the HTTP protocol. When the Web server receives an HTTP request, it responds with an HTTP response, such as sending back an HTML page. To process a request, a Web server may respond with a static HTML page or image, send a redirect, or delegate the dynamic response generation to some other program such as CGI scripts, JSPs (JavaServer Pages), servlets, ASPs (Active Server Pages), server-side JavaScripts, or some other server-side technology. Whatever their purpose, such server-side programs generate a response, most often in HTML, for viewing in a Web browser.

Understand that a Web server's delegation model is fairly simple. When a request comes into the Web server, the Web server simply passes the request to the program best able to

Page 4: Application Servers & Web Servers Faqs

handle it. The Web server doesn't provide any functionality beyond simply providing an environment in which the server-side program can execute and pass back the generated responses. The server-side program usually provides for itself such functions as transaction processing, database connectivity, and messaging.

While a Web server may not itself support transactions or database connection pooling, it may employ various strategies for fault tolerance and scalability such as load balancing, caching, and clustering—features oftentimes erroneously assigned as features reserved only for application servers.The application server

As for the application server, according to our definition, an application server exposes business logic to client applications through various protocols, possibly including HTTP. While a Web server mainly deals with sending HTML for display in a Web browser, an application server provides access to business logic for use by client application programs. The application program can use this logic just as it would call a method on an object (or a function in the procedural world).

Such application server clients can include GUIs (graphical user interface) running on a PC, a Web server, or even other application servers. The information traveling back and forth between an application server and its client is not restricted to simple display markup. Instead, the information is program logic. Since the logic takes the form of data and method calls and not static HTML, the client can employ the exposed business logic however it wants.

In most cases, the server exposes this business logic through a component API, such as the EJB (Enterprise JavaBean) component model found on J2EE (Java 2 Platform, Enterprise Edition) application servers. Moreover, the application server manages its own resources. Such gate-keeping duties include security, transaction processing, resource pooling, and messaging. Like a Web server, an application server may also employ various scalability and fault-tolerance techniques.An example

As an example, consider an online store that provides real-time pricing and availability information. Most likely, the site will provide a form with which you can choose a product. When you submit your query, the site performs a lookup and returns the results embedded within an HTML page. The site may implement this functionality in numerous ways. I'll show you one scenario that doesn't use an application server and another that does. Seeing how these scenarios differ will help you to see the application server's function.Scenario 1: Web server without an application server

In the first scenario, a Web server alone provides the online store's functionality. The Web server takes your request, then passes it to a server-side program able to handle the request. The server-side program looks up the pricing information from a database or a

Page 5: Application Servers & Web Servers Faqs

flat file. Once retrieved, the server-side program uses the information to formulate the HTML response, then the Web server sends it back to your Web browser.

To summarize, a Web server simply processes HTTP requests by responding with HTML pages.Scenario 2: Web server with an application server

Scenario 2 resembles Scenario 1 in that the Web server still delegates the response generation to a script. However, you can now put the business logic for the pricing lookup onto an application server. With that change, instead of the script knowing how to look up the data and formulate a response, the script can simply call the application server's lookup service. The script can then use the service's result when the script generates its HTML response.

In this scenario, the application server serves the business logic for looking up a product's pricing information. That functionality doesn't say anything about display or how the client must use the information. Instead, the client and application server send data back and forth. When a client calls the application server's lookup service, the service simply looks up the information and returns it to the client.

By separating the pricing logic from the HTML response-generating code, the pricing logic becomes far more reusable between applications. A second client, such as a cash register, could also call the same service as a clerk checks out a customer. In contrast, in Scenario 1 the pricing lookup service is not reusable because the information is embedded within the HTML page. To summarize, in Scenario 2's model, the Web server handles HTTP requests by replying with an HTML page while the application server serves application logic by processing pricing and availability requests.Caveats

Recently, XML Web services have blurred the line between application servers and Web servers. By passing an XML payload to a Web server, the Web server can now process the data and respond much as application servers have in the past.

Additionally, most application servers also contain a Web server, meaning you can consider a Web server a subset of an application server. While application servers contain Web server functionality, developers rarely deploy application servers in that capacity. Instead, when needed, they often deploy standalone Web servers in tandem with application servers. Such a separation of functionality aids performance (simple Web requests won't impact application server performance), deployment configuration (dedicated Web servers, clustering, and so on), and allows for best-of-breed product selection.Author BioTony Sintes is an independent consultant and founder of First Class Consulting, a consulting firm that specializes in bridging disparate enterprise systems and training. Outside of First Class Consulting, Tony is an active freelance writer, as well as author of

Page 6: Application Servers & Web Servers Faqs

Sams Teach Yourself Object-Oriented Programming in 21 Days (Sams, 2001; ISBN: 0672321092).

Application server is a Web server with the notion of logic. In other words, you can host applications there and expose those applications through a Web-based product. Web servers just service up content, HTML pages and other Web-capable files.

Difference between Web server & Application server Sep 25, 2006 12:08 AM

Click to email this message

please can anyone tell me the Difference between Web server & Application server........

[Dukes Earned 174] watertownjordanPosts:1,718Registered: 2/2/02

Re: Difference between Web server & Application server Sep 25, 2006 1:13 AM (reply 1 of 5)

Click to email this message

A web server is a server designed to communicate with a web browser. Content includes text-based two-way communication with most of the com going from server to client. Data consists of text, formatting, graphics, sounds, and dynamic content.

Page 7: Application Servers & Web Servers Faqs

An application server can be of several designs, but is basically a synchronous two-way sever that provides access to a single application shared among users through web-based or proprietiary methods. The content consists of data types, app commands, system commands, and data of complex types.

Typically, an app server provides a web-based platform for access to a database-driven application.

You could think of a web search engine as a focused application server. It's a web-based platform to access an application that queries a database of websites based on keywords.

[Dukes Earned 174] watertownjordanPosts:1,718Registered: 2/2/02

Re: Difference between Web server & Application server Sep 25, 2006 1:16 AM (reply 2 of 5)

Click to email this message

An App Server may also use non-web methods to deliver traditional access to applications.

Let's say a company has software with 10 licenses and 100 employees. Well, you can't install 100 copies of the software, nor can you allow 10 employees to use the same computer at the same time.

Therefore, a computer could connect to an app server, get 1 of 10 licenses without violating the law.

[Dukes Earned 13] MortenHjerlHansenPosts:100Registered: 20/10/05

Re: Difference between Web server & Application server Sep 25, 2006 1:17 AM (reply 3 of 5)

Click to email this message

Page 8: Application Servers & Web Servers Faqs

You

Both are typically accessed via the internet over the http protocol, so from the viewpoint of the client, theres no difference. There tends to be a common understanding, in the Java world, that application servers implements the full Java EE specification, while web servers implements only a subset.

See also.

http://en.wikipedia.org/wiki/Application_server

http://en.wikipedia.org/wiki/Web_server

[Dukes Earned 82] Herko_ter_HorstPosts:1,427Registered: 8/28/03

Re: Difference between Web server & Application server Sep 25, 2006 1:47 AM (reply 4 of 5)

Click to email this message

Common understanding? Not for me anyways. Web servers have nothing to do with Java in my understanding.

I expect a basic web server to be able to serve static resources over http, that's it. I expect an application server to be a deployment platform for applications written in a specific language.

For example, if I extend Apache httpd (which is, in its default configuration, an already very advanced webserver with some application server characteristics) with mod_php, I get a PHP application server.

For Java, I would distinguish between Servlet Containers (like Tomcat, Jetty, etc.) and J(2)EE Application Servers (like JBoss, Websphere, etc). I expect Servlet Containers to be able to handle webapps containing servlets and JSP, while I expect J(2)EE Application Servers to implement the full J(2)EE stack. Because most of these applications are web applications, both Servlet Containers and Application Servers are usually able to act as web servers.

Page 9: Application Servers & Web Servers Faqs

Hibernate FAQs

What is Hibernate?

Hibernate is a powerful, high performance object/relational persistence and query service. This lets the users to develop persistent classes following object-oriented principles such as association, inheritance, polymorphism, composition, and collections.

What is ORM?

ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of objects in a Java application in to the tables of a relational database using the metadata that describes the mapping between the objects and the database. It works by transforming the data from one representation to another.

What does an ORM solution comprises of? It should have an API for performing basic CRUD (Create, Read, Update, Delete) operations on objects of persistent classes

Should have a language or an API for specifying queries that refer to the classes and the properties of classes

An ability for specifying mapping metadata

It should have a technique for ORM implementation to interact with transactional objects to perform dirty checking, lazy association fetching, and other optimization functions

What are the different levels of ORM quality?

There are four levels defined for ORM quality.

Pure relational Light object mapping Medium object mapping Full object mapping

Page 10: Application Servers & Web Servers Faqs

What is a pure relational ORM?

The entire application, including the user interface, is designed around the relational model and SQL-based relational operations.

What is a meant by light object mapping?

The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. This approach is successful for applications with a less number of entities, or applications with common, metadata-driven data models. This approach is most known to all.

What is a hibernate xml mapping document and how does it look like?

In order to make most of the things work in hibernate, usually the information is provided in an xml document. This document is called as xml mapping document. The document defines, among other things, how properties of the user defined persistence classes’ map to the columns of the relative tables in database.

<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping> <class name="sample.MyPersistanceClass" table="MyPersitaceTable"> <id name="id" column="MyPerId"> <generator class="increment"/> </id> <property name="text" column="Persistance_message"/> <many-to-one name="nxtPer" cascade="all" column="NxtPerId"/> </class> </hibernate-mapping>

Everything should be included under <hibernate-mapping> tag. This is the main tag for an xml mapping document.

What the Core interfaces are of hibernate framework?

There are many benefits from these. Out of which the following are the most important one. Session Interface – This is the primary interface used by hibernate applications. The instances of this interface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread safe. SessionFactory Interface – This is a factory that delivers the session objects to hibernate application. Generally there will be a single SessionFactory for the whole application and it will be shared among all the application threads.

Page 11: Application Servers & Web Servers Faqs

Configuration Interface – This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify the location of hibernate specific mapping documents. Transaction Interface – This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction. Query and Criteria Interface – This interface allows the user to perform queries and also control the flow of the query execution.

What are Callback interfaces?

These interfaces are used in the application to receive a notification when some object events occur. Like when an object is loaded, saved or deleted. There is no need to implement callbacks in hibernate applications, but they’re useful for implementing certain kinds of generic functionality.

Can I rollback after a session.flush() ?

Definitely YES! Flushing the session means executing SQL like you do in plain JDBC. It has absolutely no relationship with transaction. Actually Hibernate can flush session behind your back.

I have CGLIB / reflection optimizer errors or similar when migrating from 2.1 betaX to 2.1 rc1.

Symptoms may be :

* java.lang.NoClassDefFoundError during Configuration.buildSessionFactory * java.lang.IllegalAccessError in net.sf.cglib.core.ClassEmitter.setTarget * java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.visitMethod(ILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;)Lorg/objectweb/asm/CodeVisitor;

hibernate 2.1 rc1 and above now use CGLIB 2. Remove your old CGLIB jar from your classpath and replace it with the one shipped with hibernate2 (./lib/cglib2.jar).

I've followed the above instructions and I'm still having CGLIB problems in 2.1 Final.

Examples are:

Caused by: java.lang.NoSuchMethodException: java.sql.Statement.execute(java.lang.String, [B) at java.lang.Class.getDeclaredMethod(Class.java:1256) at java.sql.PreparedStatement$$EnhancerByCGLIB$$3c240523.<clinit>(<generated>)

Page 12: Application Servers & Web Servers Faqs

Caused by: java.lang.ClassFormatError: Illegal Field name "CGLIB$load_class$ARRAY0$_Ljava_lang_String;" at java.lang.ClassLoader.defineClass0(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:537)

Both of these exceptions are from bugs in the CGLIB 2.0 RC1 library included with Hibernate 2.1 Final. They have been fixed in CGLIB 2.0 RC2, which may be downloaded here:

http://prdownloads.sourceforge.net/cglib/cglib-full-2.0-RC2.jar?download

This updated jar file will be included with the next release of Hibernate.

Related forum threads are here:

http://forum.hibernate.org/viewtopic.php?t=925978

http://forum.hibernate.org/viewtopic.php?t=926299

Storing Big5 or Unicode Strings

Data has some String fields that stores Chinese Big5 encoding String , ex: Title and Description; I use DAO pattern , and in the implementation code , when persisting 'Data', I have to manually change the String encoding from Big5 to 8859_1 to be able to store it to MySQL. I found the final solution:

In hibernate.cfg.xml:

<property name="connection.url">jdbc:mysql://host/db?useUnicode=true&amp;characterEncoding=Big5</property>

Both uneUnicode = true , and characterEncoding=Big5 are needed and make sure to 'escape' the '&' character.

I've got problems with legacy tables with UPPERCASE/lowercase identifiers

You can easily quote the table names in the mapping file, using backticks:

<class table="`TableName`" ..... >

I've got problems with WebLogic and JNDI, how does it work?

This forum believe there's some problem if you do it the regular way like most app server. Therefore, try the following (which works for me). Use a WLS Startup class to bind Hibernate Session Factory object in WLS JNDI. Here's an excerpt of a possible code:

Page 13: Application Servers & Web Servers Faqs

public class WLSStartup implements T3StartupDef { public static final String SESSION_FACTORY_JNDI = "hibernate"; public static final String URL = "t3://localhost:7001";

/** * Called by WebLogic server upon startup. This is where everything should * be initialzed. * * @param name the JNDI name of this class * @param args any input parameters * * @return the status. * * @throws Exception in case of any error */

public String startup( String name, Hashtable args ) throws Exception { String METHOD_NAME = "startup ";

// Bind the various Hibernate Object to the Weblogic JNDI try { log ( METHOD_NAME + " Going to bind Hibernate object. " ); doBind( ); log ( METHOD_NAME + " Bound Hibernate object!" ); } catch ( Exception exception ) { log ( METHOD_NAME + " Exception while binding Hibernate Object to Weblogic JNDI" ); exception.printStackTrace ( ); }

return "WLS Startup completed successfully"; }

/** * Performs Hibernate objects to Weblogic JNDI Namespace bindings. * It gets the initial context and binds the Hibernate objects to it. * * @param None * @throws Exception in case of any errors */

Page 14: Application Servers & Web Servers Faqs

private static void doBind( ) throws Exception { Properties environment = null; InitialContext context = null;

try { //Properties for storing JNDI configuration information environment = new Properties( );

//Add initial context factory environment.put( Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory"); environment.put( Context.PROVIDER_URL, URL ); log( "Constructing an Initial Directory Context object" ); context = new InitialContext( environment );

Datastore ds = Hibernate.createDatastore(); SessionFactory factory = ds.buildSessionFactory();

if (factory == null) throw new Exception("SessionFactory cannot be built?!"); try { if( context.lookup(SESSION_FACTORY_JNDI ) != null ) context.rebind(SESSION_FACTORY_JNDI, factory ); else context.bind(SESSION_FACTORY_JNDI, factory ); } catch ( NamingException nameEx ) { context.bind(SESSION_FACTORY_JNDI, factory ); }

} catch ( NamingException nameExp ) { throw new Exception( "NamingException: " + nameExp.getMessage( )); } catch( Exception excp ) { throw excp; }

Page 15: Application Servers & Web Servers Faqs

finally { if( context != null ) { try { context.close( ); context = null; } catch ( NamingException nameExp ) { throw new Exception( "NamingException for context close: " nameExp.getMessage( )); } } environment = null; }

}

Jar up the relevant Hibernate jar files and configure this Startup class under WLS console.

Then at your JNDI client (Servlet or EJBs for example) you can have a code similar to this excerpt below: -

Object objref; Context context; Hibernate.configure();

//The usual WLS JNDI context context = getInitialContext(); objref = context.lookup(WLSStartup.SESSION_FACTORY_JNDI); sessionFac = (SessionFactory) PortableRemoteObject.narrow(objref, SessionFactory.class);

if sessionFac == null) throw new Exception("Null SessionFactory found?!");

Works great with Struts 1.1 on WLS 6.X and 7.X. I've tested by writing some subclass relationship data into Oracle 8i!

Any questions can be directed to [email protected].

MS SQL Server with JSQLConnect driver throws exception with delete()

Page 16: Application Servers & Web Servers Faqs

Hibernate 2.0.1 propagates an exception from Session.flush() following Session.delete(Object):

net.sf.hibernate.HibernateException: SQL update or deletion failed (row not found) at net.sf.hibernate.impl.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:25)

NonBatchingBatcher.addToBatch expects PreparedStatement.executeUpdate() to return 1, but it returns 0 in this case, even though it has deleted 1 row from the database.

I solved this problem by appending "/lastUpdateCount=true" to the JDBC url for JSQLConnect. This makes the JDBC driver behave as Hibernate expects. Without this property, it seems the driver returned the number of rows updated by a trigger that was executed as a side-effect of the requested change. See http://www.j-netdirect.com/JSQLConnect/TechnicalReference.html#ConnectSettings for more information.

Should I GROUP BY all object attributes in HQL?

At present you need to explicitly enumerate all the employee properties in the GROUP BY. This might be a wrinkle in HQL, or it might actually be OK.

SELECT e FROM Employee e LEFT JOIN Customer c AS c.staff.id WHERE e.team.id = :id GROUP BY e.firstName, e.lastName, e.salary ORDER BY count(c.staff.id) ASC

"Flush during cascade is dangerous" with own equals() method

When you delete child object from collection like described in documentation and

* Use proxy for you persistent class * Overwrite equals method for your class * Use class comparison checking in your equals() like this

if( !(o.getClass() == getClass()) ) return false;

You may get an error because both classes are not identical. Use instanceof instead.

How to handle transactions that span multiple data access objects?

Consider a business controller that needs to delegate to 2 DAOs for a certain use case. The processing is supposed to occur within a single transaction. How to inform your DAOs that they need to participate in the surrounding transaction, instead of opening

Page 17: Application Servers & Web Servers Faqs

their own Hibernate Session? And how to make them run in their individual transactions else?

Passing around a Session instance as parameter to the DAO methods is not desirable, as such a required parameter is inconvenient, and the DAO interfaces should not be Hibernate-specific. A RYO solution according to the ThreadLocal Session pattern will work but tie the business controllers to Hibernate for transaction demarcation.

The goal is to make DAO interfaces agnostic of both the data access mechanism of an implementation and the actual transaction strategy of the caller. This allows for e.g. mixing Hibernate DAOs and plain JDBC DAOs with either native Hibernate transactions or JTA. A generic transaction mechanism is needed, with support for passing thread-bound Hibernate Sessions or JDBC Connections or whatever.

The Spring Framework provides such generic transaction management in a very lightweight way, with first-class support for Hibernate, backed by either native transactions or JTA. There is also respective support for JDO and plain JDBC. Transactions can be demarcated either programmatically or declaratively via an AOP interceptor. The generic management helps to avoid tying business objects to a particular transaction strategy.

Furthermore, Spring's lightweight bean container offers means for wiring up an application, e.g. a middle tier that consists of business objects, data access objects, and resources. Spring also provides generic AOP support within the bean container, and sophisticated convenience support for plain JDBC access. Note that Spring's individual parts can be reused on their own easily, as they are as loosely coupled as possible.

Data Access with the Spring Framework

What is the precedence for the methods in the Lifecycle and Interceptor interfaces?

Save or Update:

* Interceptor.isUnsaved

Save:

* Lifecycle.onSave * Interceptor.onSave

Update:

* Lifecycle.onUpdate

Load:

Page 18: Application Servers & Web Servers Faqs

* Interceptor.onLoad * Lifecycle.onLoad

Delete:

* Interceptor.onDelete * Lifecycle.onDelete

Flush:

* Interceptor.preFlush * Interceptor.findDirty * Interceptor.onFluchDirty * Interceptor.postFlush

Hibernate startup is slow, what can I do?

I just discovered the new cglib version available at cglib.sf.net. Using the new library has cut my Hibernate startup configuration times from sometimes 3 minutes (I had over 70 persistent classes) to nearly nothing. This has been a godsend, given the nature of the app is that it has to be restarted for every code change -- debugging could be a nightmare.

If not allready done could you (Gavin) start packaging this newer version with Hibernate -- it's a real time saver.

Luke Monahan

You need to remove bcel.jar from classpath and use asm.jar for performance ( BCEL has priority in cglib 1.0 ). We will drop BCEL in the next version.

Juozas Baliuka

MS SQL performance and unicode (indexing of VARCHARs)

Am I the only person in the world who didn't know what happens if you use VARCHAR's with Java and the MS SQL JDBC driver? It seems unlikely because I can find no mention of this in the list archives or the like. If you use VARCHARs for database tables and index those columns either (as a primary key or not) , then you will find that without this option

sendStringParametersAsUnicode=false

set on the JDBC driver string, all queries will use a table scan rather than the index to access rows. This is somewhat annoying with large tables (as you can imagine). The reason is that the JDBC driver marks the string as an NVARCHAR so when the execution plan is created, it includes the conversion of the row's VARCHAR to an

Page 19: Application Servers & Web Servers Faqs

NVARCHAR. This stops SQL Server from using an index and you end up with a very slow query.

What gets even more annoying (and potentially confusing) is that this does not happen with direct queries, only prepared statements (hence the issue with hibernate). It might be wise to make note of this fact in the FAQ or documentation. I only found 1 article on google in a news group that mentions this (and I am indebted to that person for enlightening me...)

The article: on Google Groups

From: Gary Evesson <[email protected]>

I'm getting a java.lang.ExceptionInInitializerError with JDK 1.3

Hibernate is build with the latest stable JDK 1.4, this error may be a binary incompatibility with JDK 1.3. Recompile the hibernate.jar (ant jar) with JDK 1.3. It looks like this is a combination/issue with both Tomcat and the JDK. Here's the old thread: http://sourceforge.net/forum/message.php?msg_id=2062040

If anyone is able to reproduce and debug this issue, please add to this FAQ entry.

Follow up:

Hi, we are a develop team at Universidad de las Americas, Puebla in Mexico and

we got the same problem trying to run a web app using hiberante, the app was developed using JSDK 1.4, but in the real enviroment it was suposed to run on a JSDK 1.3, all we did to get it running was:

1) upgraded to the last stable version of the 1.3 platform

2) recompiled the hiberante source with this version (all though any 1.3 version seems to do fine)

3) get the apropiate jdbc drivers for the jsdk and database

and that's it, the app is running on a JSDK 1.3 enviroment using all the virtuous functions in hibernate :)

I'm getting "Too many tables. MySQL can only use 31 tables in a join"

You can set outer-join="false" on associations or, in Hibernate 2.1, use hibernate.max_fetch_depth.

Page 20: Application Servers & Web Servers Faqs

Websphere 5 produces a com.ibm.websphere.ce.cm.StaleConnectionException: Connection is closed

Unfortunately on WebSphere 5.0 I get the following error message when closing a Hibernate Session:

net.sf.hibernate.util.JDBCExceptionReporter TRAS0014I: The following exception was logged com.ibm.websphere.ce.cm.StaleConnectionException: Connection is closed

We had this same problem with data source connections in Websphere. We "fixed" it by configuring the data source to "Disable auto connection cleanup". It's a checkbox in the data source setup in Websphere.

What are the rules for the SQL String passed in the new createSQLQuery"

There is an excellent thread about this, see http://forum.hibernate.org/viewtopic.php?t=418

Rules:

#01: All of the columns must be specified, either via {alais1}.* or by explicitly listing each.

[to be continued]

Hibernate crashes on this Sun RAQ server. What gives?

The problem with most Sun RAQs is that they are loaded with pretty old (and I guess stable) versions of Java (version 1.3 is old now, OK?!). The problem here is related to a FAQ above in that you get some really odd null pointer exceptions, e.g. when creating the session factory or when hydrating a rowset back into an object. The solution is simple: rebuild hibernate with a similar version of Java to the one on the server. In most cases this is just a case of installing the old version of Java and then setting JAVA_HOME to point to the old Java before running the hibernate build script (shipped with the distribution).

From: Russ Freeman <[email protected]>

Invalid parameter exceptions listed when an object mapping is read

Although the documentation suggests that object properties can be public, private or protected, there is still a restriction on accessing non-public properties via reflection when using a JDK < 1.4. Overcome the problem by making these properties public and document the reason in the code for future mortals!

From: Russ Freeman <[email protected]>

Page 21: Application Servers & Web Servers Faqs

Can I disable the Session cache?

You can't disable it, because that would expose you to stack overflows where there are circular references, etc.

You can, however, either clear() it, or change the FlushMode.

Issues with MS SQL Server UID (GUIDs)

MS SQL Server UID is a data type of 16-bytes binary values that operate as globally unique identifiers (GUIDs).

In character string format the UID looks like this: '{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}'

I found that this data type could cause some problems when used in i.e. loading an object from the database.

The following two examples will both have the same result:

session.load(MyObject.class, "{2C90AA1E-00F8-00F8-0001-FFFFF8F40C12}");

, and:

session.load(MyObject.class, "2C90AA1E-00F8-00F8-0001-FFFFF8F40C12");

MS SQL Server seems to remove the brackets from the UID when querying the database. When using this together with Apache JCS the difference between using brackets and not using brackets is crucial!

Suppose that MyObject have a one-to-many relationship to MyOtherObject, and this relationship is bi-directional (MyOtherObject have a reference to its parent MyObject).

When loading MyObject from database with an UID including brackets, Apache JCS will store this UID (with brackets) as the key used for locating the object in cache. This will cause the related object, MyOtherObject, not finding its parent (MyObject) in the cache and therefore load another instance of the parent MyObject into the cache.

The reason for this is; MyOtherObject will have a reference to the parent defined as an foreign key in the database. When MyOtherObject will get loaded it will try to lookup its parent by an UID without brackets!

Since we specified to load MyObject by an UID with brackets you wont get a hit in the cache cause MS SQL Server returns the UID from database without brackets. A new

Page 22: Application Servers & Web Servers Faqs

instance of MyObject will be created and its key in Apache JCS will be a UID without the brackets.

Now we have two instances of the parent MyObject in Apache JCS, one located by its UID with brackets and another located by its UID without brackets.

If you load MyObject by its UID with brackets, change the state of the object and then tries to persist the changes to database - it just wont happen!

One UPDATE will be performed cause you have changed the state of the instance MyObject stored in Apache JCS located by its UID with brackets, another UPDATE on the related instance MyOtherObject will be performed, and another UPDATE on MyObject will be performed - on the other instance to MyObject handled by MyOtherObject. This instance have not been changed but is different from the instance of MyObject located by its UID with brackets and therefor be persisted into the database with its old values. And since MS SQL Server sees the UID with or without the brackets as same, the updated row in database with the new values will be overwriten with the old values!

REMEBER! An UID with brackets or without brackets is handled the same by MS SQL Server, but NOT by Apache JCS.

21.

What does hibernate.properties file consist of?

This is a property file that should be placed in application class path. So when the Configuration object is created, hibernate is first initialized. At this moment the application will automatically detect and read this hibernate.properties file.

hibernate.connection.datasource = java:/comp/env/jdbc/AuctionDB hibernate.transaction.factory_class = net.sf.hibernate.transaction.JTATransactionFactory hibernate.transaction.manager_lookup_class = net.sf.hibernate.transaction.JBossTransactionManagerLookup hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect

What should SessionFactory be placed so that it can be easily accessed?

As far as it is compared to J2EE environment, if the SessionFactory is placed in JNDI then it can be easily accessed and shared between different threads and various components that are hibernate aware. You can set the SessionFactory to a JNDI by configuring a property hibernate.session_factory_name in the hibernate.properties file.

Page 23: Application Servers & Web Servers Faqs

What are POJOs?

POJO stands for plain old java objects. These are just basic JavaBeans that have defined setter and getter methods for all the properties that are there in that bean. Besides they can also have some business logic related to that property. Hibernate applications works efficiently with POJOs rather then simple java classes.

What is object/relational mapping metadata?

ORM tools require a metadata format for the application to specify the mapping between classes and tables, properties and columns, associations and foreign keys, Java types and SQL types. This information is called the object/relational mapping metadata. It defines the transformation between the different data type systems and relationship representations.

What is HQL?

HQL stands for Hibernate Query Language. Hibernate allows the user to express queries in its own portable SQL extension and this is called as HQL. It also allows the user to express in native SQL.

What are the different types of property and class mappings? Typical and most common property mapping

<property name="description" column="DESCRIPTION" type="string"/>

Or

<property name="description" type="string"> <column name="DESCRIPTION"/> </property>

Derived properties

<property name="averageBidAmount" formula="( select AVG(b.AMOUNT) from BID b where b.ITEM_ID = ITEM_ID )" type="big_decimal"/>

Typical and most common property mapping

<property name="description" column="DESCRIPTION" type="string"/>

Controlling inserts and updates

<property name="name" column="NAME" type="string" insert="false" update="false"/>

Page 24: Application Servers & Web Servers Faqs

What is Attribute Oriented Programming?

XDoclet has brought the concept of attribute-oriented programming to Java. Until JDK 1.5, the Java language had no support for annotations; now XDoclet uses the Javadoc tag format (@attribute) to specify class-, field-, or method-level metadata attributes. These attributes are used to generate hibernate mapping file automatically when the application is built. This kind of programming that works on attributes is called as Attribute Oriented Programming.

What are the different methods of identifying an object?

There are three methods by which an object can be identified.

Object identity –Objects are identical if they reside in the same memory location in the JVM. This can be checked by using the = = operator. Object equality – Objects are equal if they have the same value, as defined by the equals( ) method. Classes that don’t explicitly override this method inherit the implementation defined by java.lang.Object, which compares object identity. Database identity – Objects stored in a relational database are identical if they represent the same row or, equivalently, share the same table and primary key value.

What are the different approaches to represent an inheritance hierarchy? Table per concrete class. Table per class hierarchy. Table per subclass.

What are managed associations and hibernate associations?

Associations that are related to container management persistence are called managed associations. These are bi-directional associations. Coming to hibernate associations, these are unidirectional.

Q: What is threaded programming and when is it used?

A: Threaded programming is normally used when a program is required to do more than one task at the same time. Threading is often used in applications with graphical user interfaces; a new thread may be created to do some processor-intensive work while the main thread keeps the interface responsive to human interaction.

The Java programming language has threaded programming facilities built in, so it is relatively easy to create threaded programs. However, multi-threaded programs introduce a degree of complexity that is not justified for most simple command line applications.

Q: Why are wait(), notify() and notifyall() methods defined in the Object class?

Page 25: Application Servers & Web Servers Faqs

A: These methods are detailed on the Java Software Development Kit JavaDoc page for the Object class, they are to implement threaded programming for all subclasses of Object.

Q: Why are there separate wait and sleep methods?

A: The static Thread.sleep(long) method maintains control of thread execution but delays the next action until the sleep time expires. The wait method gives up control over thread execution indefinitely so that other threads can run.

More details available to subscribers:Why are there separate wait and sleep methods?

Threads and runnable types Q: What's the difference between Thread and Runnable types?

A: A Java Thread controls the main path of execution in an application. When you invoke the Java Virtual Machine with the java command, it creates an implicit thread in which to execute the main method. The Thread class provides a mechanism for the first thread to start-up other threads to run in parallel with it.

The Runnable interface defines a type of class that can be run by a thread. The only method it requires is run, which makes the interface very easy to to fulfil by extending existing classes. A runnable class may have custom constructors and any number of other methods for configuration and manipulation.

Q: How does the run() method in Runnable work?

A: It may help to think of the run method like the main method in standard single threaded applications. The run method is a standard entry point to run or execute a class. The run method is normally only executed in the context of an independent Thread, but is a normal method in all other respects.

More details available to subscribers:How does the run() method in Runnable work?

Q: A Thread is runnable, how does that work?

A: The Thread class' run method normally invokes the run method of the Runnable type it is passed in its constructor. However, it is possible to override the thread's run method with your own.

More details available to subscribers:A Thread is runnable, how does that work?

Q: Why not override Thread to make a Runnable?

A: There is little difference in the work required to override the Thread class compared with implementing the Runnable interface, both require the body of the run() method. However, it is much simpler to make an existing class hierarchy

Page 26: Application Servers & Web Servers Faqs

runnable because any class can be adapted to implement the run method. A sub-class of Thread cannot extend any other type, so application-specific code would have to be added to it rather than inherited.

Separating the Thread class from the Runnable implementation also avoids potential synchronization problems between the thread and the run method. A separate Runnable generally gives greater flexibility in the way that runnable code is referenced and executed.

Q: What's the difference between a thread's start() and run() methods?

A: The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns.

The Thread class' run() method does nothing, so sub-classes should override the method with code to execute in the second thread. If a Thread is instantiated with a Runnable argument, the thread's run() method executes the run() method of the Runnable object in the new thread instead.

Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method, but in the latter case the code is actually executed in a new thread.

Q: Can I implement my own start() method?

A: The Thread start() method is not marked final, but should not be overridden. This method contains the code that creates a new executable thread and is very specialised. Your threaded application should either pass a Runnable type to a new Thread, or extend Thread and override the run() method.

Multi-threaded design questions Q: Do I need to use synchronized on setValue(int)?

A: It depends whether the method affects method local variables, class static or instance variables. If only method local variables are changed, the value is said to be confined by the method and is not prone to threading issues.

More details available to subscribers:Do I need to use synchronized on setValue(int) ?

Q: How do I create a Runnable with inheritance?

A: To introduce a Runnable type to an existing class hierarchy, you need to create a sub-class that declares that it implements the Runnable interface, and provide a run method to fulfil the interface. This combination of interface and inheritance means that runnable implementations can be very minor extensions of existing classes, as in the example below...

Page 27: Application Servers & Web Servers Faqs

More details available to subscribers:How do I create a Runnable with inheritance?

Q: What is the SwingUtilities.invokeLater(Runnable) method for?

A: The static utility method invokeLater(Runnable) is intended to execute a new runnable thread from a Swing application without disturbing the normal sequence of event dispatching from the Graphical User Interface (GUI). The method places the runnable object in the queue of Abstract Windowing Toolkit (AWT) events that are due to be processed and returns immediately. The runnable object's run() method is only called when it reaches the front of the queue.

The deferred effect of the invokeLater(Runnable) method ensures that any necessary updates to the user interface can occur immediately, and the runnable work will begin as soon as those high priority events are dealt with. The invoke later method might be used to start work in response to a button click that also requires a significant change to the user interface, perhaps to restrict other activities, while the runnable thread executes.

Q: What is the volatile modifier for?

A: The volatile modifier is used to identify variables whose values should not be optimized by the Java Virtual Machine, by caching the value for example. The volatile modifier is typically used for variables that may be accessed or modified by numerous independent threads and signifies that the value may change without synchronization.

Q: Which class is the wait() method defined in?

A: The wait() method is defined in the Object class, which is the ultimate superclass of all others. So the Thread class and any Runnable implementation inherit this method from Object. The wait() method is normally called on an object in a multi-threaded program to allow other threads to run. The method should should only be called by a thread that has ownership of the object's monitor, which usually means it is in a synchronized method or statement block.

More details available to subscribers:Which class is the wait() method defined in?

Thread programming jargon Q: What is a green thread?

A: A green thread refers to a mode of operation for the Java Virtual Machine (JVM) in which all code is executed in a single operating system thread. If the Java program has any concurrent threads, the JVM manages multi-threading internally rather than using other operating system threads.

There is a significant processing overhead for the JVM to keep track of thread states and swap between them, so green thread mode has been deprecated and

Page 28: Application Servers & Web Servers Faqs

removed from more recent Java implementations. Current JVM implementations make more efficient use of native operating system threads.

Multi-threaded design patterns Q: What is a working thread?

A: A working thread, more commonly known as a worker thread is the key part of a design pattern that allocates one thread to execute one task. When the task is complete, the thread may return to a thread pool for later use. In this scheme a thread may execute arbitrary tasks, which are passed in the form of a Runnable method argument, typically execute(Runnable). The runnable tasks are usually stored in a queue until a thread host is available to run them.

The worker thread design pattern is usually used to handle many concurrent tasks where it is not important which finishes first and no single task needs to be coordinated with another. The task queue controls how many threads run concurrently to improve the overall performance of the system. However, a worker thread framework requires relatively complex programming to set up, so should not be used where simpler threading techniques can achieve similar results.