-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: One Composite Key as Foreign Key
PostPosted: Thu Apr 07, 2011 11:18 pm 
Newbie

Joined: Thu Apr 07, 2011 10:59 pm
Posts: 2
I have following two tables

CREATE TABLE event_type_master (
Event_Type_Code varchar(128) NOT NULL,
Event_Type_Name varchar(128) DEFAULT NULL,
PRIMARY KEY (Event_Type_Code),
UNIQUE KEY Event_Type_Code (Event_Type_Code)
)

CREATE TABLE event_master (
Event_Code varchar(128) NOT NULL,
Event_Type_Code varchar(128) NOT NULL,
Event_Name varchar(128) DEFAULT NULL,
PRIMARY KEY (Event_Code,Event_Type_Code),
CONSTRAINT FK1 FOREIGN KEY (Event_Type_Code) REFERENCES event_type_master (Event_Type_Code)
)


Now I have create model classes for the above relation as follow

EventMaster Class
Code:
@Entity
@Table(name="event_master")
public class EventMaster  implements java.io.Serializable {

     private EventMasterId id;
     private EventTypeMaster eventTypeMaster;
     private String eventName;

    public EventMaster() {
    }
   
    public EventMaster(EventMasterId id, EventTypeMaster eventTypeMaster) {
        this.id = id;
        this.eventTypeMaster = eventTypeMaster;
    }
    public EventMaster(EventMasterId id, EventTypeMaster eventTypeMaster, String eventName) {
       this.id = id;
       this.eventTypeMaster = eventTypeMaster;
       this.eventName = eventName;
    }
   
    @EmbeddedId   
    @AttributeOverrides( {
    @AttributeOverride(name="eventCode", column=@Column(name="Event_Code", nullable=false, length=128) ),
    @AttributeOverride(name="eventTypeCode", column=@Column(name="Event_Type_Code", nullable=false, length=128) ) } )
    public EventMasterId getId() {
        return this.id;
    }
   
    public void setId(EventMasterId id) {
        this.id = id;
    }
   
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="Event_Type_Code",referencedColumnName = "Event_Type_Code",  nullable=false, insertable=false, updatable=false)
    public EventTypeMaster getEventTypeMaster()
    {
        return this.eventTypeMaster;
    }
   
    public void setEventTypeMaster(EventTypeMaster eventTypeMaster) {
        this.eventTypeMaster = eventTypeMaster;
    }
   
    @Column(name="Event_Name", length=128)
    public String getEventName() {
        return this.eventName;
    }
   
    public void setEventName(String eventName) {
        this.eventName = eventName;
    }
}


EventMasterId Class for Compound Primary Key setting
Code:
@Embeddable
public class EventMasterId  implements java.io.Serializable {


     private String eventCode;
     private String eventTypeCode;

    public EventMasterId() {
    }

    public EventMasterId(String eventCode, String eventTypeCode)
    {
       this.eventCode = eventCode;
       this.eventTypeCode = eventTypeCode;
    }
   

    @Column(name="Event_Code", nullable=false, length=128)
    public String getEventCode() {
        return this.eventCode;
    }
   
    public void setEventCode(String eventCode) {
        this.eventCode = eventCode;
    }

    @Column(name="Event_Type_Code", nullable=false, length=128)
    public String getEventTypeCode() {
        return this.eventTypeCode;
    }
   
    public void setEventTypeCode(String eventTypeCode) {
        this.eventTypeCode = eventTypeCode;
    }


   public boolean equals(Object other) {
         if ( (this == other ) ) return true;
       if ( (other == null ) ) return false;
       if ( !(other instanceof EventMasterId) ) return false;
       EventMasterId castOther = ( EventMasterId ) other;
         
       return ( (this.getEventCode()==castOther.getEventCode()) || ( this.getEventCode()!=null && castOther.getEventCode()!=null && this.getEventCode().equals(castOther.getEventCode()) ) )
&& ( (this.getEventTypeCode()==castOther.getEventTypeCode()) || ( this.getEventTypeCode()!=null && castOther.getEventTypeCode()!=null && this.getEventTypeCode().equals(castOther.getEventTypeCode()) ) );
   }
   
