Hibernate Tutorial
Hibernate Tutorial
Indexed collections
Composite Collection Elements
Lifecycle objects
Automatic primary key generation
Multiple synthetic key generation strategies
Support for application assigned identifiers
Support for composite keys
Object/Relational mapping definition
XML mapping documents
Human-readable format
XDoclet support
HDLCA (Hibernate Dual-Layer Cache Architecture)
Thread safeness
Non-blocking data access
Session level cache
Optional second-level cache
Optional query cache
Works well with others
High performance
Lazy initialization
Outer join fetching
Batch fetching
Support for optimistic locking with versioning/timestamping
Highly scalable architecture
High performance
No "special" database tables
SQL generated at system initialization time
(Optional) Internal connection pooling and PreparedStatement caching
J2EE integration
JMX support
Integration with J2EE architecture (optional)
New JCA support
HIBERNATE TUTORIAL
HIBERNATE - Overview of Hibernate
High level architecture of Hibernate can be described as shown in following
illustration.
Hibernate makes use of persistent objects commonly called as POJO (POJO = "Plain
Old Java Object".) along with XML mapping documents for persisting objects to the
database layer. The term POJO refers to a normal Java objects that does not serve
any other special role or implement any special interfaces of any of the Java
frameworks (EJB, JDBC, DAO, JDO, etc...).
Rather than utilize byte code processing or code generation, Hibernate uses runtime
reflection to determine the persistent properties of a class. The objects to be
persisted are defined in a mapping document, which serves to describe the persistent
fields and associations, as well as any subclasses or proxies of the persistent object.
The mapping documents are compiled at application startup time and provide the
framework with necessary information for a class. Additionally, they are used in
support operations, such as generating the database schema or creating stub Java
source files.
Typical Hibernate code
sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Customer newCustomer = new Customer();
newCustomer.setName("New Customer");
newCustomer.setAddress("Address of New Customer");
newCustomer.setEmailId("[email protected]");
session.save(newCustomer);
tx.commit();
session.close();
First step is hibernate application is to retrieve Hibernate Session; Hibernate Session
is the main runtime interface between a Java application and Hibernate.
SessionFactory allows applications to create hibernate session by reading hibernate
configurations
file
hibernate.cfg.xml.
After specifying transaction boundaries, application can make use of persistent java
objects and use session for persisting to the databases.
HIBERNATE TUTORIAL
HIBERNATE - Features of Hibernate
HIBERNATE TUTORIAL
HIBERNATE - Getting Started With Hibernate
Hibernate is Free Software. The LGPL license is sufficiently flexible to allow the use of
Hibernate in both open source and commercial projects (see the LicenseFAQ for
details). Hibernate is available for download at http://www.hibernate.org/
We wll take up an simple java example that authenticates users based on the
credentials to get started with hibernate.
HIBERNATE TUTORIAL
HIBERNATE
Getting
Started
With
Hibernate
Preparing Database
Lets consider a simple database schema with a singe table as APPLABSUSER.
HIBERNATE TUTORIAL
HIBERNATE
Getting
Started
With
Hibernate
persistent
classes.
Hibernate is not restricted in its usage of property types, all Java JDK types and
primitives (like String, char and Date) can be mapped, including classes from the
Java collections framework. You can map them as values, collections of values, or
associations to other entities. The id is a special property that represents the
database identifer (primary key) of that class, Hibernate can use identifiers only
internally, but we would lose some of the flexibility in our application architecture.
No special interface has to be implemented for persistent classes nor do you have to
subclass from a special root persistent class. Hibernate also doesn't require any build
time processing, such as byte-code manipulation, it relies solely on Java reflection
and runtime class enhancement (through CGLIB). So, without any dependency of the
POJO class on Hibernate, we can map it to a database table.
Following code sample represents a java object structure which represents the
AppLabsUser table. Generally these domain objects contain only getters and setters
methods. One can use Hibernate extension toolset to create such domain objects.
AppLabsUser.java
package org.applabs.quickstart;
import java.io.Serializable;
import java.util.Date;
import org.apache.commons.lang.builder.ToStringBuilder;
public class AppLabsUser implements Serializable {
HIBERNATE TUTORIAL
HIBERNATE
Getting
Started
With
Hibernate
Each persistent class needs to be mapped with its configuration file. Following code
represents Hibernate mapping file for AppLabsUser class.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD
2.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="org.applabs.hibernate.quickstart.AppLabsUser"
table="applabsuser">
<id column="USER_ID" name="id" type="java.lang.Long">
<generator class="sequence"/>
</id>
<property column="USER_NAME" length="255" name="userName" notnull="true" type="java.lang.String"/>
<property column="USER_PASSWORD" length="255" name="userPassword"
not-null="true" type="java.lang.String"/>
<property column="USER_FIRST_NAME" length="255"
name="userFirstName" type="java.lang.String"/>
<property column="USER_LAST_NAME" length="255" name="userLastName"
type="java.lang.String"/>
<property column="USER_EMAIL" length="255" name="userEmail"
type="java.lang.String"/>
<property column="USER_CREATION_DATE" length="10"
name="userCreationDate" type="java.util.Date"/>
<property column="USER_MODIFICATION_DATE" length="10"
name="userModificationDate" type="java.util.Date"/>
</class>
</hibernate-mapping>
One can also generate Hibernate mapping documents using Hibernate extension
toolset. Hibernate mapping documents are straight forward. The <class> element
maps a table with corresponding class. The <id> element represents the primary key
column, and its associated attribute in the domain object. The <property> elements
represent all other attributes available in the domain object.
HIBERNATE TUTORIAL
HIBERNATE
Getting
Started
With
Hibernate
<mapping-resource> refers to the mapping document that contains mapping for domain
object and hibernate mapping document.
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="show_sql">true</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLMyISAMDialect</property>
<property
name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/applabs</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">r00Tp@$wd</property>
<mapping resource="org/applabs/hibernate/quickstart/Applabsuser.hbm.xml"/>
</session-factory>
</hibernate-configuration>
HIBERNATE
Getting
Started
With
Hibernate
<session-factory>
<property name="show_sql">true</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLMyISAMDialect</property>
<property
name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/applabs</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">r00Tp@$wd</property>
<mapping resource="org/applabs/hibernate/quickstart/Applabsuser.hbm.xml"/>
</session-factory>
</hibernate-configuration>
HIBERNATE
Getting
Started
With
Hibernate
connection details and resource mapping details etc are supplied in the program
using Configuration API.
Following example shows programmatic configuration of hibernate.
HIBERNATE
Getting
Started
With
Hibernate
SQL_STRING
"FROM
AppLabsUser
as
new
users";
Query
query
=
ArrayList list = (ArrayList)query.list();
for(int
System.out.println(list.get(i));
}
session.createQuery(SQL_STRING);
i=0;
i<list.size();i++){
session.close();
The above example shows a typical mapping document that contains class mapping
with
table.
All mapping XML document should refer to hibernate-mapping-3.0.dtd via doctype.
HIBERNATE
Hibernate
O/R
Mapping
<hibernate-mapping> element
The root element of hibernate mapping document is <hibernate-mapping> element.
This element has several optional attributes. The schema and catalog attributes
specify that tables referred to in this mapping belong to the named schema and/or
catalog. If specified, tablenames will be qualified by the given schema and catalog
names. If missing, tablenames will be unqualified. The default-cascade attribute
specifies what cascade style should be assumed for properties and Collections which
do not specify a cascade attribute. The auto-import attribute lets us use unqualified
class names in the query language, by default.
<hibernate-mapping
schema="schemaName"
catalog="catalogName"
default-cascade="cascade_style"
default-access="field|property|
(1)
(2)
(3)
(4)
(5)
ClassName"
default-lazy="true|false"
auto-import="true|false"
package="package.name"
(6)
(7)
/>
(1)
(2)
(3)
(4)
HIBERNATE
<class> element
Hibernate
O/R
Mapping
The <Class> element maps the domain object with corresponding entity in the
database. hibernate-mapping element allows you to nest several persistent <class>
mappings, as shown above. It is however good practice to map only a single
persistent class in one mapping file and name it after the persistent superclass, e.g.
User.hbm.xml, Group.hbm.xml.
<class
name="ClassName"
table="tableName"
discriminator-value="discriminator_value"
mutable="true|false"
schema="owner"
catalog="catalog"
proxy="ProxyInterface"
dynamic-update="true|false"
dynamic-insert="true|false"
select-before-update="true|false"
polymorphism="implicit|explicit"
where="arbitrary sql where condition"
persister="PersisterClass"
batch-size="N"
optimistic-lock="none|version|dirty|all"
lazy="true|false"
entity-name="EntityName"
catalog="catalog"
check="arbitrary sql check condition"
rowid="rowid"
subselect="SQL expression"
abstract="true|false"
(1)
(2)
(3)
(4)
(5)
(6)
(7)
(8)
(9)
(10)
(11)
(12)
(13)
(14)
(15)
(16)
(17)
(18)
(19)
(20)
(21)
(22)
/>
(1)
(2)
(3)
(4)
(5)
(6)
(7)
name (optional): The fully qualified Java class name of the persistent class (or
interface). If this attribute is missing, it is assumed that the mapping is for a
non-POJO entity.
table (optional - defaults to the unqualified class name): The name of its
database table.
discriminator-value (optional - defaults to the class name): A value that
distiguishes individual subclasses, used for polymorphic behaviour. Acceptable
values include null and not null.
mutable (optional, defaults to true): Specifies that instances of the class are
(not) mutable.
schema (optional): Override the schema name specified by the root
<hibernate-mapping> element.
catalog (optional): Override the catalog name specified by the root <hibernatemapping> element.
proxy (optional): Specifies an interface to use for lazy initializing proxies. You
may specify the name of the class itself.
(8)
HIBERNATE
<id> element
Hibernate
O/R
Mapping
The <id> element defines the mapping from that property to the primary key
column. Mapped classes must declare the primary key column of the database table.
Most classes will also have a JavaBeans-style property holding the unique identifier of
an instance.
<id
name="propertyName"
type="typename"
column="column_name"
unsaved-value="null|any|none|undefined|
id_value"
access="field|property|ClassName">
(1)
(2)
(3)
(4)
(5)
<generator class="generatorClass"/>
/>
(1) name (optional): The name of the identifier property.
(2) type (optional): A name that indicates the Hibernate type.
(3) column (optional - defaults to the property name): The name of the primary
key column.
(4) unsaved-value (optional - defaults to a "sensible" value): An identifier property
value that indicates that an instance is newly instantiated (unsaved),
distinguishing it from detached instances that were saved or loaded in a
previous session.
(5) access (optional - defaults to property): The strategy Hibernate should use for
accessing the property value.
HIBERNATE
Hibernate
O/R
Mapping
<generator> element
The optional <generator> child element names a Java class used to generate unique
identifiers for instances of the persistent class. If any parameters are required to
configure or initialize the generator instance, they are passed using the <param>
element.
<id name="id" type="long" column="cat_id">
<generator class="org.hibernate.id.TableHiLoGenerator">
<param name="table">uid_table</param>
<param name="column">next_hi_value_column</param>
</generator>
</id>
All generators implement the interface org.hibernate.id.IdentifierGenerator. This is a
very simple interface; some applications may choose to provide their own specialized
implementations. However, Hibernate provides a range of built-in implementations.
HIBERNATE
Hibernate
O/R
Mapping
<property> element
The <property> element declares a persistent, JavaBean style property of the class.
<property
name="propertyName"
column="column_name"
type="typename"
update="true|false"
insert="true|false"
formula="arbitrary SQL expression"
access="field|property|ClassName"
lazy="true|false"
unique="true|false"
not-null="true|false"
optimistic-lock="true|false"
/>
(1)
(2)
(3)
(4)
(4)
(5)
(6)
(7)
(8)
(9)
(10)
(3)
(4)
(5)
(6)
(7)
(8)
(9)
not-null (optional): Enable the DDL generation of a nullability constraint for the
columns.
(10) optimistic-lock (optional - defaults to true): Specifies that updates to this
property do or do not require acquisition of the optimistic lock. In other words,
determines if a version increment should occur when this property is dirty.
typename could be:
The name of a Hibernate basic type (eg. integer, string, character, date,
timestamp, float, binary, serializable, object, blob).
The name of a Java class with a default basic type (eg. int, float, char,
java.lang.String, java.util.Date, java.lang.Integer, java.sql.Clob).
The name of a serializable Java class.
HIBERNATE
Hibernate
O/R
Mapping
<many-to-one> element
An ordinary association to another persistent class is declared using a many-to-one
element. The relational model is a many-to-one association: a foreign key in one
table is referencing the primary key column(s) of the target table.
<many-to-one
name="propertyName"
column="column_name"
class="ClassName"
cascade="cascade_style"
fetch="join|select"
update="true|false"
insert="true|false"
propertyref="propertyNameFromAssociatedClass"
access="field|property|ClassName"
unique="true|false"
not-null="true|false"
optimistic-lock="true|false"
lazy="true|false"
entity-name="EntityName"
(1)
(2)
(3)
(4)
(5)
(6)
(6)
(7)
(8)
(9)
(10)
(11)
(12)
/>
(1)
(2)
(3)
(4)
(5)
(6)
(7)
(8)
access (optional - defaults to property): The strategy Hibernate should use for
accessing the property value.
(9) unique (optional): Enable the DDL generation of a unique constraint for the
foreign-key column. Also, allow this to be the target of a property-ref. This
makes the association multiplicity effectively one to one.
(10) not-null (optional): Enable the DDL generation of a nullability constraint for the
foreign key columns.
(11) optimistic-lock (optional - defaults to true): Specifies that updates to this
property do or do not require acquisition of the optimistic lock. In other words,
dertermines if a version increment should occur when this property is dirty.
(12) lazy (optional - defaults to false): Specifies that this property should be fetched
lazily when the instance variable is first accessed (requires build-time bytecode
instrumentation).
A typical many-to-one declaration looks as simple as this:
<many-to-one name="product" class="Product" column="PRODUCT_ID"/>
HIBERNATE
Hibernate
O/R
Mapping
<one-to-one> element
A one-to-one association to another persistent class is declared using a one-to-one
element. .
<one-to-one
name="propertyName" (1)
class="ClassName" (2)
cascade="cascade_style" (3)
constrained="true|false" (4)
fetch="join|select" (5)
propertyref="propertyNameFromAssociatedClass"
(6)
access="field|property|ClassName" (7)
formula="any SQL expression" (8)
entity-name="EntityName"
(1)
(2)
(3)
(4)
(5)
(6)
(7)
(8)
/>
(5)
(6)
(7)
(8)
of the mapped table references the table of the associated class. This option
affects the order in which save() and delete() are cascaded, and determines
whether the association may be proxied (it is also used by the schema export
tool).
fetch (optional - defaults to select): Chooses between outer-join fetching or
sequential select fetching.
property-ref: (optional) The name of a property of the associated class that is
joined to the primary key of this class. If not specified, the primary key of the
associated class is used.
access (optional - defaults to property): The strategy Hibernate should use for
accessing the property value.
formula (optional): Almost all one to one associations map to the primary key of
the owning entity. In the rare case that this is not the case, you may specify a
some other column, columns or expression to join on using an SQL formula.
(See org.hibernate.test.onetooneformula for an example.)
HIBERNATE TUTORIAL
HIBERNATE - Hibernate Mapping In Depth
Hibernate allows the mapping of Mapped tables with the domain objects using the
persistent collection-valued fields. These fields needs be declared as an interface
type. The actual interface can be java.util.Set, java.util.Collection, java.util.List,
java.util.Map, java.util.SortedSet, java.util.SortedMap or custom implementations of
org.hibernate.usertype.UserCollectionType
Collections instances have the usual behavior of value types. They are automatically
persisted when referenced by a persistent object and automatically deleted when
unreferenced. If a collection is passed from one persistent object to another, its
elements might be moved from one table to another. Two entities may not share a
reference to the same collection instance. Due to the underlying relational model,
collection-valued properties do not support null value semantics;
public class Product {
private String serialNumber;
private Set parts = new HashSet();
public Set getParts() { return parts; }
void setParts(Set parts) { this.parts = parts; }
public String getSerialNumber() { return serialNumber; }
void setSerialNumber(String sn) { serialNumber = sn; }
}
Collection Mapping
<map
name="propertyName"
table="table_name"
schema="schema_name"
lazy="true|false"
inverse="true|false"
cascade="all|none|save-update|delete|all-deleteorphan"
sort="unsorted|natural|comparatorClass"
order-by="column_name asc|desc"
where="arbitrary sql where condition"
fetch="join|select"
batch-size="N"
access="field|property|ClassName"
optimistic-lock="true|false"
>
<key .... />
<map-key .... />
<element .... />
</map>
(1)
(2)
(3)
(4)
(5)
(6)
(7)
(8)
(9)
(10)
(11)
(12)
(13)
(1)
These
are
some
more
mapings
which
we
Association
Component
Instance Mapping
will
discuss
later
Mapping
Mapping
HIBERNATE TUTORIAL
HIBERNATE - Hibernate Query Language
Hibernate is equipped with an extremely powerful query language that looks very
much like SQL. Queries are case-insensitive, except for names of Java classes and
properties.
Clause
The
from
clause
The
simplest
possible
Hibernate
query
is
of
From
From
which
the
form:
org.applabs.base.User
User
simply
returns
all
instances
of
the
class
org.applabs.base.User.
Most of the time, you will need to assign an alias, since you will want to refer to the
User in other parts of the query.
from
User
as
user
This query assigns the alias user to User instances, so we could use that alias later in
the
query.
The
as
keyword
is
optional;
we
could
also
write:
from
User
user
User
User,
user,
as
The
Group
Group
group
as
select
clause
The select clause picks which objects and properties to return in the query result set.
Queries may return properties of any value type including properties of component
type:
select
user.name
where user.name like 'mary%'
select
customer.contact.firstName
The
The
from
User
from
user
Customer
as
where
where
from
returns
clause
allows
User
instances
you
as
to
narrow
user
of
clause
the
list
of
where
User
cust
named
instances
returned.
user.name='mary'
'mary'.
Compound path expressions make the where clause extremely powerful. Consider:
from org.applabs.base.Customer cust where cust.contact.name is not null
This query translates to an SQL query with a table (inner) join. If you were to write
something
like
The = operator may be used to compare not only properties, but also instances:
from
Document
doc,
User
user
where
doc.user.name
user.name
The special property (lowercase) id may be used to reference the unique identifier of
an
object.
(You
may
also
use
its
property
name.)
from Document as doc where doc.id = 131512
from Document as doc where doc.author.id = 69
The
order
by
clause
The list returned by a query may be ordered by any property of a returned class or
components:
from User user order by user.name asc, user.creationDate desc, user.email
The optional asc or desc indicate ascending or descending order respectively.
The
group
by
clause
A query that returns aggregate values may be grouped by any property of a returned
class
or
components:
select
sum(document)
document.category
A
having
from
clause
Document
is
document
also
group
by
allowed.
select
sum(document)
from
Document
document
group
document.category
having document.category in (Category.HIBERNATE, Category.STRUTS)
Associations
and
by
joins
inner
join
left
outer
join
right
outer
join
full
join
(not
usually
useful)
The inner join, left outer join and right outer join constructs may be abbreviated.
Aggregate
functions
HQL queries may even return the results of aggregate functions on properties: The
supported
aggregate
functions
are
avg(...), sum(...), min(...), max(...) , count(*), count(...), count(distinct ...),
count(all...)
The distinct and all keywords may be used and have the same semantics as in SQL.
Expressions
Expressions allowed in the where clause include most of the kind of things you could
write
in
SQL:
mathematical
operators
+,
-,
*,
/
binary
comparison
operators
=,
>=,
<=,
<>,
!=,
like
logical
operations
and,
or,
not
string
concatenation
||
SQL
scalar
functions
like
upper()
and
lower()
Parentheses
(
)
indicate
grouping
in,
between,
is
null
JDBC
IN
parameters
?
named
parameters
:name,
:start_date,
:x1
SQL
literals
'foo',
69,
'1970-01-01
10:00:01.0'
Java
public
static
final
constants
eg.Color.TABBY
Sub
queries
For databases that support subselects, Hibernate supports subqueries within queries.
A subquery must be surrounded by parentheses (often by an SQL aggregate function
call). Even correlated subqueries (subqueries that refer to an alias in the outer query)
are allowed.
HIBERNATE TUTORIAL
HIBERNATE - Hibernate Complete Example
In this section we will extend our quick start sample into to a web based application
that
comprises
of
struts
and
Hibernate
support.
Introduction
In this example we will build a simple web based document repository application
using hibernate. The document repository under consideration will have
categorization of the documents based on the topics (Folder based like structure),
Keywords for each document (this will simplify searches), versioning for each
document, Document modification history, permissions based access for each entity
based
on
users
and
groups.
Database
scheme.
The concept of properties tables: Here we have extended the concept of Hash tables
to the database, Instead of adding more and more columns as per growing needs A
properties table is created per Entity, Each property (Prop) table contains name and
value pair that stores additional information for particular entity, thus you can store
as many properties as you want for a given entity. Getter and setter methods need to
be provided from the domain object so that we can represent these properties inside
domain
objects.
Basic
entities.
Basic entities such as User, Group, and Permissions along with Prop tables for each
are provided to persistent data for corresponding entities, Now as a business rule a
group contains multiple Users and One User can be a part of multiple Groups. Each
entity, User, Group, and Permission have UserProp, GroupProp and PremissionProp
respectively. The relation between Entity and Prop is one to many. E.g. User can have
multiple Properties. (For simplicity, Permission tables are not shown in the model)
Categories
and
Documents
Category refers to a Folder/Directory like structure on the file system. Each category
may or may not have its Parent Category. Category contains information like name,
description, creation details, modification deleted and deletion details. Each category
can have multiple entries. (Each Folder can contain one or more Documents (Entries)
in it. Each Document can have one or more versions in it.(Document corresponds to
version). Document contains information such as Title, Body, Summary, life cycle
details, version number, keywords, workflow status, Entry details and Attachment
details; Document also contains properties associated with it. Attachment is a file
associated with each Document, Database stores the name of file stored on the file
system and the size of Attachment.
HIBERNATE
Database Scripts
Hibernate
Complete
Example
--Drop Tables
DROP TABLE "APP"."ATTACHMENT";
DROP TABLE "APP"."CATEGORY";
DROP TABLE "APP"."CATEGORY_PROP";
DROP TABLE "APP"."DOCUMENT";
DROP TABLE "APP"."DOCUMENT_ATTACHMENT";
DROP TABLE "APP"."DOCUMENT_KEYWORDS";
DROP TABLE "APP"."DOCUMENT_PROP";
DROP TABLE "APP"."ENTRY";
DROP TABLE "APP"."GROUP";
DROP TABLE "APP"."GROUP_PROP";
DROP TABLE "APP"."IDGENERATOR";
DROP TABLE "APP"."KEYWORD";
DROP TABLE "APP"."USER";
DROP TABLE "APP"."USER_GROUP";
DROP TABLE "APP"."USER_PROP";
-- Table: "APP"."ATTACHMENT"
CREATE TABLE "APP"."ATTACHMENT"
(
"ATTACHMENT_ID" numeric NOT NULL,
"DOCUMENT_ID" numeric,
"ATTACHMEMT_PATH" varchar,
"ATTACHMENT_SIZE" numeric,
CONSTRAINT "ATTACHMENT_pkey" PRIMARY KEY ("ATTACHMENT_ID")
);
-- Table: "APP"."CATEGORY"
CREATE TABLE "APP"."CATEGORY"
(
"CATAGORY_ID" numeric NOT NULL,
"CATEGORY_NAME" varchar,
"CATEGORY_DESCRIPTION" varchar,
"CREATED_BY" numeric,
"CREATION_DATE" date,
"MODIFIED_BY" numeric,
"MODIFICATION_DATE" date,
"DELETED_BY" numeric,
"DELETE_DATE" date,
"PARENT_CATAGORY" numeric,
CONSTRAINT "CATEGORY_pkey" PRIMARY KEY ("CATAGORY_ID"),
CONSTRAINT "CATEGORY_PARENT_CATAGORY_fkey" FOREIGN KEY
("PARENT_CATAGORY") REFERENCES "APP"."CATEGORY" ("CATAGORY_ID") ON
UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT authorfk FOREIGN KEY ("CREATED_BY") REFERENCES "APP"."USER"
("USER_ID") ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT deletorfk FOREIGN KEY ("DELETED_BY") REFERENCES "APP"."USER"
("USER_ID") ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT editorfk FOREIGN KEY ("MODIFIED_BY") REFERENCES "APP"."USER"
("USER_ID") ON UPDATE NO ACTION ON DELETE NO ACTION
);
-- Table: "APP"."CATEGORY_PROP"
CREATE TABLE "APP"."CATEGORY_PROP"
(
"CATEGORY_PROP_ID" numeric NOT NULL,
"CATEGORY_ID" numeric,
"PROP_NAME" varchar,
"PROP_VALUE" varchar,
CONSTRAINT "CATEGORY_PROP_pkey" PRIMARY KEY ("CATEGORY_PROP_ID"),
CONSTRAINT "CATEGORY_PROP_CATEGORY_ID_fkey" FOREIGN KEY
("CATEGORY_ID") REFERENCES "APP"."CATEGORY" ("CATAGORY_ID") ON UPDATE
NO ACTION ON DELETE NO ACTION
);
-- Table: "APP"."DOCUMENT"
CREATE TABLE "APP"."DOCUMENT"
(
"DOCUMENT_ID" numeric NOT NULL,
"DOCUMENT_TITLE" varchar,
"DOCUMENT_BODY" varchar,
"DOCUMENT_SUMMARY" varchar,
"CREATED_BY" numeric,
"CREATION_DATE" date,
"MODIFIED_BY" numeric,
"MODIFICATION_DATE" date,
"DELETED_BY" numeric,
"DELETED_DATE" date,
"DOCUMENT_VERSION" numeric,
"DOCUMENT_STATUS" numeric,
"ENTRY_ID" numeric,
CONSTRAINT "DOCUMENT_pkey" PRIMARY KEY ("DOCUMENT_ID"),
CONSTRAINT "DOCUMENT_ENTRY_ID_fkey" FOREIGN KEY ("ENTRY_ID")
REFERENCES "APP"."ENTRY" ("ENTRY_ID") ON UPDATE NO ACTION ON DELETE NO
ACTION,
CONSTRAINT authorfk FOREIGN KEY ("CREATED_BY") REFERENCES "APP"."USER"
("USER_ID") ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT deletorfk FOREIGN KEY ("DELETED_BY") REFERENCES "APP"."USER"
("USER_ID") ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT editorfk FOREIGN KEY ("MODIFIED_BY") REFERENCES "APP"."USER"
("USER_ID") ON UPDATE NO ACTION ON DELETE NO ACTION
);
-- Table: "APP"."DOCUMENT_ATTACHMENT"
CREATE TABLE "APP"."DOCUMENT_ATTACHMENT"
(
"DOCUMENT_ATTACHMENT_ID" numeric NOT NULL,
"ATTACHMENT_ID" numeric,
"DOCUMENT_ID" numeric,
"ATTACHMENT_PATH" varchar,
"ATTACHMENT_SIZE" numeric,
CONSTRAINT "DOCUMENT_ATTACHMENT_pkey" PRIMARY KEY
("DOCUMENT_ATTACHMENT_ID"),
CONSTRAINT "DOCUMENT_ATTACHMENT_ATTACHMENT_ID_fkey" FOREIGN KEY
("ATTACHMENT_ID") REFERENCES "APP"."ATTACHMENT" ("ATTACHMENT_ID") ON
UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT "DOCUMENT_ATTACHMENT_DOCUMENT_ID_fkey" FOREIGN KEY
("DOCUMENT_ID") REFERENCES "APP"."DOCUMENT" ("DOCUMENT_ID") ON UPDATE
NO ACTION ON DELETE NO ACTION
);
-- Table: "APP"."DOCUMENT_KEYWORDS"
CREATE TABLE "APP"."DOCUMENT_KEYWORDS"
(
"DOCUMENT_KEYWORD_ID" numeric NOT NULL,
"DOCUMENT_ID" numeric,
"KEYWORD_ID" numeric,
z CONSTRAINT "DOCUMENT_KEYWORDS_pkey" PRIMARY KEY
("DOCUMENT_KEYWORD_ID"),
CONSTRAINT "DOCUMENT_KEYWORDS_DOCUMENT_ID_fkey" FOREIGN KEY
("DOCUMENT_ID") REFERENCES "APP"."DOCUMENT" ("DOCUMENT_ID") ON UPDATE
NO ACTION ON DELETE NO ACTION,
CONSTRAINT keywordidfk FOREIGN KEY ("KEYWORD_ID") REFERENCES
"APP"."KEYWORD" ("KEYWORD_ID") ON UPDATE NO ACTION ON DELETE NO
ACTION
);
-- Table: "APP"."DOCUMENT_PROP"
CREATE TABLE "APP"."DOCUMENT_PROP"
(
document_prop_id numeric NOT NULL,
document_id numeric NOT NULL,
prop_name varchar NOT NULL,
prop_value varchar,
prop_value_details varchar,
CONSTRAINT "DOCUMENT_PROP_pkey" PRIMARY KEY (document_prop_id),
CONSTRAINT "DOCUMENT_PROP_document_id_fkey" FOREIGN KEY (document_id)
REFERENCES "APP"."DOCUMENT" ("DOCUMENT_ID") ON UPDATE NO ACTION ON
DELETE NO ACTION
);
-- Table: "APP"."ENTRY"
CREATE TABLE "APP"."ENTRY"
(
"ENTRY_ID" numeric NOT NULL,
"CATEGORY_ID" numeric,
CONSTRAINT "ENTRY_pkey" PRIMARY KEY ("ENTRY_ID"),
CONSTRAINT "ENTRY_CATEGORY_ID_fkey" FOREIGN KEY ("CATEGORY_ID")
REFERENCES "APP"."CATEGORY" ("CATAGORY_ID") ON UPDATE NO ACTION ON
DELETE NO ACTION
);
-- Table: "APP"."GROUP"
-- Table: "APP"."GROUP_PROP"
CREATE TABLE "APP"."GROUP_PROP"
(
group_prop_id numeric NOT NULL,
group_id numeric NOT NULL,
prop_name varchar NOT NULL,
prop_value varchar,
prop_value_details varchar,
CONSTRAINT "GROUP_PROP_pkey" PRIMARY KEY (group_prop_id),
CONSTRAINT "GROUP_PROP_group_id_fkey" FOREIGN KEY (group_id) REFERENCES
"APP"."GROUP" ("GROUP_ID") ON UPDATE NO ACTION ON DELETE NO ACTION
);
-- Table: "APP"."IDGENERATOR"
CREATE TABLE "APP"."IDGENERATOR"
(
id numeric NOT NULL,
next_value numeric NOT NULL,
CONSTRAINT "IDGENERATOR_pkey" PRIMARY KEY (id)
);
--
Table: "APP"."KEYWORD"
CREATE TABLE "APP"."KEYWORD"
(
"KEYWORD_ID" numeric NOT NULL,
"KEYWORD_NAME" varchar,
"KEYWORD_DESCRIPTION" varchar,
CONSTRAINT "KEYWORD_pkey" PRIMARY KEY ("KEYWORD_ID")
);
-- Table: "APP"."USER"
CREATE TABLE "APP"."USER"
(
HIBERNATE
Hibernate
Complete
Example
HIBERNATE
Hibernate
Complete
Example
hbm files
User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.applabs.base.User" table="USER">
<id column="USER_ID" name="id" type="java.lang.Long">
<generator class="org.hibernate.id.TableHiLoGenerator">
<param name="table">idgen</param>
<param name="column">NEXT</param>
</generator>
</id>
<property column="USER_NAME" name="userName"
type="java.lang.String"/>
<property column="USER_PASSWORD" name="userPassword"
type="java.lang.String"/>
<property column="USER_FIRST_NAME" name="userFirstName"
type="java.lang.String"/>
<property column="USER_EMAIL" name="userEmail"
type="java.lang.String"/>
<property column="USER_LAST_NAME" name="userLastName"
type="java.lang.String"/>
<property column="CREATION_DATE" length="4" name="creationDate"
type="java.util.Date"/>
<property column="CREATED_BY" name="createdBy"
type="java.lang.Double"/>
<property column="MODIFICATION_DATE" length="4"
name="modificationDate" type="java.util.Date"/>
<property column="MODIFIED_BY" name="modifiedBy"
type="java.lang.Double"/>
<property column="DELETE_DATE" length="4" name="deleteDate"
type="java.util.Date"/>
<property column="DELETED_BY" name="deletedBy"
type="java.lang.Double"/>
<set name="properties" lazy="true" inverse="true" cascade="all-deleteorphan">
<key column="USER_ID" />
<one-to-many class="org.applabs.base.UserProp" />
</set>
</class>
</hibernate-mapping>
UserProp.hbm.xml
Category.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
CategoryProp.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.applabs.base.CategoryProp" table="CATEGORY_PROP">
<id column="CATEGORY_PROP_ID" name="id" type="java.lang.Long">
<generator class="org.hibernate.id.TableHiLoGenerator">
<param name="table">idgen</param>
<param name="column">NEXT</param>
</generator>
</id>
<property column="CATEGORY_ID" name="categoryId"
type="java.lang.Long"/>
<property column="PROP_NAME" name="propName"
type="java.lang.String"/>
<property column="PROP_VALUE" name="propValue"
type="java.lang.String"/>
</set>
</class>
</hibernate-mapping>
Document.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.applabs.base.Document" table="DOCUMENT">
<id column="DOCUMENT_ID" name="id" type="java.lang.Long">
<generator class="sequence"/>
</id>
<property column="DOCUMENT_TITLE" name="documentTitle"
type="java.lang.String"/>
<property column="DOCUMENT_BODY" name="documentBody"
type="java.lang.String"/>
<property column="DOCUMENT_SUMMARY" name="documentSummary"
type="java.lang.String"/>
<property column="CREATED_BY" length="65535" name="createdBy"
type="java.lang.Double"/>
<property column="CREATION_DATE" length="4" name="creationDate"
type="java.util.Date"/>
<property column="MODIFIED_BY" length="65535" name="modifiedBy"
type="java.lang.Double"/>
<property column="MODIFICATION_DATE" length="4"
name="modificationDate" type="java.util.Date"/>
<property column="DELETED_BY" length="65535" name="deletedBy"
type="java.lang.Double"/>
<property column="DELETED_DATE" length="4" name="deletedDate"
type="java.util.Date"/>
<property column="DOCUMENT_VERSION" length="65535"
name="documentVersion" type="java.lang.Double"/>
<property column="DOCUMENT_STATUS" length="65535"
name="documentStatus" type="java.lang.Double"/>
<property column="ENTRY_ID" length="65535" name="entryId"
type="java.lang.Double"/>
</class>
</hibernate-mapping>
DocumentProp.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.applabs.base.DocumentProp" table="DOCUMENT_PROP">
<id column="document_prop_id" name="id" type="java.lang.Long">
<generator class="sequence"/>
</id>
<property column="document_id" length="65535" name="documentId" notnull="true" type="java.lang.Double"/>
<property column="prop_name" name="propName" not-null="true"
type="java.lang.String"/>
<property column="prop_value" name="propValue"
type="java.lang.String"/>
<property column="prop_value_details" name="propValueDetails"
type="java.lang.String"/>
</class>
</hibernate-mapping>