我正在使用休眠站点上的 hibernate_reference.pdf 使用休眠多对多关联。我正在使用文档中描述的相同实体 Event.java 和 Person.java。
我看到许多人面临“无法初始化集合异常”并且许多人解决了这个问题,但堆栈溢出帖子中提到的解决方案都没有解决我的问题。可能是这些解决方案不适用于多对多关联,或者我的配置有问题。以下是我的 hbm.xml 文件:
事件.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="roseindia.tutorial.hibernate">
<class name="Event" table="EVENTS">
<id name="id" column="EVENT_ID">
<generator class="native" />
</id>
<property name="date" type="timestamp" column="EVENT_DATE" />
<property name="title" type="string" />
<property name="location" type="string" column="LOC" />
<set name="participants" table="PERSON_EVENT" inverse="true" lazy="false" cascade="all" >
<key column="EVENT_ID" not-null="true" />
<many-to-many column="PERSON_ID" class="Person" />
</set>
</class>
</hibernate-mapping>
事件.java
public class Event implements java.io.Serializable {
private long id;
private String title;
private Date date;
private String location;
public Event() {
//participants = new HashSet<Person>(0);
}
private Set participants = new HashSet(0);
public Set getParticipants() {
return participants;
}
public void setParticipants(Set participants) {
this.participants = participants;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((date == null) ? 0 : date.hashCode());
//result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result
+ ((location == null) ? 0 : location.hashCode());
//result = prime * result + ((participants == null) ? 0 : participants.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Event other = (Event) obj;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (location == null) {
if (other.location != null)
return false;
} else if (!location.equals(other.location))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
@SuppressWarnings("unchecked")
public void addToParticipants(Person person) {
this.getParticipants().add(person);
//person.addToEvent(this);
person.getEvents().add(this);
}
public void removeFromParticipants(Person person) {
this.getParticipants().remove(this);
person.getEvents().remove(person);
}
public long getId() {
return id;
}
private void setId(long id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLocation() {
return this.location;
}
public void setLocation(String location) {
this.location = location;
}
}
人.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="roseindia.tutorial.hibernate">
<class name="Person" table="PERSON">
<id name="id" column="PERSON_ID">
<generator class="native" />
</id>
<property name="age" />
<property name="firstname" />
<property name="lastname" />
<set name="events" table="PERSON_EVENT" inverse="false" lazy="true" cascade="all" >
<key column="PERSON_ID" not-null="true" />
<many-to-many column="EVENT_ID" class="Event" />
</set>
<set name="emailAddresses" table="PERSON_EMAIL_ADDR">
<key column="PERSON_ID" />
<element type="string" column="EMAIL_ADDR" />
</set>
</class>
</hibernate-mapping>
人.java
import java.util.HashSet;
import java.util.Set;
public class Person implements java.io.Serializable {
private Set events = new HashSet<Event>();
private Set emailAddresses = new HashSet();
public Set getEmailAddresses() {
return emailAddresses;
}
public void setEmailAddresses(Set emailAddresses) {
this.emailAddresses = emailAddresses;
}
public void addToEvent(Event event) {
this.getEvents().add(event);
//event.addToParticipants(this);
event.getParticipants().add(this);
}
public void removeFromEvent(Event event) {
this.getEvents().remove(event);
//event.removeFromParticipants(this);
event.getParticipants().remove(this);
}
public Set getEvents() {
return events;
}
public void setEvents(Set events) {
this.events = events;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int getAge() {
return age;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result
+ ((firstname == null) ? 0 : firstname.hashCode());
result = prime * result
+ ((lastname == null) ? 0 : lastname.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (firstname == null) {
if (other.firstname != null)
return false;
} else if (!firstname.equals(other.firstname))
return false;
if (lastname == null) {
if (other.lastname != null)
return false;
} else if (!lastname.equals(other.lastname))
return false;
return true;
}
public void setAge(int age) {
this.age = age;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
private Long id;
private int age;
private String firstname;
private String lastname;
public Person() {
}
}
ManyToManyExample.java
public class ManyToManyExample {
/**
* @param args
*/
public static void main(String[] args) {
Session session = null;
try {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
Transaction tx1 = session.beginTransaction();
System.out.println("Loading Record");
Event theEvent = (Event) session.get(Event.class, new Long(1));
session.refresh(theEvent);
Person person = new Person();
person.setAge(31);
person.getEvents().add(theEvent);
person.setFirstname("RRRRRR");
person.setLastname("NNNNNN");
person.getEmailAddresses().add("RRRRRR@yahoo.com");
theEvent.getParticipants().add(person); // Adding person ref. to event for many to many relation
session.save(theEvent);
session.save(person);
tx1.commit();
System.out.println("Done...");
} catch (Exception e) {
e.printStackTrace();
} finally {
session.flush();
session.close();
}
}
}
运行上述示例时出现以下错误:INFO DefaultLoadEventListener:129 - Error execution load command org.hibernate.exception.GenericJDBCException: could not initialize a collection: [roseindia.tutorial.hibernate.Event.participants#1] at org.hibernate .exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:82) at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:70) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) at org. hibernate.loader.Loader.loadCollection(Loader.java:1351) at org.hibernate.loader.collection.CollectionLoader.initialize(CollectionLoader.java:101) at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java: 484)在org.hibernate.event.def。DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:60) at org.hibernate.impl.SessionImpl.initializeCollection(SessionImpl.java:1346) at org.hibernate.collection.AbstractPersistentCollection.forceInitialization(AbstractPersistentCollection.java:269) at org.hibernate.engine .PersistenceContext.initializeNonLazyCollections(PersistenceContext.java:745) 在 org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:208) 在 org.hibernate.loader.Loader.loadEntity(Loader.java:1255) 在 org.hibernate。 loader.entity.EntityLoader.load(EntityLoader.java:139) 在 org.hibernate.loader.entity.EntityLoader.load(EntityLoader.java:124) 在 org.hibernate.persister.entity.BasicEntityPersister.load(BasicEntityPersister.java: 2453)在org.hibernate.event.def。DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:387) at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:368) at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:166) at org .hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:140) 在 org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:249) 在 org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener .java:123) 在 org.hibernate.impl.SessionImpl.get(SessionImpl.java:561) 在 org.hibernate.impl.SessionImpl.get(SessionImpl.java:556) 在roseindia.tutorial.hibernate.ManyToManyExample.main( ManyToManyExample.java:24) 引起:java.sql.SQLException:[Microsoft][ODBC SQL Server 驱动程序]在 sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7113) 在 sun.jdbc.createSQLException(JdbcOdbc.java:6956) 在 sun.jdbc 的描述符索引无效.odbc.JdbcOdbc.SQLGetDataDouble(JdbcOdbc.java:3656) 在 sun.jdbc.odbc.JdbcOdbcResultSet.getDataDouble(JdbcOdbcResultSet.java:5574) 在 sun.jdbc.odbc.JdbcOdbcResultSet.getLong(JdbcOdbcResultSet.java:632) 在 sun. jdbc.odbc.JdbcOdbcResultSet.getLong(JdbcOdbcResultSet.java:650) at org.hibernate.type.LongType.get(LongType.java:26) at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:77) at org .hibernate.type.NullableType.nullSafeGet(NullableType.java:68) 在 org.hibernate.persister.collection.AbstractCollectionPersister.readKey(AbstractCollectionPersister.java:612) 在 org.hibernate.loader.Loader。readCollectionElement(Loader.java:545) at org.hibernate.loader.Loader.readCollectionElements(Loader.java:344) at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:299) at org.hibernate.loader.Loader .doQuery(Loader.java:384) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:203) at org.hibernate.loader.Loader.loadCollection(Loader.java:1344) ... 还有 20 个
我创建人员对象并通过使用 session.get(...) 获取事件来添加事件。对于多对多关系,在将每个对象添加到人员的事件列表之后,我正在做其他事情并将人员添加到事件对象的参与者列表中,这会引发异常。任何有帮助或指导都深表感谢!
我使用 SQL Server 2008 作为数据库。