google Analytics

Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

Thursday, December 16, 2010

Hibernate one-one Mappng Example




Hibernate – One-to-one relationship example
Hibernate one to one Mapping Example
hibernate one to one annotation example
=========================================================================

The Scripts
CREATE TABLE `user` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `NAME` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1$$

CREATE TABLE `address` (
  `ID` int(11) NOT NULL,
  `ADDRESS` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`ID`),
  KEY `FK_ID` (`ID`),
  CONSTRAINT `FK_ID` FOREIGN KEY (`ID`) REFERENCES `user` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$

=================================================================================
The User.java Domain Class
@Entity
@Table(name = "user", catalog = "onetwoone")
public class User implements java.io.Serializable {
    private Integer id;
    private String name;
    private Address addresses;
    public User() {
    }
    @Id
    @GeneratedValue(strategy = AUTO)
    @Column(name = "ID", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    @Column(name = "NAME", length = 45)
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @OneToOne(fetch = FetchType.LAZY, mappedBy = "user")
    @Cascade( { CascadeType.ALL })
    public Address getAddresses() {
        return this.addresses;
    }

    public void setAddresses(Address addresses) {
        this.addresses = addresses;
    }
}

===================================================================================================
The Addres class
 To map the association of user in the Address class as a shared primary key association, you also need the @PrimaryKeyJoinColumn annotation:
@Entity
@Table(name = "address", catalog = "onetwoone")
public class Address implements java.io.Serializable {
    private Integer id;
    private User user;
    private String address;
    public Address() {
    }

    // Property accessors
    @GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "user"))
    @Id
    @GeneratedValue(generator = "generator")
    @Column(name = "ID", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
    @OneToOne(fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn
    public User getUser() {
        return this.user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    @Column(name = "ADDRESS", length = 45)
    public String getAddress() {
        return this.address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}
==================================================================================================
Test Programme
public class TestOneTwoOneMapping {
    public static void main(String[] args) {
        User user=new User();
        user.setName("Anish");
        Address address =new Address();
        address.setAddress("USA");
        address.setUser(user);
        user.setAddresses(address);
        new UserDAO().save(user);
    }
}

================================================================================================

The hibernatecfg.xml file
<?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>
    <property name="connection.username">root</property>
    <property name="connection.url">
        jdbc:mysql://localhost/onetwoone
    </property>
    <property name="dialect">
        org.hibernate.dialect.MySQLDialect
    </property>
    <property name="myeclipse.connection.profile">
        com.mysql.jdbc.Driver
    </property>
    <property name="connection.password">password</property>
    <property name="connection.driver_class">
        com.mysql.jdbc.Driver
    </property>
    <property name="show_sql">true</property>
    <mapping class="session.User" />
    <mapping class="session.Address" />
</session-factory>
</hibernate-configuration>
===============================================================================================
ANish

Tuesday, September 14, 2010

Using JBoss Cache as a Hibernate Second Level Cache

Using JBoss Cache as a Hibernate Second Level Cache


=============================================================
 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jee="http://www.springframework.org/schema/jee"         
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
       http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
       ">
    <bean id="cisSessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" scope="singleton">
        <property name="hibernateProperties">
            <props>               
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.generate_statistics">true</prop>   
                <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.jbc2.JndiMultiplexedJBossCacheRegionFactory</prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
                <prop key="hibernate.cache.region.jbc2.cachefactory">java:CacheManager</prop>
                <prop key="hibernate.cache.region.jbc2.cfg.entity">mvcc-entity</prop>
                <prop key="hibernate.cache.region.jbc2.cfg.query">local-query</prop>

            </props>
        </property>


        <property name="packagesToScan">
            <list>
                <value>com.test.persistence.entity</value>
            </list>
        </property>
        <property name="dataSource" ref="persistence.datasource"/>
        <property name="jtaTransactionManager" ref="jtaTransactionManager"/>
    </bean>
     
    <bean id="persistence.datasource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName">
            <value>java:TestDS</value>
        </property>
    </bean>


   <bean id="testDao" class="com.test.dao.hibernate.TestDAOImpl">
        <property name="sessionFactory" ref="testSessionFactory"/>
  </bean>
       <bean id="jtaTransactionManager"   class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName"><value>java:/TransactionManager</value></property>
    </bean>
    <bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>
    <aop:aspectj-autoproxy/>
    <tx:annotation-driven transaction-manager="txManager"/>
</beans>



========================================================
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class TestDAOImpl extends HibernateDaoSupport {

    public List<StudentEntity> getStudents() {
        getHibernateTemplate().setQueryCacheRegion("/com/test/Student");
        getHibernateTemplate().setCacheQueries(true);
        List<StudentEntity> studentList = getHibernateTemplate()
                .findByNamedQuery("student.All");
        return studentList;
    }
}

======================================================
1.The JndiMultiplexedJBossCacheRegionFactory requires that the JBoss Cache CacheManager
is already bound in JNDI; it will not create and bind one if it isn't. It is up to the the user to ensure
the cache is CacheManager and bound in JNDI before the Hibernate SessionFactory is created.

2.For non-JPA Hibernate second level caching, the same configuration properties and values are used;
they are just declared in a Hibernate SessionFactory cfg.xml
file using its syntax (and with "hibernate." removed from the property names):


1.The JndiMultiplexedJBossCacheRegionFactory requires that the JBoss Cache CacheManager
is already bound in JNDI; it will not create and bind one if it isn't. It is up to the the user to ensure
the cache is CacheManager and bound in JNDI before the Hibernate SessionFactory is created.

2.For non-JPA Hibernate second level caching, the same configuration properties and values are used;
they are just declared in a Hibernate SessionFactory cfg.xml
file using its syntax (and with "hibernate." removed from the property names):

3. JBoss Cache requires integration with a JTA TransactionManager in order to meet the
requirements of the second level caching use case. This means your Hibernate application must
be configured to use JTA:


Single JBoss Cache Instance Architecture
    For the single cache case, the user should specify SharedJBossCacheRegionFactory as their
    hibernate.cache.region.factory_class
Multiple JBoss Cache Instance Architecture
    Here the user should specify MultiplexedJBossCacheRegionFactory as their
    hibernate.cache.region.factory_class. The MultiplexedJBossCacheRegionFactory
    shares almost all its code with SharedJBossCacheRegionFactory; the main
    difference is it constructs a different CacheInstanceManager implementation -- the
    MultiplexedCacheInstanceManager.

Hibernate Second Level Caching in JBoss AS 5
Clustered JPA
http://opensourceframework.blogspot.com/2010/08/caching-queries-with-hibernatetemplate.html

----
---
ANish

Monday, August 30, 2010

named query in hibernate

Hibernate Named Queries Example
Using Named Query
named query example

Calling a named query
In Hibernate, the getNamedQuery() method obtains a Query instance for a named query:
session.getNamedQuery("findItemsByName")
.setString("desc", description);



Java
Persistence also supports named
queries
:
em.createNamedQuery("
findItemsByName").setParameter("desc",
description);

 


Named queries don't have to be HQL or JPA QL strings; they may even be native
SQL queries—and your Java code doesn't
need to know the difference:

<sql-query name="findItemsByName">
<return alias="item"
class="Item"/>
<![CDATA[
select {item.*}
from item where name like :desc
]]>
</sql-query>



named query with annotations

Assume you consider
a particular named query to belong to a particular entity class:

package auction.model

import ...;

@NamedQueries({

@NamedQuery(
name = "findItemsByName",
query = "select i from Item i where i.name like :name"
),
...
})
@Entity
@Table(name = "ITEM")
public class Item { ... }


Named Query Hibernate
hibernate named
query annotation
http://opensourceframework.blogspot.com/2010/07/hibernate-named-query-example.html



named query in hibernate


hibernate named query example


Anish

Caching queries with HibernateTemplate

hibernateTemplate 2nd level cache
Caching queries with HibernateTemplate
hibernateTemplate caching
Speed Up Your Hibernate Applications with Second-Level Caching
hibernate jboss cache guide

Hibernate Caching with JBOSS Treecache example
Hibernate Caching
=============================================================
 

=============================================================

The treecache.xml
<?xml version="1.0" encoding="UTF-8"?>
<server>
    <mbean code="org.jboss.cache.TreeCache" name="jboss.cache:service=TreeCache">
        <depends>jboss:service=TransactionManager</depends>
        <!-- Configure the TransactionManager -->
        <attribute name="TransactionManagerLookupClass">org.jboss.cache.JBossTransactionManagerLookup</attribute>
        <!-- Isolation level : SERIALIZABLE
                               REPEATABLE_READ (default)
                               READ_COMMITTED
                               READ_UNCOMMITTED
                               NONE
        -->
        <attribute name="IsolationLevel">REPEATABLE_READ</attribute>

        <!-- Valid modes are LOCAL, REPL_ASYNC and REPL_SYNC -->
        <attribute name="CacheMode">LOCAL</attribute>
       
        <!-- Just used for async repl: use a replication queue -->
        <attribute name="UseReplQueue">false</attribute>

        <!-- Replication interval for replication queue (in ms) -->
        <attribute name="ReplQueueInterval">0</attribute>

        <!-- Max number of elements which trigger replication -->
        <attribute name="ReplQueueMaxElements">0</attribute>

        <!-- Whether or not to fetch state on joining a cluster -->
        <attribute name="FetchStateOnStartup">true</attribute>

        <!-- The max amount of time (in milliseconds) we wait until the
             initial state (ie. the contents of the cache) are retrieved from
             existing members in a clustered environment
        -->
        <attribute name="InitialStateRetrievalTimeout">5000</attribute>

        <!-- Number of milliseconds to wait until all responses for a synchronous call have been received. -->
        <attribute name="SyncReplTimeout">15000</attribute>

        <!-- Max number of milliseconds to wait for a lock acquisition -->
        <attribute name="LockAcquisitionTimeout">15000</attribute>

        <!-- Name of the eviction policy class. -->
        <!--
        <attribute name="EvictionPolicyClass">org.jboss.cache.eviction.FIFOPolicy</attribute>
        -->
        <!--  Specific eviction policy configurations. This is LRU -->

        <attribute name="EvictionPolicyConfig">
          <config>
            <attribute name="wakeUpIntervalSeconds">5</attribute>
            <region name="/_default_">
             <attribute name="maxNodes">5000</attribute>
             <attribute name="timeToLiveSeconds">1000</attribute>
             <attribute name="maxAgeSeconds">120</attribute>
            </region>
            <region name="hibernate/HibernateLogEntryDao">
             <attribute name="maxNodes">5000</attribute>
             <attribute name="timeToLiveSeconds">1000</attribute>
            </region>
          </config>
        </attribute>

    </mbean>
</server>





=================================================
The treecache.xml,to be placed in the common location where log4j properties files are read


Jar's Needed Jboss-cache.jar and jgroups.jar and comman hibernate Jar's


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:jboss="http://www.springmodules.org/schema/jboss"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
                           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
                           http://www.springmodules.org/schema/jboss
                           http://www.springmodules.org/schema/cache/springmodules-jboss.xsd">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName"><value>oracle.jdbc.driver.OracleDriver</value></property>
        <property name="url"><value>jdbc:oracle:thin:@localhost:1521:XE</value></property>
        <property name="username"><value>smc</value></property>
        <property name="password"><value>smc</value></property>
        <property name="maxActive"><value>100</value></property>
        <property name="maxIdle"><value>30</value></property>
        <property name="maxWait"><value>1000</value></property>
        <property name="defaultAutoCommit"><value>false</value></property>
    </bean>

    <bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mappingLocations">
            <list>
                <value>classpath*:/dataaccess/hibernate/*.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
                <prop key="hibernate.cache.provider_class">org.hibernate.cache.TreeCacheProvider</prop>

                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
                <prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>
            </props>
        </property>
    </bean>

    <bean id="hibernateDaoSupport" abstract="true" class="org.springframework.orm.hibernate3.support.HibernateDaoSupport">
        <property name="sessionFactory" ref="hibernateSessionFactory"/>
    </bean>
 

    <bean id="templatelessLogEntryDao" class="com.apress.prospring2.ch11.dataaccess.hibernate.TemplatelessHibernateInvoiceLogEntryDao">
        <constructor-arg ref="hibernateSessionFactory"/>
    </bean>
 

  <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
     <bean id="lodDao" class="com.apress.prospring2.ch11.dataaccess.HiberNateDaoSupportIml">
         <property name="sessionFactory" ref="hibernateSessionFactory"/>
     </bean>
</beans>





Implementation Code:-

  public List<LogEntry> getAll() {
        System.out.println("GetAll Called");
        long start, end, total;
        start = System.currentTimeMillis();
        getHibernateTemplate().setQueryCacheRegion("HibernateLogEntryDao");
        getHibernateTemplate().setCacheQueries(true);

        List<LogEntry> returns=getHibernateTemplate().find("from LogEntry");
        end = System.currentTimeMillis();
        total = end - start;
        System.out.println("Totall-->>"+total);
        return returns;
       
    }





hibernateTemplate 2nd level cache

Caching queries with HibernateTemplate

hibernateTemplate caching

Speed Up Your Hibernate Applications with Second-Level Caching

hibernate jboss cache guide
Using treecache as 2nd level cache
JBoss Cache based Hibernate Second Level Cache provider

Sunday, August 29, 2010

Versioning without version numbers or timestamps Hibernate

Versioning without version numbers or timestamps in Hibernate
=============================================================

=============================================================
Application don't have version or timestamp columns, Hibernate can still perform automatic versioning, but only for objects that are retrieved and modified in the same persistence context (that is, the same Session). If you need optimistic locking for conversations implemented with detached objects, you must use a version number or timestamp that is transported with the detached object.
=============================================================

=============================================================
This alternative implementation of versioning checks the current database state against the unmodified values of persistent properties at the time the object was retrieved (or the last time the persistence context was flushed). You may enable this functionality by setting the optimistic-lock attribute on the class mapping:

<class name="Book" table="Book" optimistic-lock="all">
    <id .../>
    ...
</class>

=============================================================

=============================================================


Versioning with Java Persistence or JPA
 To enable automatic versioning for a particular entity, you need to add a version property or field:

@Entity
public class BOOK{
    ...
    @Version
    @Column(name = "VERSION")
    private int version;
    ...
}

======================================================================

=============================================================

=============================================================


Versoning Example In Hibernate
http://opensourceframework.blogspot.com/2010/07/hibernate-vesioning-example.html

Sunday, August 22, 2010

Improve Hibernate Speed

Improve Hibernate Speed

Ehcache is an open source widely used java distributed cache for general purpose caching, Java EE and light-weight containers. It features memory and disk stores, replicate by copy and invalidate, listeners, cache loaders, cache extensions, cache exception handlers, a gzip caching servlet filter, RESTful and SOAP APIs and much more. Ehcache is available under an Apache open source license and is actively supported

Hibernate Second Level Cache
Setting Ehcache as the Hibernate Second Level Cache

Hibernate 3.0 - 3.2
Use:

<property name="hibernate.cache.provider_class">
net.sf.ehcache.hibernate.EhCacheProvider
</property>

for instance creation, or

<property name="hibernate.cache.provider_class">
net.sf.ehcache.hibernate.SingletonEhCacheProvider
</property>

to force Hibernate to use a singleton Ehcache CacheManager.


For example to enable cache entries for the domain object
com.somecompany.someproject.domain.Country there would be a mapping file
something like the following:

<hibernate-mapping>

<class
name="com.somecompany.someproject.domain.Country"
table="ut_Countries"
dynamic-update="false"
dynamic-insert="false"
>
...
</class>
</hibernate-mapping>

This can also be achieved using the @Cache annotation, e.g.

@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Country { ... }


To enable caching, add the following element.

<cache usage="read-write|nonstrict-read-write|read-only" />

Using Query Caches
For example, let's say we have a common query running against the Country Domain.

Code to use a query cache follows:

public List getStreetTypes(final Country country) throws HibernateException {
final Session session = createSession();
try {
final Query query = session.createQuery(

"select st.id, st.name"
+ " from StreetType st "
+ " where st.country.id = :countryId "
+ " order by st.sortOrder desc, st.name");
query.setLong("countryId", country.getId().longValue());
query.setCacheable(true);
query.setCacheRegion("query.StreetTypes");
return query.list();
} finally {
session.close();
}
}

The query.setCacheable(true) line caches the query.

The query.setCacheRegion("query.StreetTypes") line sets the name of the Query Cache.
=========================================================================

Introduction to Hibernate Caching
Hibernate Performance Tuning
Hibernate Second Level Cache
Searches related to hibernate 2nd level cache
hibernate 2nd level cache spring modules
manipulating hibernate 2nd level cache
hibernate ehcache
spring modules cache java
nhibernate 2nd level cache
hibernate cache use second level cache
hibernate clear second level cache
for more information on ehCache

http://ehcache.org/documentation/hibernate.html

Friday, July 23, 2010

Hibernate Named Query Example

hibernate-mapping
query name="smc.Product.findProductTypeByName">from Producttype type where type.name=? order by type.name ASCSELECT t.value FROM TEXT t, POSTPAIDOPTIONGROUP g where t.textualdescription=g.name AND t.language = 0 AND t.media = 0 AND t.client = 0 AND t.touchpoint = 0 AND t.role = 0 order by t.value ASC sql-query


--Code Snippet
Query queryObject = null;
queryObject = getDBSession().getNamedQuery("Product.findProductTypeByName");
queryObject.setParameter(0, name);
List productTypeList = queryObject.list();




--code Sbippet
List groupName=getDBSession(userdto).getNamedQuery("Product.getGroupName").list();

HiberNate Named Query Example


from Producttype type where type.name=? order by type.name ASC
SELECT t.value FROM TEXT t, POSTPAIDOPTIONGROUP g where t.textualdescription=g.name AND t.language = 0 AND t.media = 0 AND t.client = 0 AND t.touchpoint = 0 AND t.role = 0 order by t.value ASC

Thursday, July 8, 2010

Hibernate Pagination Example

---- Anish Pagination Support contact anish2good@yahoo.co.in

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class HibernateResultDao extends HibernateDaoSupport implements ResultDao {

public ResultSearchResult search(final ResultSearchArgument a) {
return (ResultSearchResult) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query query;
ResultSearchResult result = new ResultSearchResult();
query = session.createQuery("from Result where name = :s");
query.setString("s", a.getS());
query.setFirstResult(a.getFirstResult());
query.setMaxResults(a.getMaxResults());
result.setResult(query.list());

query = session.createQuery("select count(*) from Result where name = :s");
query.setString("s", a.getS());
result.setTotalResults((Long)query.uniqueResult());

return result;
}
});
}


hibernate pagination query
spring hibernate pagination
hibernate paging query
hibernate scrollable

Hibernate one to Many Example

Hibernate one Many Example

hibernate one-to-many



=============================================================
 

=============================================================

<?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">
<!--
    Anish
-->
<hibernate-mapping>
    <class name="session.Student" table="STUDENT" schema="RUBY">
        <id name="id" type="java.lang.Long">
            <column name="ID" precision="22" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" length="10" />
        </property>
        <set name="subjects" inverse="true">
            <key>
                <column name="EMPID" precision="22" scale="0" />
            </key>
            <one-to-many class="session.Subject" />
        </set>
    </class>
</hibernate-mapping>



<?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">
<!--
    ANish
-->
<hibernate-mapping>
    <class name="session.Subject" table="SUBJECT" schema="RUBY">
        <id name="id" type="java.lang.Long">
            <column name="ID" precision="22" scale="0" />
            <generator class="assigned" />
        </id>
        <many-to-one cascade="save-update" name="student" class="session.Student" fetch="select">
            <column name="EMPID" precision="22" scale="0" />
        </many-to-one>
        <property name="name" type="java.lang.String">
            <column name="NAME" length="10" />
        </property>
    </class>
</hibernate-mapping>

 

 
related
Relation One to Many  Hibernate  Java
hibernate one-to-many
hibernate one-to-many list
hibernate one-to-many set
hibernate one-to-many example
hibernate one-to-many cascade
hibernate one-to-many annotation
hibernate one-to-one
hibernate many-to-many
hibernate many to one cascade
ANish



public class Student implements java.io.Serializable {

// Fields

private Long id;
private String name;
private Set subjects = new HashSet(0);

// Constructors

/** default constructor */
public Student() {
}

/** minimal constructor */
public Student(Long id) {
this.id = id;
}

/** full constructor */
public Student(Long id, String name, Set subjects) {
this.id = id;
this.name = name;
this.subjects = subjects;
}

// Property accessors

public Long getId() {
return this.id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

public Set getSubjects() {
return this.subjects;
}

public void setSubjects(Set subjects) {
this.subjects = subjects;
}

}


public class Subject implements java.io.Serializable {

// Fields

private Long id;
private Student student;
private String name;

// Constructors

/** default constructor */
public Subject() {
}

/** minimal constructor */
public Subject(Long id) {
this.id = id;
}

/** full constructor */
public Subject(Long id, Student student, String name) {
this.id = id;
this.student = student;
this.name = name;
}

// Property accessors

public Long getId() {
return this.id;
}

public void setId(Long id) {
this.id = id;
}

public Student getStudent() {
return this.student;
}

public void setStudent(Student student) {
this.student = student;
}

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}



}

Hibernate EmptyInterceptor Example

/**
* @author NathA1
*/
public class EntryInterceptor extends EmptyInterceptor {
/*
* @see org.hibernate.EmptyInterceptor#onSave(java.lang.Object, java.io.Serializable, java.lang.Object[], java.lang.String[], org.hibernate.type.Type[])
*/
@Override
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
final Date now = new Date();
final String loginUserName ="NathA1";
setValue(state, propertyNames, "datecreation", now);
setValue(state, propertyNames, "usercreation", loginUserName);
setValue(state, propertyNames, "dateupd", now);
setValue(state, propertyNames, "userupd", loginUserName);
return true;
}

/*
* @see org.hibernate.EmptyInterceptor#onFlushDirty(java.lang.Object, java.io.Serializable, java.lang.Object[], java.lang.Object[], java.lang.String[], org.hibernate.type.Type[])
*/
@Override
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
final Date now = new Date();
final String loginUserName ="NathA1";
setValue(currentState, propertyNames, "dateupd", now);
setValue(currentState, propertyNames, "userupd", loginUserName);
return true;
}

/**
* Sets the value.
*
* @param currentState the current state
* @param propertyNames the property names
* @param propertyToSet the property to set
* @param value the value
*/
private void setValue(Object[] currentState, String[] propertyNames, String propertyToSet, Object value) {
for (int i = 0; i < propertyNames.length; i++) {
if (propertyNames[i].equalsIgnoreCase(propertyToSet)) {
currentState[i] = value;
}
}
}

}

