简体   繁体   中英

Java Hibernate - Composite Primary Key Issue

I have following two tables

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

CREATE TABLE event_master ( Event_Code varchar(128) NOT NULL, Event_Type_Code varchar(128) NOT 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:-

@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) {
   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;
}

}

EventMasterId Class for Compound Primary Key setting:-

@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) { ........ }

public int hashCode() { .......... }
}

EventTypeMaster Class

@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;
}

@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

    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.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.ja va: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.

I think you have a typo.

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

Should the first line be key1.setEventTypeCode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM