SDSU Emerging Technology
Fall Semester, 2004
One-to-One Mapping
Previous     Lecture Notes Index     Next     
© 2004, All Rights Reserved, SDSU & Roger Whitney
San Diego State University -- This page last updated 18-Nov-04

CS 683 Emerging Technologies Fall Semester, 2004 Doc 29 One-to-One Mapping

Contents

Using the Class database Account

One-to-one Mapping Example

Database

People Class

Address Class

People.hbm.xml

Main.java

hibernate.properties

Glorp Version

Copyright ©, All rights reserved. 2004 SDSU & Roger Whitney, 5500 Campanile Drive, San Diego, CA 92182-7700 USA. OpenContent ( http://www.opencontent.org/opl.shtml) license defines the copyright on this document

Using the Class database Account

From Glorp

login := Login new database: PostgreSQLPlatform new;
   username: 'yourUserName';
   password: 'yourPassword';
   connectString: 'bismarck.sdsu.edu_yourUserName'.

Hibernate

## PostgreSQL
   
hibernate.dialect net.sf.hibernate.dialect.PostgreSQLDialect
hibernate.connection.driver_class org.postgresql.Driver
hibernate.connection.url jdbc:postgresql://bismarck.sdsu.edu/yourUserName
hibernate.connection.username yourUserName
hibernate.connection.password yourPassword

jdbc

   public static Connection getJdbcConnection() throws Exception {
      String dbUrl = " jdbc:postgresql://bismarck.sdsu.edu/yourUserName ";
      String user = " yourUserName";
      String password = " yourPassword ";
      Class.forName("org.postgresql.Driver");
      return DriverManager.getConnection( dbUrl, user, password);
   }

For Hibernate & JDBC the postgeSQL jdbc driver must be in your classpath

One-to-one Mapping Example

Hibernate

Each Person has one Address

Database

SQL used to create tables

CREATE TABLE PEOPLE (
   ID serial NOT NULL ,
   FIRST_NAME varchar(50) NULL ,
   LAST_NAME varchar(50) NULL ,
   ADDRESS_ID int4 NULL , 
   CONSTRAINT PEOPLE_PK PRIMARY KEY  (id),
   CONSTRAINT PEOPLE_UNIQ UNIQUE  (id))
   
CREATE TABLE ADDRESSES (
   STREET varchar(50) NULL ,
   CITY varchar(50) NULL ,
   ID serial NOT NULL , 
   CONSTRAINT ADDRESSES_PK PRIMARY KEY  (id),
   CONSTRAINT ADDRESSES_UNIQ UNIQUE  (id))

People Class

package cs683;
   
public class People {
   String firstName;
   String lastName;
   Address address;
   long id;
   
   public People () {   }
   
   public People(String first, String last) {
      firstName = first;
      lastName = last;
   }
   
   public String getLastName() {   return lastName; }
   
   public String getFirstName() {   return firstName; }
   
   public void setFirstName( String name) {firstName = name; }
   
   public void setLastName( String name) { lastName = name; }
   
   public long getId() {   return id; }
   
   public void setId(long l) {id = l; }
   public String toString() {
      return firstName + " " + lastName + id;
   }
   public Address getAddress() {   return address; }
   public void setAddress(Address address) { this.address = address; }
}

Address Class

package cs683;
   
public class Address {
   String street;
   String city;
   long id;
   
   public String getCity() {
      return city;
   }
   
   public void setCity(String city) {
      this.city = city;
   }
   public long getId() {
      return id;
   }
   public void setId(long id) {
      this.id = id;
   }
   public String getStreet() {
      return street;
   }
   public void setStreet(String street) {
      this.street = street;
   }
}

People.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
   
<hibernate-mapping package="cs683">
   <class
      name="People"
      table="people" >
      <id
         name="id"
         type="long"
         column="id" >
         <generator class="increment"/>
      </id>
   
      <many-to-one name="address" class="cs683.Address" column="address_id" 
         unique="true" cascade="all"  />
   
      <property
         name="lastName"
         column="last_name"
         type="string"
         not-null="false"
         length="50" />
      <property
         name="firstName"
         column="first_name"
         type="string"
         not-null="false"
         length="50" />

People.hbm.xml Continued


   </class>
   <class
      name="Address"
      table="addresses"
   >
      <id
         name="id"
         type="long"
         column="id"
      >
         <generator class="increment"/>
      </id>
   
      <property
         name="street"
         column="street"
         type="string"
         not-null="false"
         length="50"
      />
      <property
         name="city"
         column="city"
         type="string"
         not-null="false"
         length="50"
      />
      
   </class>
</hibernate-mapping>

Main.java

package cs683;
   
import java.util.List;
   
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.MappingException;
import net.sf.hibernate.Query;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;
   
public class Main {
   public static void main(String[] args) throws Exception {
      System.out.println("Start");
      sampleRead();
   }
   
   static void sampleRead() throws 
         MappingException, HibernateException, Exception {
      Session session = getHibernateSession();   
      Query getFrost =  session.createQuery("from People p where p.lastName = :var1 " );
      getFrost.setString("var1", "Whitney");
      List result = getFrost.list();
      System.out.println("Number of Objects: " + result.size());
      System.out.println(result.get(0));
      session.close();
   }

Main Continued

   static Session getHibernateSession() throws 
         MappingException, HibernateException, Exception {
      Configuration config = new Configuration();
      config.addClass(cs683.People.class);
      SessionFactory sessions = config.buildSessionFactory();
      Session session = sessions.openSession();
      return session;
   }
   
}

hibernate.properties

# PostgreSQL
   
hibernate.dialect net.sf.hibernate.dialect.PostgreSQLDialect
hibernate.connection.driver_class org.postgresql.Driver
hibernate.connection.url jdbc:postgresql://bismarck.sdsu.edu/cs683whitney
hibernate.connection.username cs683whitney
hibernate.connection.password secret
hibernate.query.substitutions yes
   
hibernate.connection.pool_size 2
   
hibernate.dialect=net.sf.hibernate.dialect.PostgreSQLDialect
hibernate.c3p0.max_size 2
hibernate.c3p0.min_size 2
hibernate.c3p0.timeout 5000
hibernate.c3p0.max_statements 100
hibernate.c3p0.idle_test_period 3000
hibernate.c3p0.acquire_increment 2
hibernate.c3p0.validate false

Glorp Version

Smalltalk defineClass: #Person
   superclass: #{Core.Object}
   indexedType: #none
   private: false
   instanceVariableNames: 'firstName lastName id address '
   classInstanceVariableNames: ''
   imports: ''
   category: 'GlorpExperiments'

Smalltalk defineClass: #Address
   superclass: #{Core.Object}
   indexedType: #none
   private: false
   instanceVariableNames: 'street city id '
   classInstanceVariableNames: ''
   imports: ''
   category: 'GlorpExperiments'

These classes have the standard accessor methods

Descriptor

Smalltalk defineClass: #GlorpTutorialDescriptor
   superclass: #{Glorp.DescriptorSystem}
   indexedType: #none
   private: false
   instanceVariableNames: ''
   classInstanceVariableNames: ''
   imports: '
         Glorp.*
         '
   category: 'GlorpExperiments' 
   
GlorpTutorialDescriptor >>allTableNames
   ^#( 'PEOPLE' 'ADDRESSES' ) 
   
GlorpTutorialDescriptor >>constructAllClasses
   ^(super constructAllClasses)
      add: Person;
      add: Address;
      yourself 
   
GlorpTutorialDescriptor >>tableForADDRESSES: aTable 
   aTable createFieldNamed: 'street' type: (platform varChar: 50).
   (aTable createFieldNamed: 'city' type: (platform varChar: 50)).
   (aTable createFieldNamed: 'id' type: platform sequence) bePrimaryKey 

GlorpTutorialDescriptor >>tableForPEOPLE: aTable 
   | addressId |
   (aTable createFieldNamed: 'id' type: platform sequence) bePrimaryKey.
   (aTable createFieldNamed: 'first_name' type: (platform varChar: 50)).
   (aTable createFieldNamed: 'last_name' type: (platform varChar: 50)).
   addressId := aTable createFieldNamed: 'address_id' type: platform int4.
   aTable addForeignKeyFrom: addressId to: ((self tableNamed: 'ADDRESSES') fieldNamed: 'id').   
   
GlorpTutorialDescriptor >>descriptorForAddress: aDescriptor 
   | table |
   table := self tableNamed: 'ADDRESSES'.
   aDescriptor table: table.
   (aDescriptor newMapping: DirectMapping) from: #street
      to: (table fieldNamed: 'street').
   (aDescriptor newMapping: DirectMapping) from: #city
      to: (table fieldNamed: 'city').
   (aDescriptor newMapping: DirectMapping) 
      from: #id
      to: (table fieldNamed: 'id'). 

GlorpTutorialDescriptor >>descriptorForPerson: aDescriptor 
   | personTable |
   personTable := self tableNamed: 'PEOPLE'.
   aDescriptor table: personTable.
   (aDescriptor newMapping: DirectMapping) 
      from: #firstName
      to: (personTable fieldNamed: 'first_name').
   (aDescriptor newMapping: DirectMapping) 
      from: #lastName
      to: (personTable fieldNamed: 'last_name').
   (aDescriptor newMapping: DirectMapping) 
      from: #id
      to: (personTable fieldNamed: 'id').
   (aDescriptor newMapping: OneToOneMapping)
         attributeName: #address. 
   
GlorpTutorialDescriptor >>classModelForAddress: aClassModel
   aClassModel newAttributeNamed: #id.
   aClassModel newAttributeNamed: #street.
   aClassModel newAttributeNamed: #city. 
   
GlorpTutorialDescriptor >>classModelForPerson: aClassModel
   aClassModel newAttributeNamed: #id.
   aClassModel newAttributeNamed: #firstName.
   aClassModel newAttributeNamed: #lastName.
   aClassModel newAttributeNamed: #address type: Address. 

Sample Login without Table Creation

login := Login new database: PostgreSQLPlatform new;
   username: 'cs683whitney';
   password: 'secret';
   connectString: 'bismarck.sdsu.edu_cs683whitney'.
   
accessor := DatabaseAccessor forLogin: login.
accessor login.
   
session := GlorpSession new.
session system: (GlorpTutorialDescriptor forPlatform: login database).
session accessor: accessor.
   
session beginUnitOfWork.
person := Person first: 'Sam' last: 'Whitney'.
address := Address new.
address
   street: 'Maple';
   city: 'SD'.
person address: address.
session register: person.
session commitUnitOfWork

Previous     visitors since 18-Nov-04     Next