Hibernate Coding

August 7, 2017 | Author: lcbk2133 | Category: Data, Computer Data, Computing, Technology, Data Management
Share Embed Donate


Short Description

Download Hibernate Coding...

Description

1. Simple Example

username jdbc:oracle:thin:username/password@localhost:1521/XE org.hibernate.dialect.Oracle9Dialect MyDriver password oracle.jdbc.driver.OracleDriver Simple.hbm.xml :

Client class import org.hibernate.*; import org.hibernate.cfg.*; import org.hibernate.transaction.*; public class mainSimple { public mainSimple() { // TODO Auto-generated constructor stub } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub SessionFactory sf = new Configuration().configure(). buildSessionFactory(); Session ses = sf.openSession(); Transaction tx = ses.beginTransaction(); Simple sob=new Simple(); Sob.setId(21); Sob.setName(“LCBK Raju”); Ses.save(sob); Tx.close(); Ses.close(); } } 2. Create session factory: a. SessionFactory sessions = new Configuration() .addResource("hello/Message.hbm.xml") .setProperties( System.getProperties() ) .buildSessionFactory(); b. SessionFactory sessions = new Configuration() .addClass(org.hibernate.auction.model.Item.class) .addClass(org.hibernate.auction.model.Category.class) .addClass(org.hibernate.auction.model.Bid.class) .setProperties( System.getProperties() ) .buildSessionFactory();

c. d.

addjar SessionFactory Configuration().configure(“/aaa/bbb.xml”)…. e. General Way(hibernate.config.xml as config file) SessionFactory Configuration().configure().buildsessionFactory();

ses=new ses=new

3.c3po connection pooling settings hibernate.connection.driver_class = oracle.jdbc.driver.OracleDriver hibernate.connection.url jdbc:oracle:thin:username/password@localhost:1521/XE hibernate.connection.username = auctionuser hibernate.connection.password = secret hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect hibernate.c3p0.min_size=5 hibernate.c3p0.max_size=20 hibernate.c3p0.timeout=300 hibernate.c3p0.max_statements=50 hibernate.c3p0.idle_test_period=3000

=

4. Container managed hibernate.properties hibernate.connection.datasource = java:/comp/env/jdbc/AuctionDB hibernate.transaction.factory_class = \ net.sf.hibernate.transaction.JTATransactionFactory hibernate.transaction.manager_lookup_class = \ net.sf.hibernate.transaction.JBossTransactionManagerLookup hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect 5. true// generated SQL to console

logging

6.Session Factory Class example a. package src2; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; /** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */

all

public class HibernateSessionFactory { /** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal threadLocal = new ThreadLocal(); private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; static { try { configuration.configure(configFile); sessionFactory configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error SessionFactory %%%%"); e.printStackTrace(); } } private HibernateSessionFactory() { }

=

Creating

/** * Returns the ThreadLocal Session instance. Lazy initialize * the SessionFactory if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) {

if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory sessionFactory.openSession() : null; threadLocal.set(session); }

!=

null)

?

return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error SessionFactory %%%%"); e.printStackTrace(); } }

=

Creating

/** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /**

* return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return session factory * * session factory will be rebuilded in the next call */ public static void setConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile; sessionFactory = null; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; } } b. Get Session Factory Session ses=HibernateSessionfactory.getSession(); 8. Hibernate uses reflection in mappings a. the following mappings are equivalent: b. u can omit column if pojo property name column name are same. c. d. derived properties e. U don’t required POJO f. g. class level setting ... h. If the complete class is immutable, set the immutable="false" in the class mapping i. Quoted properties j. Naming Strategy ---- Add Notes k. Schema 1. ... 2. .. L. 9. a. Hibernate exposes database identity to the application in two ways: ■ The value of the identifier property of a persistent instance ■ The value returned by Session.getIdentifier(Object o) b. Choosing Primary Key

XXX: assigned, native, identity, hilo, sequence, increment, uuid.hex 10. An object of entity type have DB identity. An object of value type does not have DB identity. 11. Composition: Life cycle of part dependent on life cycle of the whole. Hibernate uses term component for a user defined class that is persisted to same table as owning entity. For an example User class(Entity type), Address Class(Value type) // reusing component ……………………………………… ……………………………… Table would be userId, username, off_street,off_fno, home_street, home_fno (office address) (home address) components For bi-directional composition we need to do //tell the parent So we can call Adress.getUser() now. Limitations: 1. shared references are not possible because only user can acess it. 2. If u store a component with null values then hibernate returns a null component. 12. 3 different approaches to representing inheritance hierarchy. a. Table per class: No polymorphism,

Associations Hibernate Associations are inherently unidirectional. ManyToOne: UnDirectional public class Bid { ... private Item item; public void setItem(Item item) { this.item = item; } public Item getItem() { return item; } ... } Next, here’s the Hibernate mapping for this association: ... This mapping is called a unidirectional many-to-one association. The column ITEM_ID in the BID table is a foreign key to the primary key of the ITEM table. ManyToOne Bidirectional: public class Item { ... private Set bids = new HashSet(); public void setBids(Set bids) { this.bids = bids; } public Set getBids() { return bids; } public void addBid(Bid bid) { bid.setItem(this); bids.add(bid); }

... } Basic One to Many Mapping. ...

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF