8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 1/23
This tutorial shows a simple example using Hibernate. We will create a simpleJava application, showing how Hibernate works.
Consulting / Development
I am a freelancer and can be booked for your projects. In cooperation with other
specialists, you have even access to a development team of highly qualifiedexperts.
Java Persistence and Hibernate Training
I offer training on Hibernate and Java Persistence (Glassfish with Oracle Toplink or JBoss).
General
Author: Sebastian Hennebrueder
Date:
First edition 2005
updated February, 9th 2008
Used software and frameworks
Eclipse 3.x
MyEclipse or alternatively Hibernate Tools are recommended but optional
Hibernate 3.x (I used 3.3)
Source code: http://www.laliluna.de/download/first-hibernate-example-
tutorial.zip
The sources does not include the libraries. Download the libraries from
hibernate.org and your database driver and add them to the project as explained below! The example must be configured to work with your database settings!
Read the tutorial.
PDF version of the tutorial: http://www.laliluna.de/download/first-hibernate-
example-tutorial-en.pdf
Java
Persistenceand
HibernateTraining
I offer training on
Hibernateand Java
Persistence(Glassfish
withOracle
Toplink or JBoss).
Get more
information.
Consulting/
Development
I am afreelancer
and can be booked for
your
projects. Incooperation with
other specialists,
you haveeven
access to adevelopme
nt team of highly
qualifiedexperts.
Get moreinformatio
n.
Hibernate
and JavaPersistence
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 2/23
Old PDF version with Hibernate 2: http://www.laliluna.de/download/first-
hibernate-2-example-tutorial-en.pdf
Short introductionHibernate is a solution for object relational mapping and a persistencemanagement solution or persistent layer. This is probably not understandable for
anybody learning Hibernate.
What you can imagine is probably that you have your application with some
functions (business logic) and you want to save data in a database. When you useJava all the business logic normally works with objects of different class types.
Your database tables are not at all objects.
Hibernate provides a solution to map database tables to a class. It copies one row
of the database data to a class. In the other direction it supports to save objects to
the database. In this process the object is transformed to one or more tables.
Developer
Guide
XML andAnnotation
s,Performan
ce chapter,Hibernate
search,Integration
withSpring,
EJB3 andJSF
Availableas up to
date ebook Get moreinformatio
n.
News
Devoxx2009
Presentation
(Nov. 18, 2009)
Window IdBrowser
Extension(Blog)
(Nov. 13, 2
009)JSF 2evaluationand test
(Blog) (Nov. 10, 2
009)
Devoxx
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 3/23
Saving data to a storage is called persistence. And the copying of tables to objects
and vice versa is called object relational mapping.
Create a Java ProjectUsing Eclipse press the keys Ctrl+n (Strg+n) to create a new project. Select a Java project. We will call it FirstHibernateExample.
Prepare the project for Hibernate
using MyEclipse
When you are using MyEclipse, right click on your project in the package explorer
andchoos
e Add Hiber
natecapa
bilitie s.
presentation on
ChoosingWeb
Framework
s (Blog) (Sep. 17, 2009)
JQueryJSON
autocomplete library
(Blog) (Sep. 01, 2
009)
Better Java
application packaging
- JSR 277Java
ModuleSystem
(Blog) (Aug. 21, 2
009)
Performance Tuning
Tips for Hibernate
and JavaPersistence
(Jan. 27, 2009)
Hibernate /Java
PersistenceeBook
update
(Jan. 27, 2009)
Hibernate
Searchwith
Lucene (Jan. 12, 2
009)
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 4/23
Continue the wizard and create a new hibernate.cfg.xml in the src directory.
In the last step you can create a Hibernate SessionFactory. I prefer to create my
own. You can find it below.
Prepare the project for Hibernate for
anybody
If you do not use MyEclipse, you can use the ant build to retrieve the libs using
Ivy or alternatively just download Hibernate from the websitehttp://www.hibernate.org/
You will need at least Hibernate Core. If you want to use Annotations you needHibernate Annotations and if you want to use Hibernate Search, you need to
download Hibernate Search as well.
Extract the file. Hibernate comes with a long list of libraries. You do not need allof them. There is a REAME file in the lib directory explaining what is required.
Open your project properties, select ³Java Build Path´, click on ³Add ExternalJars´ and add the libaries shown below to your project path.
The following list includes the libraries to use Hibernate with XML or annotations,EHCache, PostgreSQL and logging over log4j.
y antlr.jar
y backport-util-concurrent.jar y hibernate-commons-annotations.jar
y hibernate-annotations.jar y postgresql.jar
y hibernate-ehcache.jar y log4j.jar
y ejb3-persistence.jar y slf4j-log4j12.jar
y slf4j-api.jar
y javassist.jar y commons-collections.jar y dom4j.jar
y lucene-core.jar y commons-logging.jar
y hibernate-search.jar y jta.jar
y hibernate-core.jar
Notes fromthe
DevoxxConference
(Dec. 16, 2
008)
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 5/23
y ehcache.jar y xml-apis.jar
Create a SessionFactory
A session factory is important for Hibernate. It implements a design pattern, that
ensures that only one instance of the session is used per thread. You should onlyget your Hibernate session from this factory.
Create a class named InitSessionFactory in the package de.laliluna.hibernate and
add the source code below./**
** @author Sebastian Hennebrueder* created Feb 22, 2006* copyright 2006 by http://www.laliluna.de*/package de.laliluna.hibernate;
import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.AnnotationConfiguration;
/*** @author hennebrueder This class garanties that only one single
SessionFactory* is instanciated and that the configuration is donethread safe as* singleton. Actually it only wraps the HibernateSessionFactory.* You are free to use any kind of JTA or ThreadtransactionFactories.*/public class SessionFactoryUtil {
/** The single instance of hibernate SessionFactory */private static org.hibernate.SessionFactory sessionFactory;
/**
* disable contructor to guaranty a single instance*/
private SessionFactoryUtil() {}
static{// Annotation and XML
sessionFactory = newAnnotationConfiguration().configure().buildSessionFactory();
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 6/23
// XML only// sessionFactory = newConfiguration().configure().buildSessionFactory();}
public static SessionFactory getInstance() {
return sessionFactory;}
/*** Opens a session and will not bind it to a session context* @return the session*/
public Session openSession() {return sessionFactory.openSession();
}
/*** Returns a session from the session context. If there is no
session in the context it opens a session,
* stores it in the context and returns it.* This factory is intended to be used with a
hibernate.cfg.xml* including the following property <property* name="current_session_context_class">thread</property>
This would return* the current open session or if this does not exist,
will create a new* session** @return the session*/
public Session getCurrentSession() {
return sessionFactory.getCurrentSession();}
/*** closes the session factory*/
public static void close(){if (sessionFactory != null)
sessionFactory.close();sessionFactory = null;
}}
Configuring Log4J
As you can see above we added the log4j library. This library does like a
configuration file in the source directory or it welcomes you with the following
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 7/23
error.
log4j:WARN No appenders could be found for logger (TestClient).log4j:WARN Please initialize the log4j system properly.
Create a file named log4j.properties in the root directory and insert the following:
### direct log messages to stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p%c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to'debug' ###
log4j.rootLogger=debug, stdout
log4j.logger.org.hibernate=info#log4j.logger.org.hibernate=debug
### log HQL query parser activity#log4j.logger.org.hibernate.hql.ast.AST=debug
### log just the SQLlog4j.logger.org.hibernate.SQL=debug
### log JDBC bind parameters ###log4j.logger.org.hibernate.type=info
### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=info
### log HQL parse trees#log4j.logger.org.hibernate.hql=debug
### log cache activity ###log4j.logger.org.hibernate.cache=info
### log transaction activity#log4j.logger.org.hibernate.transaction=debug
### log JDBC resource acquisition#log4j.logger.org.hibernate.jdbc=debug
### enable the following line if you want to track down connection###### leakages when using DriverManagerConnectionProvider ####log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
Add the database driver
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 8/23
Even Hibernate needs a database driver to access a database. Open the project properties, click on ³Java Build Path´, select ³Add External Jars´ and add your
database driver. If you use PostgreSQL you can find your database driver onhttp://jdbc.postgresql.org if you use MySQL have a look here
http://www.mysql.de/products/connector/j
Create database and tables.
Create a database with MySql or PostgreSQL or anything you like. Call it³firsthibernate´.
Using PostgreSql use the following script to create your table:
CREATE TABLE "public"."honey" (id SERIAL,name text,taste text,PRIMARY KEY(id)
);
Using MySql use the following script:
CREATE TABLE `honey` (`id` int(11) NOT NULL auto_increment,`name` varchar(250) default NULL,`taste` varchar(250) default NULL,
PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1
Create the class
Create a new class named ³Honey´ in the package ³de.laliluna.example´. Add
three fields id, name and taste and generate (Context menu -> Source -> GenerateGetter and Setter) or type the getters and setters for the fields. Then create an
empty constructor.
package de.laliluna.example;
public class Honey {private Integer id;private String name;private String taste;
public Honey(){
}
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 9/23
public Integer getId() {
return id;}
public void setId(Integer id) {
this.id = id;}
public String getName() {return name;
}
public void setName(String name) {this.name = name;
}
public String getTaste() {return taste;
}
public void setTaste(String taste) {this.taste = taste;
}
public String toString() {return "Honey: "+getId()+" Name: "+getName()+"
Taste: "+getTaste();}
}
Create the Hibernate configuration
Create a new file named ³hibernate.cfg.xml´ in your root directory if it is not
already created.
Insert the following in your hibernate file. Do not forget to change the usernameand the password to suit your database configuration.
PostgreSQL Version:
<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-
configuration-3.0.dtd"><hibernate-configuration><session-factory>
<propertyname="connection.url">jdbc:postgresql://localhost/firsthibernate</
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 10/23
property><property name="connection.username">postgres</property><property
name="connection.driver_class">org.postgresql.Driver</property><property
name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="connection.password">p</property><propertyname="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- thread is the short name fororg.hibernate.context.ThreadLocalSessionContextand let Hibernate bind the session automatically to the
thread--><property
name="current_session_context_class">thread</property><!-- this will show us all sql statements --><property name="hibernate.show_sql">true</property>
<!-- mapping files -->
<mapping resource="de/laliluna/example/Honey.hbm.xml" /></session-factory></hibernate-configuration>
MySQL Version:
<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory>
<propertyname="connection.url">jdbc:mysql://localhost/firsthibernate</property>
<property name="connection.username">root</property><property
name="connection.driver_class">com.mysql.jdbc.Driver</property><property
name="dialect">org.hibernate.dialect.MySQLDialect</property><property name="connection.password">r</property>
<propertyname="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- thread is the short name fororg.hibernate.context.ThreadLocalSessionContextand let Hibernate bind the session automatically to the
thread--><property
name="current_session_context_class">thread</property>
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 11/23
<!-- this will show us all sql statements --><property name="hibernate.show_sql">true</property>
<!-- mapping files --><mapping resource="de/laliluna/example/Honey.hbm.xml" />
</session-factory></hibernate-configuration>
This file includes the configuration of the database in our case a PostgreSQL
database and all mapping files. In our case it is only the file Honey.hbm.xml. The
tag<propertyname="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
configures the dialect. Change this to fit your database. Have a look in the chapter
³SQL Dialects´ of the Hibernate reference to find the dialect for your database.
XML Mapping
You can use XML or annotations to define, how to map your class attributes to a
database table.
Create the Honey.hbm.xml in the package de.laliluna.example and change it to thefollowing:
PostgreSQL Version: <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate MappingDTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" ><hibernate-mapping><class name="de.laliluna.example.Honey" table="honey"><id name="id" column="id" >
<generator class="sequence"><param
name="sequence">honey_id_seq</param>
</generator>
</id>
<property name="name" column="fooname" /><property name="taste" column="bartaste" /></class></hibernate-mapping>
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 12/23
MySQL Version: <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate MappingDTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" ><hibernate-mapping><class name="de.laliluna.example.Honey" table="honey"><id name="id" column="id" ><generator class="increment"/></id><property name="name" column="fooname" /><property name="taste" column="bartaste" /></class></hibernate-mapping>
In this file the mapping from our class Honey to the database table honey is
configured.
Annotation based mapping
If you use annotation, you can define the mapping in the class.
package de.laliluna.example;
import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.GeneratedValue;
@Entitypublic class Honey {
@Id@GeneratedValue
private Integer id;
private String name;
private String taste;// ......... snip .........
Create a Test Client
Create a Java Class ³TestClient´ in the package ³de.laliluna.example´.
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 13/23
Add the following source code. It includes methods to create entries in thedatabase, to update and to list them.
package de.laliluna.example;
import java.util.Iterator;import java.util.List;
import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.Transaction;import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import de.laliluna.hibernate.SessionFactoryUtil;
public class TestExample {
final static Logger logger =LoggerFactory.getLogger(TestExample.class);
/*** @param args*/public static void main(String[] args) {Honey forestHoney = new Honey();forestHoney.setName("forest honey");forestHoney.setTaste("very sweet");Honey countryHoney = new Honey();countryHoney.setName("country honey");countryHoney.setTaste("tasty");createHoney(forestHoney);createHoney(countryHoney);// our instances have a primary key now:logger.debug("{}", forestHoney);logger.debug("{}", countryHoney);listHoney();deleteHoney(countryHoney);listHoney();forestHoney.setName("Norther Forest Honey");updateHoney(forestHoney);
}
private static void listHoney() {Transaction tx = null;Session session =
SessionFactoryUtil.getInstance().getCurrentSession();try {tx = session.beginTransaction();
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 14/23
List honeys = session.createQuery("select h from Honey ash")
.list();for (Iterator iter = honeys.iterator(); iter.hasNext();) {Honey element = (Honey) iter.next();logger.debug("{}", element);
}tx.commit();} catch (RuntimeException e) {if (tx != null && tx.isActive()) {try {
// Second try catch as the rollback could fail as welltx.rollback();
} catch (HibernateException e1) {logger.debug("Error rolling back transaction");
}// throw again the first exception
throw e;}
}}
private static void deleteHoney(Honey honey) {Transaction tx = null;Session session =
SessionFactoryUtil.getInstance().getCurrentSession();try {tx = session.beginTransaction();session.delete(honey);tx.commit();
} catch (RuntimeException e) {
if (tx != null && tx.isActive()) {try {
// Second try catch as the rollback could fail as welltx.rollback();
} catch (HibernateException e1) {logger.debug("Error rolling back transaction");
}// throw again the first exception
throw e;}
}}
private static void createHoney(Honey honey) {
Transaction tx = null;Session session =
SessionFactoryUtil.getInstance().getCurrentSession();try {tx = session.beginTransaction();session.save(honey);tx.commit();
} catch (RuntimeException e) {if (tx != null && tx.isActive()) {
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 15/23
try {// Second try catch as the rollback could fail as well
tx.rollback();} catch (HibernateException e1) {logger.debug("Error rolling back transaction");
}
// throw again the first exceptionthrow e;}
}}
private static void updateHoney(Honey honey) {Transaction tx = null;Session session =
SessionFactoryUtil.getInstance().getCurrentSession();try {tx = session.beginTransaction();session.update(honey);tx.commit();
} catch (RuntimeException e) {if (tx != null && tx.isActive()) {try {
// Second try catch as the rollback could fail as welltx.rollback();
} catch (HibernateException e1) {logger.debug("Error rolling back transaction");
}// throw again the first exception
throw e;}
}}
}
Congratulations. You have finished your first steps in the Hibernate world.
We wanted to give you a fast entry in the Hibernate world. There are many more
complex topics and better implementation to use Hibernate. For example, theopening and closing of the session in each method is not a good practice. A
session can be reused during which saves a lot of time.
If you want to learn more about best practices have a look at my eBook or my
Hibernate training offers.
Copyright and disclaimer
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 16/23
This tutorial is copyright of Sebastian Hennebrueder, laliluna.de. You maydownload a tutorial for your own personal use but not redistribute it. You must not
remove or modify this copyright notice.
The tutorial is provided as is. I do not give any warranty or guaranty any fitness
for a particular purpose. In no event shall I be liable to any party for direct,indirect, special, incidental, or consequential damages, including lost profits,arising out of the use of this tutorial, even if I has been advised of the possibility of
such damage.
Copyright (c) 2004-2009 by Sebastian Hennebrueder, laliluna.de Impressum
Jasper Reports
-DVSHU5HSRUWVLVWKHZRUOG£VPRVWSRSXODURSHQVRXUFH-DYDUHSRUWLQJOLEUDU\<RXFDQHDVLO\HPEHGLWLQWRDQ\-DYDDSSOLFDWLRQWRGHOLYHUVRSKLVWLFDWHGSULQWRUZHEUHSRUWLQJ<RXFDQDOVRXVHLWWRFUHDWHRXWSXWWRILOHVIRUIXUWKHUSURFHVVLQJLQDSSOLFDWLRQVOLNH([FHO)RUXVHUVZLWKPRUHVRSKLVWLFDWHGUHSRUWPDQDJHPHQWUHTXLUHPHQWVUHSRUWVGHVLJQHGIRU-DVSHU5HSRUWVFDQEHHDVLO\PLJUDWHGWRWKH-DVSHU6RIWVWDQGDORQHUHSRUWVHUYHU-DVSHU'HFLVLRQV
:RUNLQJ2I-DVSHU5HSRUWV
7RJHQHUDWHMDVSHUUHSRUWZHUHTXLUHD-5;0/ILOHDOVRFDOOHGWHPSODWH -5;0/ILOHFRQWDLQVWKHUHSRUWVWUXFWXUHLQIRUPDWLRQ -5;0/ILOHSDUVHE\-5;PO/RDGHUDQGFRQYHUWLWLQWR-DVSHU'HVLJQ2EM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java.util.HashMap; 8. import java.util.Map;
9. import net.sf.jasperreports.engine.JRException; 10. import net.sf.jasperreports.engine.JasperCompileManager; 11. import net.sf.jasperreports.engine.JasperExportManager; 12. import net.sf.jasperreports.engine.JasperFillManager; 13. import net.sf.jasperreports.engine.JasperPrint; 14. import net.sf.jasperreports.engine.JasperReport; 15. import net.sf.jasperreports.view.JasperViewer;
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 18/23
16. 17. public class Main { 18. 19. 20. public Main() { 21. }
22. 23. 24. public static void main(String[] args) { 25. // TODO code application logic here 26. 27. 28. String reportSource1 = "./templates/stdtab.jrxml";
29. String reportSource = "./templates/sampletab.jrxml";
30. String reportDest = "./report/reports1/MyProjReport.pdf";
31. String reportDest1 = "./report/reports2/SampleReport.html";
32. String reportDest2 = "./report/reports3/SampleReport.xml"; 33. Map<String, Object> params = new HashMap<String, Object>(); 34. params.put("reportTitle", "MY Project Reports"); 35. params.put("author", "SRINIVAS");
36. params.put("startDate", (new java.util.Date()).toString()); 37. try 38. { 39. JasperReport jasperReport = 40.
JasperCompileManager.compileReport(reportSource); 41. JasperReport jasperReport1 = 42.
JasperCompileManager.compileReport(reportSource1); 43. // Make the driver class available.
44. Class.forName("oracle.jdbc.driver.OracleDriver");
45. 46. // Create a connection to pass into the report.
47. java.sql.Connection conn =
DriverManager.getConnection( 48. "url", "username", "password"); 49. 50. // Replace the empty JR datasource parameter
with 51. // the connection parameter named conn. 52. JasperPrint jasperPrint =
53. JasperFillManager.fillReport( 54. jasperReport, params, conn); 55. JasperPrint jasperPrint1 = 56. JasperFillManager.fillReport( 57. jasperReport1, params, conn); 58. 59. JasperExportManager.exportReportToPdfFile( 60. jasperPrint, reportDest); 61. JasperExportManager.exportReportToHtmlFile(
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 19/23
62. jasperPrint1, reportDest1); 63. 64. JasperExportManager.exportReportToXmlFile( 65. jasperPrint, reportDest2,true); 66. 67. // JasperViewer.viewReport(jasperPrint);
68. // JasperViewer.viewReport(jasperPrint1); 69. } 70. catch (JRException e) 71. { 72. e.printStackTrace(); 73. } 74. 75. // Exception handling for the Class.forName method.
76. catch (ClassNotFoundException ex) 77. { 78. ex.printStackTrace(); 79. }
80. 81. // Exception handling for the
DriverManager.getConnection method.
82. catch (Exception ex) 83. { 84. ex.printStackTrace(); 85. } 86. } 87. 88. } 89. 90. 91.
92. JRXML FILES93. 94. 95. 96. sampletab.jrxml 97. 98. 99. 100. <?xml version="1.0"?> 101. <!DOCTYPE jasperReport102. PUBLIC "-//JasperReports//DTD Report Design//EN" 103.
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd"> 104. 105. <jasperReport name="HelloReportWorld"> 106. <parameter name="reportTitle"
class="java.lang.String"/> 107. <parameter name="author" class="java.lang.String"/> 108. <parameter name="startDate" class="java.lang.String"/> 109.
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 20/23
110. <queryString> 111. <![CDATA[SELECT * FROM SAMPLETAB]]> 112. </queryString> 113. 114. 115. <field name="NAME" class="java.lang.String"/>
116. <field name="FNAME" class="java.lang.String"/> 117. 118. <title> 119. <band height="60"> 120. <textField> 121. <reportElement x="0" y="10" width="500"
height="40"/> 122. <textElement textAlignment="Center"> 123. <font size="28"/> 124. </textElement> 125. <textFieldExpression
class="java.lang.String">
126.
<![CDATA[$P{reportTitle}]]> 127. </textFieldExpression> 128. </textField> 129. <textField> 130. <reportElement x="0" y="40" width="500"
height="20"/> 131. <textElement textAlignment="Center"/> 132. <textFieldExpression
class="java.lang.String"> 133. <![CDATA["Run by: " + $P{author} 134. + " on " + $P{startDate}]]> 135. </textFieldExpression> 136. </textField> 137. </band> 138. 139. 140. 141. 142. </title> 143. 144. <columnHeader> 145. <band height="30"> 146. <rectangle> 147. <reportElement x="0" y="0" width="530"
height="25"/>
148. <graphicElement/> 149. </rectangle> 150. <staticText> 151. <reportElement x="10" y="5" width="50"
height="15"/> 152. <textElement/> 153. <text><![CDATA[NAME]]></text> 154. </staticText> 155. <staticText>
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 21/23
156. <reportElement x="60" y="5" width="150" height="15"/>
157. <text><![CDATA[FNAME]]></text> 158. </staticText> 159. 160. 161. </band> 162. </columnHeader> 163. 164. 165. <detail> 166. <band height="20"> 167. <textField> 168. <reportElement x="10" y="0" width="50"
height="15"/> 169. <textElement/> 170. <textFieldExpression
class="java.lang.String">
171.
<![CDATA[$F{NAME}]]> 172. </textFieldExpression> 173. </textField> 174. <textField> 175. <reportElement x="60" y="0" width="150"
height="15"/> 176. <textElement/> 177. <textFieldExpression
class="java.lang.String"> 178. <![CDATA[$F{FNAME}]]> 179. </textFieldExpression> 180. </textField> 181. 182. </band> 183. </detail> 184. 185. </jasperReport> 186. 187. stdtab.jrxml 188. 189. <?xml version="1.0"?> 190. <!DOCTYPE jasperReport191. PUBLIC "-//JasperReports//DTD Report Design//EN" 192.
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
193. 194. <jasperReport name="HelloReportWorld"> 195. <parameter name="reportTitle"
class="java.lang.String"/> 196. <parameter name="author" class="java.lang.String"/> 197. <parameter name="startDate" class="java.lang.String"/> 198. 199. <queryString> 200. <![CDATA[SELECT * FROM STDTAB]]>
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 22/23
201. </queryString> 202. 203. 204. <field name="SNO" class="java.lang.Integer"/> 205. <field name="SNAME" class="java.lang.String"/> 206. 207. <title> 208. <band height="60"> 209. <textField> 210. <reportElement x="0" y="10" width="500"
height="40"/> 211. <textElement textAlignment="Center"> 212. <font size="28"/> 213. </textElement> 214. <textFieldExpression
class="java.lang.String"> 215. <![CDATA[$P{reportTitle}]]> 216. </textFieldExpression>
217.
</textField> 218. <textField> 219. <reportElement x="0" y="40" width="500"
height="20"/> 220. <textElement textAlignment="Center"/> 221. <textFieldExpression
class="java.lang.String"> 222. <![CDATA["Run by: " + $P{author} 223. + " on " + $P{startDate}]]> 224. </textFieldExpression> 225. </textField> 226. </band> 227. 228. </title> 229. 230. <columnHeader> 231. <band height="30"> 232. <rectangle> 233. <reportElement x="0" y="0" width="530"
height="25"/> 234. <graphicElement/> 235. </rectangle> 236. <staticText> 237. <reportElement x="10" y="5" width="50"
height="15"/>
238. <textElement/> 239. <text><![CDATA[SNO]]></text> 240. </staticText> 241. <staticText> 242. <reportElement x="60" y="5" width="150"
height="15"/> 243. <text><![CDATA[SNAME]]></text> 244. </staticText> 245.
8/8/2019 This Tutorial Shows a Simple Example Using Hibernate
http://slidepdf.com/reader/full/this-tutorial-shows-a-simple-example-using-hibernate 23/23
246. </band> 247. </columnHeader> 248. 249. <detail> 250. <band height="20"> 251. <textField>
252. <reportElement x="10" y="0" width="50" height="15"/>
253. <textElement/> 254. <textFieldExpression
class="java.lang.Integer"> 255. <![CDATA[$F{SNO}]]> 256. </textFieldExpression> 257. </textField> 258. <textField> 259. <reportElement x="60" y="0" width="150"
height="15"/> 260. <textElement/>
261.
<textFieldExpressionclass="java.lang.String"> 262. <![CDATA[$F{SNAME}]]> 263. </textFieldExpression> 264. </textField> 265. 266. </band> 267. </detail> 268. 269. </jasperReport>
Top Related