У меня есть следующие две таблицы
CREATE TABLE event_type_master (
Event_Type_Code varchar (128) NOT NULL,
ПЕРВИЧНЫЙ КЛЮЧ (Event_Type_Code)
)
CREATE TABLE event_master (
Код события varchar (128) NOT NULL,
Event_Type_Code varchar (128) NOT NULL,
ПЕРВИЧНЫЙ КЛЮЧ (Event_Code, Event_Type_Code),
CONSTRAINT FK1 FOREIGN KEY (Event_Type_Code) ССЫЛКИ event_type_master (Event_Type_Code)
)
Теперь я создал классы моделей для вышеуказанного отношения следующим образом
Класс EventMaster: -
@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 для настройки составного первичного ключа: -
@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;
}
}
После настройки All я создал класс HebernateUtil, используя Netbeans для подключения к HibernateSession Factory, и попытался проверить добавление записи в таблицу event_master следующим образом
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();
}
Но я получаю следующее сообщение об ошибке
Hibernate: вставить в event_master (Create_DTTM, Created_By, Event_Desc, Event_Name, Event_Short_Name, Last_Mod_By, Last_Mod_DTTM, Event_Code, Event_Type_Code) значения (?,?,?,?,?,?,?,?,?,?,?,?,?
1473 [main] WARN org.hibernate.util.JDBCExceptionReporter - Ошибка SQL: 1048, SQLState: 23000
1473 [main] ОШИБКА org.hibernate.util.JDBCExceptionReporter - Столбец Event_Type_Code не может быть пустым
1474 [main] ОШИБКА org.hibernate.event.def.AbstractFlushingEventListener - Не удалось синхронизировать состояние базы данных с сеансом
org.hibernate.exception.ConstraintViolationException: не удалось выполнить пакетное обновление JDBC
org.hibernate.exception.ConstraintViolationException: не удалось выполнить пакетное обновление JDBC
в org.hibernate.exception.SQLStateConverter.convert (SQLStateConverter.java:94)
в org.hibernate.exception.JDBCExceptionHelper.convert (JDBCExceptionHelper.java:66)
в org.hibernate.jdbc.AbstractBatcher.executeBatch (AbstractBatcher.java:275)
в org.hibernate.engine.ActionQueue.executeActions (ActionQueue.java:266)
в org.hibernate.engine.ActionQueue.executeActions (ActionQueue.java:167)
в org.hibernate.event.def.AbstractFlushingEventListener.performExecutions (AbstractFlushingEventListener.java:321)
в org.hibernate.event.def.DefaultFlushEventListener.onFlush (DefaultFlushEventListener.java:50)
в org.hibernate.impl.SessionImpl.flush (SessionImpl.java:1028)
в org.hibernate.impl.SessionImpl.managedFlush (SessionImpl.java:366)
в org.hibernate.transaction.JDBCTransaction.commit (JDBCTransaction.java:137)
at test.NewMain.main (NewMain.java:46)
Причина: java.sql.BatchUpdateException: столбец Event_Type_Code не может быть пустым
at com.mysql.jdbc.PreparedStatement.executeBatchSerially (PreparedStatement.java:1666)
в com.mysql.jdbc.PreparedStatement.executeBatch (PreparedStatement.java:1082)
в org.hibernate.jdbc.BatchingBatcher.doExecuteBatch (BatchingBatcher.java:70)
в org.hibernate.jdbc.AbstractBatcher.executeBatch (AbstractBatcher.java:268)
Пожалуйста, помогите мне решить эту проблему.