   public int hashCode() {
         int result = 17;
         
         result = 37 * result + ( getEventCode() == null ? 0 : this.getEventCode().hashCode() );
         result = 37 * result + ( getEventTypeCode() == null ? 0 : this.getEventTypeCode().hashCode() );
         return result;
   }   


}


EventTypeMaster Class
Code:
@Entity
@Table(name="event_type_master")
public class EventTypeMaster  implements java.io.Serializable {
     private String eventTypeCode;
     private String eventTypeName;
     private Set<EventMaster> eventMasters = new HashSet<EventMaster>(0);

    public EventTypeMaster() {
    }

   
    public EventTypeMaster(String eventTypeCode) {
        this.eventTypeCode = eventTypeCode;
    }
    public EventTypeMaster(String eventTypeCode, String eventTypeName, Set eventMasters) {
       this.eventTypeCode = eventTypeCode;
       this.eventTypeName = eventTypeName;
       this.eventMasters = eventMasters;
    }
   
    @Id   
    @Column(name="Event_Type_Code", unique=true, nullable=false, length=128)
    public String getEventTypeCode() {
        return this.eventTypeCode;
    }
   
    public void setEventTypeCode(String eventTypeCode) {
        this.eventTypeCode = eventTypeCode;
    }
   
    @Column(name="Event_Type_Name", length=128)
    public String getEventTypeName() {
        return this.eventTypeName;
    }
   
    public void setEventTypeName(String eventTypeName) {
        this.eventTypeName = eventTypeName;
    }
   
    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="eventTypeMaster")
    @JoinColumn(name="Event_Type_Code", referencedColumnName = "Event_Type_Code")
    public Set<EventMaster> getEventMasters() {
        return this.eventMasters;
    }
   
    public void setEventMasters(Set<EventMaster> eventMasters) {
        this.eventMasters = eventMasters;
    }




}






After setting All I created a HebernateUtil Class using Netbeans to connect to HibernateSession Factory and tried to Test adding a record to event_master table as follow

Code:
Session session = null;
        session = NewHibernateUtil.getSessionFactory().getCurrentSession();
       
        try {
            org.hibernate.Transaction tx = session.beginTransaction();
            EventMasterId key1=new EventMasterId();
            EventTypeMaster eTypeMaster1=new EventTypeMaster();
           
            eTypeMaster1=(EventTypeMaster)session.load(EventTypeMaster.class, "e1");

            key1.setEventCode(eTypeMaster1.getEventTypeCode());
            key1.setEventCode("Test_Event_Code");

            EventMaster em=new EventMaster();
            em.setId(key1);
            em.setEventTypeMaster(eTypeMaster1);
            em.setEventName("Test Event Name");
            em.setEventDesc("Event Description");
       
       
            session.save(em);
       
            session.getTransaction().commit();

        } catch (Exception e) {
            e.printStackTrace();
        }


But I am getting following Error


Hibernate: insert into event_master (Create_DTTM, Created_By, Event_Desc, Event_Name, Event_Short_Name, Last_Mod_By, Last_Mod_DTTM, Event_Code, Event_Type_Code) values (?, ?, ?, ?, ?, ?, ?, ?, ?)
1473 [main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1048, SQLState: 23000
1473 [main] ERROR org.hibernate.util.JDBCExceptionReporter - Column 'Event_Type_Code' cannot be null
1474 [main] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1028)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:366)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
at test.NewMain.main(NewMain.java:46)
Caused by: java.sql.BatchUpdateException: Column 'Event_Type_Code' cannot be null
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1666)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1082)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)


Please help me to solve this.


Top
 Profile  
 
 Post subject: Re: One Composite Key as Foreign Key
PostPosted: Fri Apr 08, 2011 1:00 am 
Newbie

Joined: Thu Apr 07, 2011 10:59 pm
Posts: 2
There is a mistake. I solved it. Thanks


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.