Hibernate versioning Example

The <version> element is optional and indicates that the table contains versioned data. This is
particularly useful if you plan to use long transactions.

<version
column="version_column"
name="propertyName"
type="typename"
access="field|property|ClassName"
unsaved-value="null|negative|undefined"
generated="never|always"
insert="true|false"
node="element-name|@attribute-name|element/@attribute|."
/>

Version numbers can be of Hibernate type long, integer, short, timestamp or calendar.
A version or timestamp property should never be null for a detached instance. Hibernate will detect
any instance with a null version or timestamp as transient, irrespective of what other unsavedvalue
strategies are specified. Declaring a nullable version or timestamp property is an easy way
to avoid problems with transitive reattachment in Hibernate. It is especially useful for people using
assigned identifiers or composite key

<?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="session.Writer" table="WRITER" schema="SMC">
<id name="id" type="java.lang.Long">
<column name="ID" precision="22" scale="0" />
<generator class="increment" />
</id>
<version name="version" type="java.lang.Long">
<column name="VERSION" precision="22" scale="0" />
</version>
<property name="name" type="java.lang.String">
<column name="NAME" length="20" />
</property>
</class>
</hibernate-mapping>

=============================================================

=============================================================

public class Writer implements java.io.Serializable {

// Fields

private Long id;
private Long version;
private String name;

// Constructors

/** default constructor */
public Writer() {
}

/** full constructor */
public Writer(String name) {
this.name = name;
}

// Property accessors

public Long getId() {
return this.id;
}

public void setId(Long id) {
this.id = id;
}

public Long getVersion() {
return this.version;
}

public void setVersion(Long version) {
this.version = version;
}

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

}


=============================================================

=============================================================
Hibernate Automatic Versioning
How to do optimistic locking in Spring
Optimistic Locking and Versioning in Hibernate
StaleObjectState Excption