Beginning Hibernate Third Edition Joseph B. Ottinger Download
Beginning Hibernate Third Edition Joseph B. Ottinger Download
Ottinger
- PDF Download (2025)
https://ebookultra.com/download/beginning-hibernate-third-
edition-joseph-b-ottinger/
https://ebookultra.com/download/java-persistence-with-hibernate-
second-edition-of-hibernate-in-action-christian-bauer/
https://ebookultra.com/download/elements-of-music-third-edition-
joseph-n-straus/
https://ebookultra.com/download/hibernate-in-action-1st-edition-
christian-bauer/
https://ebookultra.com/download/beginning-asp-net-2-0-ajax-1st-
edition-wallace-b-mcclure/
Hibernate Search in Action 1st Edition Emmanuel Bernard
https://ebookultra.com/download/hibernate-search-in-action-1st-
edition-emmanuel-bernard/
https://ebookultra.com/download/pro-hibernate-and-mongodb-1st-edition-
anghel-leonard-auth/
https://ebookultra.com/download/excel-for-chemists-a-comprehensive-
guide-third-edition-e-joseph-billoauth/
https://ebookultra.com/download/musculoskeletal-imaging-the-
requisites-third-edition-b-j-manaster-md-phd/
https://ebookultra.com/download/adaptive-health-management-
information-systems-concepts-cases-and-practical-applications-third-
edition-joseph-tan/
Beginning Hibernate Third Edition Joseph B. Ottinger
Digital Instant Download
Author(s): Joseph B. Ottinger, Dave Minter, Jeff Linwood (auth.)
ISBN(s): 9781430265184, 1430265183
Edition: 3
File Details: PDF, 2.28 MB
Year: 2014
Language: english
For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.
Contents at a Glance
Index���������������������������������������������������������������������������������������������������������������������������������205
v
Introduction
Hibernate is an amazing piece of software. With a little experience and the power of annotations, you can build a
complex, database-backed system with disturbing ease. Once you have built a system using Hibernate, you will never
want to go back to the traditional approaches.
While Hibernate is incredibly powerful, it presents a steep learning curve when you first encounter it—steep
learning curves are actually a good thing because they impart profound insight once you have scaled them. Yet
gaining that insight takes some perseverance and assistance.
Our aim in this book is to help you scale that learning curve by presenting you with the minimal requirements
of a discrete Hibernate application, explaining the basis of those requirements, and walking you through an example
application that is built using them. We then provide additional material to be digested once the fundamentals are
firmly understood. Throughout, we provide examples rather than relying on pure discourse. We hope that you will
continue to find this book useful as a reference text long after you have become an expert on the subject.
xxi
■ Introduction
Chapter 3 presents an example application, walking you through the complete process of creating and running
the application. It then looks at a slightly more complex example and introduces the notion of generating the database
schema directly from Hibernate annotations.
Chapter 4 covers the Hibernate lifecycle in depth. It discusses the lifecycle in the context of the methods available
on the core interfaces. It also introduces key terminology and discusses the need for cascading and lazy loading.
Chapter 5 explains why mapping information must be retained by Hibernate and demonstrates the various types
of associations that can be represented by a relational database. It briefly discusses the other information that can be
maintained within a Hibernate mapping.
Chapter 6 explains how Hibernate lets you use the annotations to represent mapping information. It provides
detailed examples for the most important annotations, and discusses the distinctions between the standard JPA 2
annotations and the proprietary Hibernate ones.
Chapter 7 explains some of the uses of the Java Persistence API (as opposed to the Hibernate-native API), as well
as the lifecycle and validation of persisted objects.
Chapter 8 revisits the Hibernate Session object in detail, explaining the various methods that it provides.
The chapter also discusses the use of transactions, locking, and caching, as well as how to use Hibernate in a
multithreaded environment.
Chapter 9 discusses how Hibernate can be used to make sophisticated queries against the underlying relational
database using the built-in Hibernate Query Language (HQL).
Chapter 10 introduces the Criteria API, which is a programmatic analog of the query language discussed
in Chapter 9.
Chapter 11 discusses how the Filter API can be used to restrict the results of the queries introduced in
Chapters 9 and 10.
Chapter 12 introduces Hibernate OGM, which maps objects to non-relational data stores like Infinispan and
Mongodb, among others. It shows some of the uses of Hibernate Search to provide a common search facility for
NoSQL, as well as offering full text query support.
Appendix presents a large number of peripheral features that do not warrant more extensive coverage in a
beginner-level text. The appendix discusses the basics, with examples, of the support for versioning and optimistic
locking, and some of the obscure limitations of Hibernate and various ways that these can be worked around. It also
discusses the use of events and interceptors.
xxii
Chapter 1
Most significant development projects involve a relational database.1 The mainstay of most commercial applications
is the large-scale storage of ordered information, such as catalogs, customer lists, contract details, published text, and
architectural designs.
With the advent of the World Wide Web, the demand for databases has increased. Though they may not know it,
the customers of online bookshops and newspapers are using databases. Somewhere in the guts of the application a
database is being queried and a response is offered.
Hibernate 4 is a library that simplifies the use of relational databases in Java applications by presenting relational
data as simple Java objects, accessed through a session manager, therefore earning the description of being an
“Object/Relational Mapper,” or ORM. It provides two kinds of programmatic interfaces: a “native Hibernate” interface
and the Java EE-standard Java Persistence API.
There are solutions for which an ORM-like Hibernate is appropriate, and some for which the traditional approach
of direct access via the Java Database Connectivity (JDBC) API is appropriate. We think that Hibernate represents a
good first choice, as it does not preclude the simultaneous use of alternative approaches, even though some care must
be taken if data is modified from two different APIs.
To illustrate some of Hibernate’s strengths, in this chapter we take a look at a brief example using Hibernate and
contrast this with the traditional JDBC approach.
There would be no nasty surprises, no additional work to correlate the class with tables in the database, and no
performance problems.
1
A relational database is a collection of sets of data items, each of which is formally described and organized. Rules can be put into
place for the data such that it can be validated, and indexes can be created such that the data can be queried and updated quickly
and safely.
2
Well, perhaps an ideal world in which an ORM is used for data access. But in this book this can be assumed to be the case.
1
Chapter 1 ■ An Introduction to Hibernate 4.2
Hibernate comes remarkably close to this, at least when compared with the alternatives,but there are
configuration files to create and subtle performance and synchronization issues to consider. Hibernate does, however,
achieve its fundamental aim: it allows you to store POJOs in the database. Figure 1-1 shows how Hibernate fits into
your application between the client code and the database.
The common term for the direct persistence of traditional Java objects is object/relational mapping—that is,
mapping the objects in Java directly to the relational entities in a database.
POJOs can be any Java object at all. Hibernate allows you to persist POJOs with very few constraints. Listing 1-2
is an example of a simple POJO that might be used to represent a message. (We’ll be modifying this class as we walk
through some example code.)
2
Chapter 1 ■ An Introduction to Hibernate 4.2
The sole condescension to Hibernate here is the provision of a default constructor. Hibernate demands that all
POJOs to be stored should provide a default constructor;3 but even that situation can be worked around when
third-party classes fail to satisfy this limited requirement (through the use of an Interceptor mechanism in the
Hibernate configuration; we will demonstrate this in Appendix A).
rs = ps.executeQuery();
while (rs.next()) {
Message message = new Message();
message.setId(rs.getLong(1));
message.setText(rs.getString(2));
list.add(message);
}
if (list.size() > 1) {
Assert.fail("Message configuration in error; table should contain only one."
+" Set ddl to drop-create.");
}
if (list.size() == 0) {
Assert.fail("Read of initial message failed; check saveMessage() for errors."
+" How did this test run?");
}
for (Message m : list) {
System.out.println(m);
}
// eagerly free resources
rs.close();
ps.close();
connection.close();
3
See http://docs.jboss.org/hibernate/orm/4.2/quickstart/en-US/html/ch02.html#hibernate-gsg-
tutorial-basic-entity for more details. Short form: Hibernate uses reflection to construct an object before data population. The
shortest (and quickest) path to doing that is with a no-argument constructor.
3
Chapter 1 ■ An Introduction to Hibernate 4.2
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
try {
if (rs != null && !rs.isClosed()) {
rs.close();
}
} catch (SQLException ignored) {
}
try {
if (ps != null && !ps.isClosed()) {
ps.close();
}
} catch (SQLException ignored) {
}
try {
if (connection != null && !connection.isClosed()) {
connection.close();
}
} catch (SQLException ignored) {
}
}
}
Could some of this be trimmed down? Of course. The code to close the resources is very long (and since
applications that use JDBC would do this sort of thing a lot, this code begs for refactoring into reusable methods).
Using a connection pool instead of DriverManager would also help with this because most, if not all, connection pools
automatically release resources on garbage collection. (In this case, though, eager release is still valuable.) You could
also use classes like Spring’s JDBCTemplate to handle error conditions and connection management.
However, in the end the problem remains: there’s a lot of resource management involved, primarily around
handling error and termination conditions, and the code itself is very brittle. If we added a field to the database,
we would have to find every SQL statement that might need to access that field, and we would modify the code to
accommodate it.
We also run into the issue of types with this code. This is a very simple object: it stores a simple numeric identifier
with a simple string. However, if we wanted to store a geolocation, we’d have to break the location into its multiple
properties (longitude and latitude, for example), and store each separately, which means your object model no longer
cleanly matches your database.
All of this makes using the database directly look more and more flawed, and that’s not before factoring in other
issues around object persistence and retrieval.
4
Chapter 1 ■ An Introduction to Hibernate 4.2
Hibernate handles the mapping of the object to the database table, including constructing the database schema
for you if you so configure it; it doesn’t require one table per object type; you can easily map one object to multiple
tables. And Hibernate also handles relationships for you; for example, if you added a list of addresses to a Person
object, you could easily have the addresses stored in a secondary table, constructed and managed by Hibernate.
In addition to mapping the object to the database table, Hibernate can handle mappings of new types to the
database. The geolocation can be specified as its own table, can be normalized, or can have a custom serialization
mechanism such that you can store it in whatever native form you need.
Hibernate’s startup takes a little bit longer than direct JDBC code, to be sure. However, system initialization
time is usually not a meaningful metric. Most applications have long runtimes and the percentage of time spent
in Hibernate initialization is irrelevant to the actual performance of the application; Hibernate’s advantages in
maintenance and object management more than make up for any time the application spends in configuration.
As usual, the right way to consider performance is through testing and analysis of an actual application, as opposed
to spitballing anecdotal evidence.
Any Java object capable of being persisted to a database is a candidate for Hibernate persistence. Therefore,
Hibernate is a natural replacement for ad hoc solutions (like our JDBC example), or as the persistence engine for
an application that has not yet had database persistence incorporated into it. Furthermore, by choosing Hibernate
persistence, you are not tying yourself to any particular design decisions for the business objects in your
application—including which database the application uses for persistence, which is a configurable aspect.
@BeforeClass
public void setup() {
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistryBuilder srBuilder = new ServiceRegistryBuilder();
srBuilder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = srBuilder.buildServiceRegistry();
factory = configuration.buildSessionFactory(serviceRegistry);
}
@Test(dependsOnMethods = "saveMessage")
public void readMessage() {
Session session = factory.openSession();
@SuppressWarnings("unchecked")
List<Message> list = (List<Message>) session.createQuery("from Message").list();
if (list.size() > 1) {
Assert.fail("Message configuration in error; table should contain only one."
+" Set ddl to create-drop.");
}
if (list.size() == 0) {
Assert.fail("Read of initial message failed; check saveMessage() for errors."
+" How did this test run?");
}
5
Chapter 1 ■ An Introduction to Hibernate 4.2
Note that the manual coding to populate the Message object has not been eradicated; rather, it has been moved
into an external configuration file that isolates this implementation detail from the main logic.
Also note that we’re using the Hibernate Query Language (HQL) to locate the Message. HQL is very powerful, and
this is a poor usage of it; we’ll dig into HQL quite a bit as we progress.
Some of the additional code in the Hibernate example given in Listing 1-4 actually provides functionality
(particularly transactionality and caching) beyond that of the JDBC example.
Mappings
As we have intimated, Hibernate needs something to tell it which tables relate to which objects. In Hibernate
parlance, this is called a mapping. Mappings can be provided either through Java annotations or through an XML
mapping file. In this book, we will focus on using annotations, as we can mark up the POJO Java classes directly.
Using annotations gives you a clear picture of the structure at the code level, which seems to be preferred by people
writing code.4 Hibernate also takes a configuration-by-exception approach for annotations: if we are satisfied with
the default values that Hibernate provides for us, we do not need to explicitly provide them as annotations. For
instance, Hibernate uses the name of the POJO class as the default value of the database table to which the object is
mapped. In our example, if we are satisfied with using a database table named Message, we do not need to define it
in the source code.
In fact, if our only access is through Hibernate, we don’t really even need to know what the table name is; as our
example shows, we query based on object type and not the table name. Hibernate automatically constructs the query
such that the correct table name is used, even if we were to change the table name to “Messages,” for example.
Listing 1-5 shows the Message POJO with annotations for mapping the Java object into the database. It adds
an identifier and a toString( ) method to our original POJO; we’d want the ID in any event, but the toString( ) adds
convenience as we use the class. (We’ll eventually want to add an equals( ) and hashCode( ) as well.)
@Entity
public class Message {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
@Column(nullable = false)
String text;
4
Go figure; who knew coders like for things to be code? (Besides coders, I mean.)
6
Chapter 1 ■ An Introduction to Hibernate 4.2
public Message() {
}
@Override
public String toString() {
return "Message{" +
"id=" + getId() +
", text='" + getText() + '\'' +
'}';
}
}
Persisting an Object
In the interest of completeness, here’s the method used to write a Message into the database with Hibernate. (The
JDBC version of this code is present in the downloadable examples, but adds nothing to the knowledge of how to use
Hibernate.)
Summary
In this chapter, we have considered the problems and requirements that have driven the development of Hibernate.
We have looked at some of the details of a trivial example application written with and without the aid of Hibernate.
We have glossed over some of the implementation details, but we will discuss these in depth in Chapter 3.
In the next chapter, we will look at the architecture of Hibernate and how it is integrated into your applications.
7
Chapter 2
Integrating Hibernate into a Java application is easy. The designers of Hibernate avoided some of the more common
pitfalls and problems with the existing Java persistence solutions, and created a clean but powerful architecture.
In practice, this means that you do not have to run Hibernate inside any particular Java EE container or framework.
Hibernate only requires Java 6 or later.1
At first, adding Hibernate to your Java project looks intimidating: the distribution includes a large set of libraries.
To get your first Hibernate application to work, you have to set up the database references and the Hibernate
configuration, which might include mapping your objects to the database. You also have to create your POJOs,
including any annotation-based mapping. After you have done all of that, you need to write the logic in your
application that uses Hibernate to actually accomplish something! But once you learn how to integrate Hibernate with
your application, the basics apply for any project that uses Hibernate.
One of the key features of Hibernate’s design is the principle of least intrusiveness: the Hibernate developers did
not want Hibernate to intrude into your application more than was necessary. This led to several of the architectural
decisions made for Hibernate. In Chapter 1, you saw how Hibernate can be applied to solve persistence problems
using conventional Java objects. In this chapter, we explain some of the configuration details needed to support
this behavior.
1
The runtime requirement of at least Java 6 was confirmed by Steve Ebersole, lead of the Hibernate project. He also specified that
JDK 1.7 was required in order to build Hibernate from source.
9
Chapter 2 ■ Integrating and Configuring Hibernate
6. Create a Hibernate XML configuration file that points to your database and your mapped
classes (covered in this chapter).
7. In your Java application, create a Hibernate Configuration object that references your
XML configuration file (covered in this chapter).
8. Also in your Java application, build a Hibernate SessionFactory object from the
Configuration object (covered in this chapter).
9. Retrieve the Hibernate Session objects from the SessionFactory, and write your data
access logic for your application (create, retrieve, update, and delete).
Don’t worry if you don’t understand every term or concept mentioned in this list. After reading this chapter,
and then following the example in the next chapter, you will know what these terms mean and how they fit together.
Deploying Hibernate
There are two sets of components necessary for integration of Hibernate into your application: a database driver and
the Hibernate libraries themselves.
The example code for this book uses HSQLDB as a small, embeddable database; this can be found at
http://hsqldb.org/. This is not to indicate that other databases are of less value than HSQLDB, but it is simply
an expedient choice; HSQLDB’s sort-of sibling project H2 is also workable, as is Derby; if you have a MySQL or
PostgreSQL data server handy, those work as well.
If you’re using the Hibernate binary download (from a “release bundle,” via http://www.hibernate.org/downloads),
all of the jars contained in the lib/required directory are mandatory in order to use Hibernate.
10
Chapter 2 ■ Integrating and Configuring Hibernate
Perhaps an easier way to integrate Hibernate is through the use of a build tool, like SBT
(http://www.scala-sbt.org/), Gradle (http://www.gradle.org/, used by the Hibernate project itself ), or Maven
(http://maven.apache.org/), the latter which is arguably the most popular of the build tools, if not the best.2
All of these build tools are able to bundle dependencies into a deliverable artifact. They’re also able to include
dependencies transitively, which means that projects that depend on a given subproject also inherit that subproject’s
dependencies.
We’ll target Maven as a build environment for the rest of the book; users of other build tools are generally able to
migrate from Maven fairly easily, and we’ll make sure to keep developers who don’t use build tools in mind as well.
Installing Maven
There are many ways to install Maven. This is a cursory overview; different operating systems (and different system
configurations) can affect the installation procedure, so when you are in doubt, you can refer to http://maven.
apache.org/download.cgi#Installation for the actual documentation.
To save you some time, however, you can download Maven from http://maven.apache.org/download.cgi/; you
should get the most recent version. UNIX users (including Linux and MacOS users) should download the file ending
in tar.gz; Windows users should download the zip file.
In UNIX, untar the file into a directory of your choice; an example of the command that might be run is:
This will create ~/work/apache-maven-3.0.5/, and the mvn executable will be in ~/work/apache-maven-3.0.5/bin;
add this to your command path.
For Windows, open the archive and extract it into a known location (for example, C:\tools\). Add the location of
mvn.bat (in this example, C:\tools\apache-maven-3.0.5\bin) to your path via the System Properties dialog, and you
should be able to run Maven with “mvn” in the command prompt.
Maven uses a project object model, typically written in XML, called “pom.xml”. This file describes the project’s
name and versions and builds configurations (if any), as well as any subprojects and any project dependencies. When
Maven is run, it will automatically download any resources it needs in order to complete the build as specified, and
then it will compile the project source code; if the project includes tests, it will run the tests and complete the build if
(and only if ) no test failures occur.
This book uses a parent project that contains global dependencies for the book, and subprojects corresponding
to the chapters; much of the operating code is written as a set of tests in the subprojects. Chapter 1, for example,
used two methods to write data to and read data from a database; those tests were written as TestNG test classes:
chapter01.hibernate.PersistenceTest and chapter01.jdbc.PersistenceTest.
The parent project’s configuration file, after Chapter 1 was written, looked like Listing 2-1.
2
Arguments about “which build tool is best” are a lot like arguments about relative merits of IDEA, Emacs, Netbeans, Eclipse, and
others. Everyone has an opinion, and that opinion is perfectly valid for the one who holds it; however, Maven is generally agreed
upon not to be the “best build tool,” much like Eclipse is not the “best editor.” They’re popular. They’re common. That’s about it.
11
Chapter 2 ■ Integrating and Configuring Hibernate
<artifactId>hibernate-parent</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>chapter01</module>
</modules>
<name>hibernate-parent</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>[6.0.12,)</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>[4.2.6,4.2.9]</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>[2.2.9,)</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<showDeprecation>true</showDeprecation>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
</plugins>
</build>
</project>
This specifies a number of things about the project (such as the Java version), and includes three dependencies:
Hibernate itself, the HSQLDB database, and TestNG, the last which is limited to the testing phase (as the “scope”
node instructs).
12
Chapter 2 ■ Integrating and Configuring Hibernate
The child projects—in this listing, this is only chapter01—will receive this configuration and its set of
dependencies automatically, which means we don’t have to repeat ourselves very often.
To build and run this project after installing Maven, you simply have to go to the directory that contains pom.xml,
and execute “mvn package”—which will, as stated, download all the required dependencies, build them, and then test
the projects in order.
Maven projects have a specific folder layout, although it’s configurable; by default, the Java compiler compiles all
code found in src/main/java, and the resulting class files are included with src/main/resources in the deliverable
artifact. The src/test/java directory contains tests, which are then compiled and run (with src/test/resources
and the deliverable artifact in the classpath as well).
Wow, that’s a lot of non-Hibernate discussion–and all of it can be found (and subverted) on the websites for each
given build environment. In general, you can (and should) use what you like; this book uses Maven because of how
common it is, not because it’s the One True Build Tool.
Let’s look at the actual code we’ve been running so far and explain it all. That will give you a basis for future
discussion, even if you’re not going to use it much beyond this chapter.
We’ve already mentioned the top-level pom.xml file; we’re going to start in the chapter02 directory (which is
a clone of the chapter01 directory, except with “chapter02” instead of “chapter01”). Our project description file
(our pom.xml) is very simple, specifying only the parent project and the current project’s name (see Listing 2-2).
<artifactId>chapter02</artifactId>
</project>
Our Message.java is held in src/main/java/chapter02/Message.java. This is the same POJO as in Listing 1-5,
except that it’s in a different package (chapter02.hibernate instead of chapter01.hibernate). Since everything else
is the same, we won’t list it here.
Our actual running code is in the src/test directory and consists of two relevant files3: src/test/java/
chapter02/hibernate/PersistenceTest.java and src/test/resources/hibernate.cfg.xml.
We’ve already seen the test methods from PersistenceTest.java, but let’s take a look at the entire Listing 2-3 so
you understand everything in it.
3
There are other classes in the tree, but we no longer care about JDBC in this chapter; they’re here because you were promised
that chapter02’s tree was the same as chapter01’s. All of the JDBC stuff is going to be ignored.
13
Chapter 2 ■ Integrating and Configuring Hibernate
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.testng.Assert;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import java.util.List;
@BeforeSuite
public void setup() {
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistryBuilder srBuilder = new ServiceRegistryBuilder();
srBuilder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = srBuilder.buildServiceRegistry();
factory = configuration.buildSessionFactory(serviceRegistry);
}
@Test
public void saveMessage() {
Message message = new Message("Hello, world");
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
session.persist(message);
tx.commit();
session.close();
}
@Test(dependsOnMethods = "saveMessage")
public void readMessage() {
Session session = factory.openSession();
@SuppressWarnings("unchecked")
List<Message> list = (List<Message>) session.createQuery(
"from Message").list();
if (list.size() > 1) {
Assert.fail("Message configuration in error; "
+ "table should contain only one."
+ " Set ddl to drop-create.");
}
14
Chapter 2 ■ Integrating and Configuring Hibernate
if (list.size() == 0) {
Assert.fail("Read of initial message failed; "
+ "check saveMessage() for errors."
+ " How did this test run?");
}
for (Message m : list) {
System.out.println(m);
}
session.close();
}
}
To begin, note that we’re using TestNG to run the tests, which in this case affects our class in a few simple ways.
First, the actual test methods are annotated with @Test; we indicate a dependency between tests with a setting
for readMessage(). If saveMessage() were to fail, readMessage() would not be executed, as its execution depends on
a successful saveMessage().
Second, there’s a mehod annotated with @BeforeSuite method, which is executed before any of the tests are
attempted. This gives us a chance to do system initialization. This is where we’re setting up Hibernate for usable
state–in the JDBC code, we use this same mechanism to load the JDBC driver and create our database schema.4
Third, we indicate that failure through the use of Assert.fail(), which should be easy to understand. An
exception also indicates a failure, unless we tell TestNG that we expect an exception to be thrown (and we can also tell
TestNG what specific type of exceptions allow the test to pass).
You’re likely to use this construct often because it’s easy to integrate into your project build lifecycle (as Maven
runs the available tests as part of the build). Also, it gives you a clear order of execution, and also provides an easy way
to see what works and what doesn’t work. You should feel free to write tests to validate your own understanding of
what is being described.
Next, note how the test is constructed.
The test shows the canonically correct way to use Hibernate’s native API5: first, construct a SessionFactory,
which is the entry point to the Hibernate API (much as EntityManager is the entry point for the Java Persistence
Architecture); then use the SessionFactory to retrieve short-lived Session objects through which updates, or reads,
are performed.
The actual tests mirror the JDBC code fairly well6 (or vice versa); in both, we acquire a resource through which
we “talk to” the database, then we perform an action, then we commit our changes (if any) and clean up. (There are
definitely details being skipped; this is the ten-thousand-foot view of the mechanisms in place.)
The last piece of the puzzle is the actual configuration file itself, which is in src/test/resource/hibernate.cfg.xml.
See Listing 2-4.
4
Hmm, we promised that we weren’t going to mention the JDBC code any more. Whoops.
5
Hibernate implements the Java Persistence Architecture as an alternative API. It’s a little more generic than the native API,
and is configured slightly differently, even though most of the concepts are identical.
6
Darn it, we keep on coming across that JDBC code that isn’t supposed to be mentioned.
15
Chapter 2 ■ Integrating and Configuring Hibernate
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">
org.hsqldb.jdbc.JDBCDriver
</property>
<property name="connection.url">
jdbc:hsqldb:db2;shutdown=true
</property>
<property name="connection.username">sa</property>
<property name="connection.password"/>
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create-drop</property>
<mapping class="chapter02.hibernate.Message"/>
</session-factory>
</hibernate-configuration>
This file might serve as a boilerplate for every Hibernate configuration. In it, we specify the JDBC driver class;
the JDBC URL, user name, and password used to access the database; a dialect (which allows Hibernate to correctly
produce SQL for each given database); some configuration, such as whether to dump the generated SQL to the
console; and what to do for the schema. Lastly, it specifies the classes that should be managed—in this case, only our
Message class.
There are a lot of things we can control from this file; we can even use it to specify the mapping of our objects to
the database (i.e., ignoring the annotations we’ve been using so far). You’ll see a little more of how to do this in later
chapters of this book; it helps quite a bit in mapping existing database schemata7 to object models.
Most coders will (and should) prefer the annotation-based mappings.
Connection Pooling
As you’ve seen, Hibernate uses JDBC connections in order to interact with a database. Creating these connections is
expensive—probably the most expensive single operation Hibernate will execute in a typical-use case.
Since JDBC connection management is so expensive, you can pool the connections, which can open connections
ahead of time (and close them only when needed, as opposed to “when they’re no longer used”).
Thankfully, Hibernate is designed to use a connection pool by default, an internal implementation. However,
Hibernate’s built-in connection pooling isn’t designed for production use. In production, you would use an external
connection pool by using either a database connection provided by JNDI (the Java Naming and Directory Interface) or
an external connection pool configured via parameters and classpath.
7
“Schemata” is the plural of “schema.” See http://www.merriam-webster.com/dictionary/schema.
16
Other documents randomly have
different content
nyomoruságát minél szinesebben illusztrálhassák. De ezt a
nyomoruságot semmi se dokumentálja olyan ékesszólón, mint a
tulajdon példájuk. Szegény ördögök! Mennyire megvetették a
pennarágókat, az ifjui álmok, a reménységek idején! És amióta
várakozásaikban megcsalódtak, amióta rájöttek, hogy Mars csak
tisztességet ad, ellenben Apolló jóval több márkát, sőt tallérokat is:
mily buzgalommal forgatják az irótollat, mily lázas gyorsasággal
készitik el élményeik leirását, mily tömegesen jelentkeznek az irói
tantième-ekért! A pénzért, ami oly iszonyuan kell, még a
pennarágásra is elszánják magukat, elmondják mindazt, amit
tudnak, elbeszélik felebbvalóik és pajtásaik, továbbá ezek hölgyeinek
összes gyöngéit, elmondanák talán a tulajdon bajaikat is.
Ez a nagy készség, ez a sok igyekezet nem hiábavaló; fáradságuk
megleli bőséges anyagi jutalmát. De honnan hát ez az eredmény,
mely könyveik tartalma után meglepő? Mi magyarázza meg munkáik
piaczi sikerét, a tömegnek a csekély érdekességü leleplezésekkel
szemben tanusitott szertelen érdeklődését? A feleletet ne keressük
Bilséék irói kvalitásaiban és abban, hogy munkáik mi ujat
tartalmaznak; a feleletet csak a tömeg gondolkozásában találhatjuk
meg. És itt egy ellenmondásra lelünk, amely azonban már nem
ismeretlen.
Sikereik alapja az, hogy mindannyian olyan témáról szólanak,
amelynek a kicsinyességei is biztosan számithatnak a nagyközönség
érdeklődésére, s a kicsinyességei sokkal inkább, mint a komolyabb
részei. A katonai élet intimitásai épp ugy vonzzák a tömeg
képzeletét, mint a kulisszák világának apró rejtelmei. A sokaság
szemében a szinésznő mellett a katonatiszt a mai társasélet
legérdekesebb tipusa. A tisztikar, minden más osztályon kivül és
felett, első osztályt alkot, s a respektusból, melyet joggal igényel,
mindenki, aki hozzá tartozik, kiveszi a maga részét. Minél inkább
elmosódik a különbség polgár és polgár, az egyik vagy a másik
foglalkozás között, amelyek rangban ma már nem igen differálnak, s
aszerint adnak tekintélyt, amily arányban sikert és vagyont: a
katonatiszti egyenruha, amely még az egyetlen nevezetesebb
disztinkcziót állapitja meg a nem rangbeliek között, annál nagyobb
hatással van a tömegre. A portepé viselői a társaséletben bizonyos
arisztokrácziát alkotnak; s ugyanaz a sokaság, mely egyre több és
több vonalon követeli az egyenlőséget, minél radikálisabb elveknek
hódol, annál inkább tisztel mindent, ami arisztokratikus. Bepillantani
a katonatisztek életének intimitásaiba, ez ma majdnem annyit jelent:
mint bejuthatni egy pillanatra a rangbeliek körébe, ahová mindenki
törekszik, annál nagyobb buzgalommal és annál nagyobb tömeg
társaságában, minél sürübben emlegeti az egész világ a
demokratikus elvek már kissé hervadt szóvirágait.
Erre a naiv érdeklődésre Bilséék nyugodtan számithattak. És
könyveik nemcsak a sövény mögül bámészkodókat elégitették ki,
hanem azokat is, akik a katona-regények tartalmából, de különösen
abból, hogy a tiszt urak ilyen könyveket adnak ki, kárörömmel látták,
hogy a hatalmas német hadsereg egyes köreiben s itt-ott más
hadseregek alantasabb rétegeiben is, eddigelé hallatlan, minden
fegyelmet megcsufoló, éppen nem katonai szellem kezd lábrakapni.
Bilséék regényei kétségtelenné teszik, hogy a zugolódó
elégedetlenség, a forradalmi szellem első megnyilvánulása már a
hadseregek egyes rétegeibe is befészkelte magát, s azt sejtetik,
hogy a hadseregek egyre szaporodó és növekedő házi mizériái
lassanként ki fogják kezdeni ezt a tiszteletreméltó intézményt. És a
polgári társadalomnak talán ugyanazok az elemei, amelyek
tisztelettel és irigységgel teli érdeklődéssel leskelődnek az
arisztokratikus helyzetnek örvendő tisztek intimitásaira, még akkor
is, mikor ezek minden katonai kötelességet megcsufolnak:
ugyanezek az elemek ujjonganak, mikor azt hiszik, hogy a szükséges
és minden tiszteletre méltó intézmény dekompozicziójának a tüneteit
látják. A tömeg ma különb egyesekből verődik össze, de
naivitásában, ösztöneiben, indulataiban ma is ugyanolyan, mint
Shakspere-nek a „nép“-e. A tömeg örök gyermek; vásott és korlátolt.
II.
A sok ujonnan keletkezett katona-história közül Baudissin Farkas
gróf, irói nevén Freiherr von Schlicht Erstklassige Menschen czimü,
ugynevezett regénye érdemli meg figyelmünket. Ez se ajánlható
azoknak, akik nem vitairatot, hanem tendencziák nélkül való
szépirodalmi munkát akarnak olvasni; igazi regénynek a legjobb
akarattal se mondható. Tessék-lássék meséje mindössze annyi, hogy
egy polgári származásu tiszt, akit olyan gárdaezredbe helyeztek át,
ahol csupa előkelő származásu tiszt szolgál, uj bajtársai körében a
megalázások egész kálváriáját járja végig, s végre is kénytelen tiszti
rangjáról lemondani, egyesegyedül a polgári származása miatt,
ennekutána pedig feleségül vesz egy katona-családból származó,
előkelő, de szegény leányt, akivel a gárdaezrednél tartózkodása
idején ismerkedett meg. Ennyi mesével a legszerényebb és
legtürelmesebb regényolvasó se elégszik meg, s ezt a mesét
hasonlóan keveset mondó epizódok fujják fel hosszu elbeszéléssé.
De mélyebben jellemzett s elevenné tett alakok sincsenek e
könyvben; a szerző a szereplők lelkét nem világitja meg, csak a
társaságban való viselkedésüket irja le szinesebben és adatokat
közöl róluk, rábizván az olvasóra, mint a kávéházi beszélgető rábizza
hallgatójára, hogy ezekből az adatokból maga alkosson képet
magának a legtöbbször emlegetett figurák lelki világáról. De a
sovány mesén, a szóra se érdemes epizódokon s a nagyon
fölületesen jellemzett alakokon kivül van ebben a könyvben valami,
ami, ha a czélzatosságokkal nem törődő regényolvasót nem is elégiti
ki, megkapja azok figyelmét, akiket ennek az ugynevezett regénynek
a tárgya, milieuje s gondolatköre még akkor is érdekel, ha ezekről
nem valamely elsőrangu irómüvész szól, hanem csak egy intelligens
megfigyelő, aki sokat foglalkozott a szóbanforgó tárgygyal, ügyesen
irja le a részleteiben kevésbbé ismert milieut, s helyes itélettel
ismerteti ama kihatásainál fogva általános érdekességü gondolatkört.
A szerző ugyanis érdekes képeket ad a német tisztek életmódjáról, a
viselkedésükben megnyilatkozó gondolkozásról és jellemvonásokról,
s a fejtegetésekbe, melyekkel e képeket kiséri, beleszövi azt a
kritikát, amelyet a hagyományos katonai szellem ellen izgató, s a
hadsereg reformálását követelő, legujabb keletü „irodalom“ ma már
sok könyvben hangoztat.
Ha egy kissé szemügyre veszszük ezeket a képeket, sorra
megismerkedünk a hadsereg mai szervezetét vádoló összes
panaszokkal, és megismerjük egyszersmind minden részletükben
azokat a viszonyokat is, amelyek a nem mindig jóhiszemü Bilse-
iskola feljajdulásaira okot vagy ürügyet szolgáltattak.
A Baudissin gróf könyvében szereplő gárdaezred tisztikarát
ünnepen találjuk. Harmincz és egynéhányadik évfordulója van a
gravelottei csatának, amelyen ez a gárdaezred igen kitüntette
magát, mert legénységének egy harmada, tisztikarának pedig a fele
ott maradt a csatatéren. Az ilyen évfordulókon az elesettek óriási
koszorut kapnak, az élők pedig, akik a csatában nem vettek részt,
fényes lakomát, pezsgővel. Az emlékezetes nap megünneplését ez
alkalommal összekötik az ezred uj kaszinó-épületének a
felavatásával. Vendégeik is vannak: az ulánustisztek, akikkel
iszonyuan szeretnének minél vastagabb barátságba keveredni. Mert
mégis csak a lovasság a hadseregnek a crême-je s az ulánusok
olyanforma felsőbbséggel tekintenek le rájuk, mint aminővel ők
tekintenek a közönséges gyalogos tisztekre. Az ulánusok alkotják a
hadsereg „legfeudálisabb“ elemét; tisztjeik között egy sincs, aki nem
előkelő származásu. Az ünneplőknek is az a főbüszkesége, hogy
köztük nincsen polgár-ivadék; s éppen ez ad nekik jogczimet arra,
hogy az ulánusok barátságát kereshessék. A lakomán csak
egyetlenegy czivil van jelen: az épitész, aki a kaszinó-épület tervét
ingyen készitette, a gárdaezredhez való ragaszkodásból, mert annak
idején itt önkénteskedett. Szivességét azzal viszonozzák, hogy
meghivják a bankettre. Hadd emlegesse egész életében, hogy
micsoda szerencsében volt része ezen az estén. Aztán meg kitünő
reklám neki, hogy egy tálból ehetett velük. Különben türhető
embernek találják, mert meglátszik a kezén, hogy manicure-rel
ápoltatja.
Miről beszélgetnek a lakomán az előkelő gárdatisztek és a még
előkelőbb ulánusok? Ilyenekről: mi történik amazoknál és mi történik
emezeknél, ha a hadnagy részegségében inzultálja a tiszthelyettes
altisztet, aki nem elég gyorsan ugrott fel, mikor a tiszt ráköszöntött?
Itt is, ott is ugyanaz történik; tudniillik csak két megoldás
képzelhető. Vagy: bocsánatot kér a hadnagy a tiszthelyettes altiszttől
az egész tisztikar előtt; vagy: a hadnagy „repül“, de amannak nem
marad más választása, mint hogy agyonlőjje magát, mert a
felpofozott altisztből soha se lehet tiszt. Majd panaszkodnak, hogy
ma már tiszt lehet mindenki, akinek a családja a rendőrséggel nem
került konfliktusba. A vendéglátók eldicsekednek vele, hogy a
gárdaezredekben nincs senki, aki polgári családból származnék. Az
ilyen tiszt mindnyájukat feszélyezné, de bizonyára ő maga is igen
kényelmetlenül érezné magát közöttük; ott, ahova nem való.
Elmondják végül egymásnak, hogy ők továbbra is azok akarnak
maradni, akik ma; tudniillik olyan emberek, akik a társadalom első
osztályát alkotják. Azért jelszavuk: az összetartás s fentartása annak
a választófalnak, mely a polgári társadalmat tőlük távoltartja.
Egy kissé „exprès“, az olvasó számára beszélgetnek igy; a
valóságban talán egyébről is diskurálnak. De ennyi nagyitást meg
lehet bocsátani a regényirónak, akinek végre is ki kell éleznie a
mondanivalóját. Az bizonyos, hogy sok tulzás nincsen ebben az
előadásban. Egyforma foglalkozásu emberek, ha maguk közt vannak,
mindig sokat beszélgetnek a mesterségük dolgairól, s ez a szabály
talán sehol se érvényesül annyira, mint a katonatiszteknél, akiket
sokféle érdeklődés, sokféle ismeretek nem igen vonnak el a közös
témától. Az se tünik fel tóditásnak, hogy sok „jó házból való“
hadnagyocska szaladgál a világban, aki sehogy se tud eltelni
szerencsés társadalmi helyzetével, s akit ezen a hiuságon kivül
jóformán semmi se foglalkoztat. Elhiszszük Baudissin grófnak, hogy
egy ilyen lakomán egész sereg olyan alak találkozik, akinek minden
igyekezete az, hogy az előkelők közt a legelőkelőbb legyen, aki
tartózkodó és zárkózott, mert „ez előkelő“, aki keveset beszél, a
szemlélődőt játszsza, elmésségeken töri a fejét s teszi magát, mintha
már mindent megunt volna, csak azért, mert ezt igy látta előkelő
mintáktól. És nem éppen hihetetlen alak az az idősebb tiszt se, aki
igy nyilatkozik: „Büszkeségünk, hogy csekély eszközeink ellenére is
azok maradhassunk, akik vagyunk“ – arra czélozván, hogy akárhány
társának sok nélkülözést kell elszenvednie, hogy állásához méltón
léphessen fel. Annyival könnyebben elképzelhető, hogy sokan
beszélnek igy, mert hiszen ebben a felfogásban már bizonyos
nemesebb fajta büszkeség nyilatkozik meg; ezen tehát a
szatirikusnak nincs mért fennakadnia. De jegyezzük meg mindjárt,
hogy az a másik hiuság, a gyerekes hiuság, melynek a szerző
néhány mulatságos példáját beszéli el, nem valami specziális hibája
a hadseregnek. Ezzel a hiusággal nemcsak a tiszti kaszinóban
találkozni, hanem mindenütt, ahol nagy számban vannak együtt
előkelő származásu fiatal emberek; s ezt a hibát csak ott lehet a
katonaság rovására irni, ahol, mint a nagynémet hadseregben, az a
felfogás érvényesül, hogy a tiszti állás első sorban a nemesi
osztálynak való. S kérdés, nem helyesebb-e, hogy itt az előkelőket
ugyanazokra a helyekre csoportositják „előkelő ezred“-eket
formálván, mintha szétszórnák őket a hadseregben, s az olyan
konfliktusokat, aminőt Baudissin gróf beszél el, nem csupán egy-két,
hanem sok ezredben tennék lehetővé, tehát gyakorivá s szinte
mindennapossá?!
A lakomán az udvar képviselője a hivatalos tósztok után, kissé
savanyu arczot vágva, mondja el a felsőbb helyről hozott üzenetet,
hogy az ünneplők uj bajtársat kapnak, bizonyos Winkler
személyében, akit valamelyik határszéli, közönséges gyalogos
ezredtől helyeztek át a gárdaezredhez. Maga a hirhozó is igyekszik
átsiklani a kellemetlen ujságon s örül, mikor már másról beszélhet. A
többieket valósággal konsternálja a hir; az ezredestől a legfiatalabb
hadnagyig mindegyik kétségbe van esve. „Polgáriak lettünk!“ – fut
végig a suttogás a termen. És éppen most! Alig hogy végre
összejöttek az ulánusokkal, alig hogy megvan az óhajtott barátság!
Félő, hogy mindjárt vége a komaságnak, mert hiszen polgári
származásu cseppent közéjök! És az ulánusok csakugyan egyszerre
elkezdenek feszengeni.
De hogyan kerülhetett közéjük az a bizonyos Winkler? Winkler
egy gazdag gyárosnak a fia. Az apa grata persona az udvarnál,
melynek szolgálatokat tett. A fiunak nem volt kedve a katonai
pályához; a szülei kedvéért szolgál, akik persze igen szeretnének
nagy urat faragni belőle. Anyjának nincsen forróbb óhajtása, mint
hogy fiuk annál az előkelő ezrednél szolgáljon; bántja az a gondolat,
hogy vannak ajtók, amelyeket a pénz nem nyit fel előttük. Az
idősebb Winkler tehát nagyszerü alapitványt tesz, amelyet nem lehet
egyébbel honorálni, mint hogy teljesitik a kérését, s fiát áthelyezik a
gárdához. Megint a hiuság; itt is, ott is, mindig a hiuság. Nemcsak az
arisztokraták hibája ez, hanem a többieké is, akik csak azért nem
arisztokraták, mert nem lehetnek azok.
Baudissin gróf regénye hosszasan irja le, mily fagyosan fogadják
az ezrednél a Winkler-fiut s mennyire éreztetik vele, hogy nem
tartják közéjük valónak. Nem mondja, hogy a szolgálatban is
okoznának neki kellemetlenségeket, – pedig a vitairat csak igy
bizonyithatná azt, hogy a hadsereg szervezetében van a hiba – de
beszámol vele, hogy a szolgálaton kivül, a társadalmi érintkezésben
hogyan éreztetik vele a polgári származását, milyen fagyosak
maradnak hozzá, mennyire magára hagyják s hányszor adják jelét
azokban a társaságokban, ahol mindnyájuknak meg kell jelenniök,
hogy nem tartják magukkal egyenrangunak. A regény folyamán
Baudissin gróf alkalmat talál annak hangsulyozására, hogy Winkler
különb ember, mint többen azok közül, akik lenézik, de hősét azért
nem tudja valami rendkivül szimpatikussá tenni, mert Winklernek
csak folyton sebzett érzékenységét és hiuságában való szenvedését
látjuk, meg azt a jómódját, hogy mindig szórhatja a pénzét, mig
azok közül néhányan, akik „nem fogadják be“, gyakran vért izzadnak
a garas hijján. Az apró szekaturákat, amelyeket el kell viselnie,
szintén nem találjuk szörnyüeknek; nagyon ridegen, de korrektül
viselkednek vele szemben, egyetlenegy embert kivéve. Nem
igazságtalanok hozzá, csak előitélettel vannak iránta. Nem találjuk se
szimpatikusnak, se eléggé érthetőnek, hogy Winkler – bármennyiszer
adják értésére bajtársai, hogy szeretnék maguk közül kinézni – olyan
sokáig türi ferde helyzetét; s miután „daczból“ egy jó darabig
kitartott, de aztán hirtelen megelégli a mulatságot, elhatározását
nem találjuk eléggé motiváltnak. Az ok, mely arra készti, hogy
lemondjon tiszti rangjáról, csekélység; a mit nem tud türni, semmi
ahhoz képest, amit már lenyelt. Példája tehát nem meggyőző, s ha
arról van szó, hogy egy olyan gárdaezredben, ahol csupa nemesi sarj
szolgál, a polgári származásu tiszt helyzete tarthatatlan: Winkler
tulajdonképpen nem is panaszkodhatik. Bizonyára akadtak, akik, épp
oly ártatlanul, rosszabbul jártak nála, holott nem voltak abban a
kedvező helyzetben, mint ő, hogy az első kellemetlenség után
„valet“-et mondhattak volna a lehetetlen szituácziónak. Szóval, mikor
Winkler megelégli a gárdaezrednél való szolgálatot, az olvasó
benyomása az, hogy: debuisset pridem, és mit is keresett azon a
gályán?!
Ha a szerző, aki előkelő származásu ember és sokáig volt
katonatiszt, teljesen együtt érez a határozatlanságból s szüleinek
kedvéért kapaszkodó, habozó természetü és kissé türelmes
Winklerrel: ez az iró mögött rejtőzködő embernek bizonyára
becsületére válik. Világos, hogy Baudissin gróf nemes gondolkozásu,
előitéletek nélkül való ember, akiben nincsen osztálygőg és
korlátoltság. De ebből nem következik, hogy az, amit támad,
csakugyan olyan értelmetlenség volna, mint amilyennek ő tünteti fel.
Ahhoz, hogy a világon minden hierarchia eltörlődjék, olyan
társadalmi átalakulásoknak kellene elkövetkezniök, amelyeket ma
még elképzelni sem tudunk. Egyelőre a különböző foglalkozásokat
nem tekinthetjük egyenranguaknak. Aki a szemetet söpri el, nem
végez olyan értékes munkát, mint az, aki a tudományt egy lépéssel
előbbre viszi, és az, aki a kóbor kutyákat fogdossa össze, nem
tarthat számot akkora megbecsülésre, mint az operatőr, akinek a
tudásától, az eszétől, a szemétől és a kezétől mindennap egy pár
emberélet függ. A tekintélyből mindenekelőtt annyit arrogálhat
valaki, amennyi a foglalkozását megilleti, és a sokféleképpen
értékelhető, különböző foglalkozások között a katonáé kivételes
disztinkczióra tarthat számot. Akármennyire elmosódik is a hosszas
békében a katonaság presztizse és akármilyen kicsinyeseknek
látszanak a háboru apró előkészületei: maga a dolog ma még az
emberi akarat nagyobb erőfeszitései közé tartozik. Végre is, aki az
életét viszi a vásárra egy közczél érdekében, több becsülésre szolgál
rá, mint az, akinek a foglalkozása nem szolgál egyebet, csak a saját
életének fentartását. És ameddig minden fogalmunk meg nem
változik a férfiasságról, amely ma még abban találja meg
legvilágosabb kifejezését, hogy valaki az életét is kész feláldozni
valamely közczélért vagy eszméért, ami ugyanazt jelenti, s csak
bizonyos, erejét és egyéniségét megillető föltételek közt hajlandó
megalkudni az élettel: a katonai hiuság természetes marad, s annak
arrogálása, hogy a katonai hivatás bizonyos morális fensőbbségben
van számtalan, a legtöbb békés foglalkozás felett: nem esztelenség.
Akármit mondjon némely ujabb elmélet: ez a tétel ma a
közfelfogásban is érvényesül s alighanem érvényesülni fog, amig az
örökbéke valósággá nem válik; az élet, a „gyakorlat“, a konvencziók,
a szokások, számtalan társadalmi jelenség mind bizonyitják, hogy
érvényesül. Ez a követelés csak ott válik esztelenséggé, kómikussá
vagy gyülöletessé, ahol a tulzás kezdődik, ahol ez a követelés az
itélet nélkül való, az összesség jogait az egyén jogaitól
megkülönböztetni nem tudó, brutális önzéssel, vagy a más jogát
nem respektáló s magának képzelt jogokat tulajdonitó nevetséges
arrogancziával egyesülten lép fel.
Nem esztelenség az a másik előitélet sem, amelyet a szerző ab
ovo elitél. Ma, amikor annyi szó van a betegségek, a bün és a lelki
tehetségnek örökléséről, jóhiszemüen nem lehet azt állitani, hogy
csak éppen azok a kiválóságok nem öröklődnek, melyekkel annak
idején rangot szereztek a mai előkelők ősei. Persze ez a hereditás
nem megy odáig, hogy minden főuri ivadék nemesebb anyagnak,
vagy éppen kiválóságnak születnék; hiszen talán az a hajdani
kiválóság is csak nagyobb erő vagy véletlen szerencse volt. De csak
az elfogultság tagadhatja, hogy az arisztokráczián általában igenis
meglátszanak valamely régi kiválóság, a régibb kultura, vagy
legalább is a nemzedékről-nemzedékre örökölt szerencsésebb
életmód és testi jólét hatásai; ha akad köztük akárhány, aki olyan
canaille, mintha nem rózsafán termett volna: összességük, egészben
– s mindenütt a világon – jobb emberanyag, mint a megfelelő számu
szolga-ivadék; talán nem épebb, de fejlettebb agy- és idegrendszerü.
Azért a származáshoz füződő előitélet tisztára babonának nem
mondható; s az ősi névvel, a ranggal és az ezekkel kapcsolatos
egyéb, örökölt jókkal való megelégedés igen érthető. De hiszen az
arisztokratikus büszkeség voltaképpen nem is abból áll, mintha az
előkelők folyton az őseiken lovagolnának; ez a büszkeség inkább a
gondolkozásmód és az izlés bizonyos közösségén alapszik s a
leggyakrabban a másféle gondolkozástól és másféle izléstől való
idegenkedésben nyilatkozik meg. Hogy tehát ebben a büszkeségben
ne volna némi ráczió és hogy a tömegből való huzódozásuknak, még
exkluzivitásuknak is, ne volna elfogadható oka, vagy legalább némi
alapja, magyarázata: bajos állitani. Következésképpen ennek a
büszkeségnek csak az elfajulásai foglalkoztathatják a szatirikust.
Baudissin gróf olyan arisztokratákról szól, akik közt van négy
vagy öt canaille, vannak korrekt urak, a legtöbben tuczatemberek.
Ügyet se vet rá, észre se veszi, hogy miközben alakjait bemutatja,
sok olyan jótulajdonságról emlékszik meg, amelyek az arisztokraták
speczialitásai. (A szegény rokonok gyámolitása; a koldus
grófkisasszony nemes büszkesége: a szeretett, de vagyonos kérőtől
való huzódozása stb.) Nem veszi észre, hogy „a munka emberei“-ről,
akiket magasztal, nem tud ennyi jót mondani, s csak a hiuságot, az
élvezetvágyat, s a szükségtelenül exponált érzékenységet mutatja
meg bennök. Megbotránkozik, joggal, a fényes nevet viselő, kevély,
de pénztelenségükben mindenre képes canaille-ok elvetemültségén,
de legtöbbet a tuczatemberekkel foglalkozik, akik lenézik a polgári
származásu pénzes embert s el vannak telve kiváltságos
helyzetükkel, holott nincs egyebük, mint a rangjok. Nem veszi észre,
hogy ezek a tuczat-emberek voltaképpen igen menthetően,
barátságtalanul, de tisztességesen viselkednek Winklerrel szemben.
Nem tetszik nekik a köztük léte, előitélettel fogadják, ridegen szólnak
hozzá, éreztetik vele vélt felsőbbségüket; de nem utaznak rá, soha
se bántják meg, nem iparkodnak maguk közül kiintrikálni; mikor
rászolgál, nem tagadják meg tőle az elismerést; kiméletesen bánnak
vele, sőt még védik is, mikor bajba kerül. Csak éppen nem ugranak a
nyakába.
De hát mit is keres azon a gályán? Mért kivánkozott éppen a
grófok közé? Nem tudott ott maradni a hozzá hasonlók között? Mért
találja jobbnak a cseresznyét, ha a nagyurakkal egy tálból eheti?
Nem gondolta meg, hogy ha olyan helyre törekszik, amelyet az
előbbinél jobbnak, finomabbnak, előkelőbbnek, kiváltságosnak talál,
ennek a helynek ára van, amelyet az érzékenysége fog megfizetni?
Vagy azt hitte, hogy a pénzével mindent megfizethet? Mivel különb
annak a hiusága, aki szeretne a grófokhoz dörgölőzni, annak a
grófnak a hiuságánál, aki nem szeret a polgárral parolázni?
Winklernek nincs igaza és itt nincs igaza Baudissin grófnak sem.
Előkelő hadnagyocskáinak a kevélysége oktalan és ott, ahova ők
még csak megvetéssel se tekintenek le, a derék és okos embereknek
egész sokasága él, amely csak kómikusnak, szánalmasnak és
együgyünek találhatja ezt a kevélységet. De az a hiba, melyet
Baudissin gróf a hadsereg rovására ir, nem a hadsereg hibája. Nem
ennek a szervezete fejleszti ki az önérzetnek ilyen nevetséges
tultengését. Az efajta visszásságok megvannak minden téren,
nemcsak a tiszti kaszinóban; s azok a kómikus vonások, amelyeket
Baudissin gróf véletlenül tiszteken vett észre, megfigyelhetők olyan
embereken is, akiknek nem a kardcsörtetés a foglalkozása. A
Baudissin gróf regénye is azt bizonyitja. Ez a könyv semmivel se
foglalkozik annyit, mint a hiusággal. Egész sereg előkelő származásu
katonatisztet szerepeltet, akiket az Isten megfosztott az eszüktől s e
helyett nevetnivaló hiusággal vert meg. De a regénynek az az alakja,
akiben a hiuság a legnagyobb s a legvégzetesebb: egy nadrággomb-
gyáros.
IRODALOM ÉS UJSÁGIRÁS.
I.
II.
III.
IV.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookultra.com