30 diciembre 2009

Setting an isolation level

Setting an isolation level
Every JDBC connection to a database is in the default isolation level of the DBMS—
usually read committed or repeatable read. You can change this default in the
DBMS configuration. You may also set the transaction isolation for JDBC connec-
tions on the application side, with a Hibernate configuration option:
hibernate.connection.isolation = 4
Hibernate sets this isolation level on every JDBC connection obtained from a
connection pool before starting a transaction. The sensible values for this option
are as follows (you may also find them as constants in java.sql.Connection):
■ 1—Read uncommitted isolation
■ 2—Read committed isolation
■ 4—Repeatable read isolation
■ 8—Serializable isolation
Note that Hibernate never changes the isolation level of connections obtained
from an application server-provided database connection in a managed environ-
ment! You can change the default isolation using the configuration of your appli-
cation server. (The same is true if you use a stand-alone JTA implementation.)
As you can see, setting the isolation level is a global option that affects all con-
nections and transactions. From time to time, it’s useful to specify a more restric-
tive lock for a particular transaction. Hibernate and Java Persistence rely on
optimistic concurrency control, and both allow you to obtain additional locking
guarantees with version checking and pessimistic locking.

Transaction types




RESOURCE-LOCAL=>EntityTransaction
JTA=>UserTransaction

Hibernate exceptions

Any Hibernate operation, including flushing the persistence context, can throw a
RuntimeException. Even rolling back a transaction can throw an exception! You
want to catch this exception and log it; otherwise, the original exception that led
to the rollback is swallowed.
An optional method call in the example is setTimeout(), which takes the
number of seconds a transaction is allowed to run. However, real monitored trans-
actions aren’t available in a Java SE environment. The best Hibernate can do if
you run this code outside of an application server (that is, without a transaction
manager) is to set the number of seconds the driver will wait for a Prepared-
Statement to execute (Hibernate exclusively uses prepared statements). If the
limit is exceeded, an SQLException is thrown.

You don’t want to use this example as a template in your own application,
because you should hide the exception handling with generic infrastructure code.
You can, for example, write a single error handler for RuntimeException that
knows when and how to roll back a transaction. The same can be said about open-
ing and closing a Session. We discuss this with more realistic examples later in
the next chapter and again in chapter 16, section 16.1.3, “The Open Session in
View pattern.”
Hibernate throws typed exceptions, all subtypes of RuntimeException that help
you identify errors:
■ The most common HibernateException is a generic error. You have to
either check the exception message or find out more about the cause by
calling getCause() on the exception.
■ A JDBCException is any exception thrown by Hibernate’s internal JDBC
layer. This kind of exception is always caused by a particular SQL statement,
and you can get the offending statement with getSQL(). The internal
exception thrown by the JDBC connection (the JDBC driver, actually) is
available with getSQLException() or getCause(), and the database- and
vendor-specific error code is available with getErrorCode().
■ Hibernate includes subtypes of JDBCException and an internal converter
that tries to translate the vendor-specific error code thrown by the database
driver into something more meaningful. The built-in converter can pro-
duce JDBCConnectionException, SQLGrammarException, LockAquisition-
Exception, DataException, and ConstraintViolationException for the
most important database dialects supported by Hibernate. You can either
manipulate or enhance the dialect for your database, or plug in a SQLEx-
ceptionConverterFactory to customize this conversion.
■ Other RuntimeExceptions thrown by Hibernate should also abort a transac-
tion. You should always make sure you catch RuntimeException, no matter
what you plan to do with any fine-grained exception-handling strategy.

You now know what exceptions you should catch and when to expect them. How-
ever, one question is probably on your mind: What should you do after you’ve
caught an exception?
All exceptions thrown by Hibernate are fatal. This means you have to roll back
the database transaction and close the current Session. You aren’t allowed to con-
tinue working with a Session that threw an exception.

Usually, you also have to exit the application after you close the Session fol-
lowing an exception, although there are some exceptions (for example, Stale-
ObjectStateException) that naturally lead to a new attempt (possibly after
interacting with the application user again) in a new Session.

A history of exceptions

Exceptions and how they should be handled always
end in heated debates between Java developers. It isn’t surprising that
Hibernate has some noteworthy history as well. Until Hibernate 3.x, all
exceptions thrown by Hibernate were checked exceptions, so every Hiber-
nate API forced the developer to catch and handle exceptions. This strat-
egy was influenced by JDBC, which also throws only checked exceptions.
However, it soon became clear that this doesn’t make sense, because all
exceptions thrown by Hibernate are fatal. In many cases, the best a
developer can do in this situation is to clean up, display an error message,
and exit the application. Therefore, starting with Hibernate 3.x, all
exceptions thrown by Hibernate are subtypes of the unchecked Runtime-
Exception, which is usually handled in a single location in an application.
This also makes any Hibernate template or wrapper API obsolete.

Manning.Java.Persistence.with.Hibernate.Nov.2006.pdf

06 diciembre 2009

Have you ever found yourself frustrated with a ClassNotFoundException?

Tattletale

Have you ever found yourself frustrated with a ClassNotFoundException? Would you like to know what libraries are in your project and what they depend on? Would you like to get a full report on this stuff every time you run your ant build? If so you need to use the JBoss Tattletale project!

JBoss Tattletale is a tool that can help you get an overview of the project you are working on or a product that you depend on.

The tool will provide you with reports that can help you

  • Identify dependencies between JAR files

  • Find missing classes from the classpath

  • Spot if a class/package is located in multiple JAR files

  • Spot if the same JAR file is located in multiple locations

  • With a list of what each JAR file requires and provides

  • Verify the SerialVersionUID of a class

  • Find similar JAR files that have different version numbers

  • Find JAR files without a version number

  • Find unused JAR files

  • Identify sealed and signed JAR archives

  • Locate a class in a JAR file

  • Get the OSGi status of your project

JBoss Tattletale will recursive scan the directory pass as the argument for JAR files and then build the reports as HTML files.

JBoss Tattletale is licensed under GNU Lesser General Public License (LGPL) version 2.1 or later.

We hope that JBoss Tattletale will help you in your development tasks !

Please, visit the official JBoss Tattletale project page at http://www.jboss.org/tattletale/.

JavaBeans

Javabeans may be used just like a stateless or stateful session bean. However, they do not provide the functionality of a session bean (declarative transaction demarcation, declarative security, efficient clustered state replication, EJB 3.0 persistence, timeout methods, etc).

Seam JavaBean components may be instantiated using Component.getInstance() or
@In(create=true). They should not be directly instantiated using the new operator.

Entity beans

Entity beans are not usually used as JSF action listeners, but do often function as backing beans that provide properties to JSF components for display or form submission. In particular, it is common to use an entity as a backing bean, together with a stateless session bean action listener to implement create/update/delete type functionality.

Seam entity bean components may be instantiated using Component.getInstance(),
@In(create=true) or directly using the new operator.

Stateful session beans

Application state that does not belong in the database should usually be held by stateful session beans. Instead of sticking information about the current
conversation directly in the HttpSession, you should keep it in instance variables of a stateful session bean that is bound to the conversation context.

Stateful session beans are often used as JSF action listener, and as backing beans that provide properties to JSF components for display or form submission.

Seam stateful session bean components may be instantiated using Component.getInstance()
or @In(create=true)
. They should not be directly instantiated via JNDI lookup or the new operator.

Stateless session beans

Stateless session beans can be accessed concurrently as a new instance is used for each request. Assigning the instance to the request is the responsibility of the EJB3 container (normally instances will be allocated from a reusable pool meaning that you may find any instance variables contain data from previous uses of the bean).

Seam stateless session bean components may be instantiated using Component.getInstance() or @In(create=true). They should not be directly instantiated via JNDI lookup or the new operator.

05 diciembre 2009

El catalán es un dialecto del español

definiciones:

dialecto.

(Del lat. dialectus, y este del gr. διάλεκτος).

1. m. Ling. Sistema lingüístico considerado con relación al grupo de los varios derivados de un tronco común. El español es uno de los dialectos nacidos del latín.

2. m. Ling. Sistema lingüístico derivado de otro, normalmente con una concreta limitación geográfica, pero sin diferenciación suficiente frente a otros de origen común.

3. m. Ling. Estructura lingüística, simultánea a otra, que no alcanza la categoría social de lengua.


lengua.

(Del lat. lingua).

1. f. Órgano muscular situado en la cavidad de la boca de los vertebrados y que sirve para gustación, para deglutir y para modular los sonidos que les son propios.

2. f. Sistema de comunicación verbal y casi siempre escrito, propio de una comunidad humana.

3. f. Sistema lingüístico cuyos hablantes reconocen modelos de buena expresión. La lengua de Cervantes es oficial en 21 naciones

4. f. Sistema lingüístico considerado en su estructura.

5. f. Vocabulario y gramática propios y característicos de una época, de un escritor o de un grupo social. La lengua de Góngora La lengua gauchesca


idioma.

(Del lat. idiōma, y este del gr. ἰδίωμα, propiedad privada).

1. m. Lengua de un pueblo o nación, o común a varios.




catalán, na.

1. adj. Natural de Cataluña. U. t. c. s.

2. adj. Perteneciente o relativo a este antiguo principado, hoy comunidad autónoma de España.

3. m. Lengua romance vernácula que se habla en Cataluña y en otros dominios de la antigua Corona de Aragón.



castellano, na.

(Del lat. Castellānus).

1. adj. Natural de Castilla. U. t. c. s.

2. adj. Perteneciente o relativo a esta región de España.

3. adj. Dicho de una gallina: De cierta variedad negra muy ponedora.

4. m. Lengua española, especialmente cuando se quiere introducir una distinción respecto a otras lenguas habladas también como propias en España.

5. m. Dialecto románico nacido en Castilla la Vieja, del que tuvo su origen la lengua española.

6. m. Variedad de la lengua española hablada modernamente en Castilla la Vieja.




español, la.

(Del prov. espaignol, y este del lat. mediev. Hispaniŏlus, de Hispania, España).

1. adj. Natural de España. U. t. c. s.

2. adj. Perteneciente o relativo a este país de Europa.

3. m. Lengua común de España y de muchas naciones de América, hablada también como propia en otras partes del mundo.








a favor:











en contra:

04 diciembre 2009

hsqldb

para instalar y gestionar bases de datos hsqldb:

1.- bajar hsqldb de su web
2.- descomprimir en c:\hsqldb
3,. ejecutar
java -cp lib/hsqldb.jar org.hsqldb.Server -database.0 file:mydb -dbname.0 xdb

4.- ejecutar desde demo:
runManagerSwing.bat

5.- conectar mediante el wizard del manager (jdbc:hsqldb:hsql://localhost/xdb)
6.- generar el esquema ejecutando:
CREATE SCHEMA ROOT AUTHORIZATION dba;
SET SCHEMA ROOT;
CREATE USER root PASSWORD root ADMIN;
7.- crear las tablas como por ejemplo:
create table MESSAGES (
MESSAGE_ID bigint generated by default as identity (start with 1),
MESSAGE_TEXT varchar(255),
NEXT_MESSAGE_ID bigint,
primary key (MESSAGE_ID)
);

alter table MESSAGES
add constraint FK131AF14C3CD7F3EA
foreign key (NEXT_MESSAGE_ID)
references MESSAGES;
8.- Desde el HSQL Manager seleccionamos Schemas -> HERMES

03 diciembre 2009

hibernate3:hbm2ddl

hibernate3:hbm2ddl

  1. la solución más fácil para lo del esquema en hsqldb es crear el esquema a mano desde HSQLDB database manager
  2. otra solución sencilla puede ser definir el esquema en orm.xml y eliminarlo de las entities (lo que ponga en el orm.xml sobreescribe lo que ponga en anotaciones)
  3. la solución óptima parece ser eliminar @Table de las entities y declarar el default_schema en persistence.xml, en hibernate.properties y/o en hibernate.cfg.xml
  4. <?xml version="1.0" encoding="UTF-8"?>
    <entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd"
    version="1.0">

    <persistence-unit-metadata>
    <persistence-unit-defaults>
    <schema>hermes</schema>
    </persistence-unit-defaults>
    </persistence-unit-metadata>

    </entity-mappings>

  5. la solución más elegante, aunque mucho más complicada, es aplicar los parches a:
  • src/org/hibernate/dialect/Dialect.java
  • src/org/hibernate/dialect/HSQLDialect.java
  • src/org/hibernate/cfg/Configuration.java