我正在开发一个Spring MVC应用程序,其中有两个模型类:LocationModel和ContactModel。以下是代码:
@Entity
@Table(name="Contact")
public class ContactModel {
@Id
@Column(name="contactid")
@GeneratedValue
private int contactId;
@Column(name="contactname")
private String contactName;
@Column(name="contactemail")
private String email;
@Column(name="contactphone")
private String phone;
@ManyToOne
@JoinColumn(name="locationid")
private LocationModel locationModel;
}
@Entity
@Table(name="Location")
public class LocationModel {
@Id
@Column(name="locationid")
@GeneratedValue
private int locationId;
@Column(name="locationname")
private String locationName;
@Column(name="locationdesc")
private String locationDescription;
@Column(name="type")
private String locationType;
@Column(name="address")
private String address;
@Column(name="state")
private String state;
@Column(name="circle")
private int circle;
@Column(name="district")
private int district;
@Column(name="town")
private int town;
@Column(name="lattitude")
private String lattitude;
@Column(name="longitude")
private String longitude;
@Column(name="locationuid")
private String locationUID;
@Column(name="category")
private String category;
@Column(name="bedcount")
private int bedCount;
@OneToMany(mappedBy = "locationModel", fetch = FetchType.EAGER)
private List<ContactModel> contactList;
}
位置表中的主键是联系人表中的外键。我在联系表中有2条记录,位置ID为0。
我使用以下代码获取联系人列表:
Session session = sessionFactory.getCurrentSession();
Query query = session
.createQuery("from ContactModel where contactName like :contactName");
return query.setParameter("contactName", contactName + "%").list();
但它显示例外:
Error performing load command : org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.bizmerlin.scm.model.LocationModel#0]
17:03:31,135 ERROR [stderr] (http--127.0.0.1-9090-2) org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.bizmerlin.scm.model.LocationModel#0]
17:03:31,139 ERROR [stderr] (http--127.0.0.1-9090-2) at org.hibernate.internal.SessionFactoryImpl$1$1.handleEntityNotFound(SessionFactoryImpl.java:247)
17:03:31,141 ERROR [stderr] (http--127.0.0.1-9090-2) at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:214)
17:03:31,143 ERROR [stderr] (http--127.0.0.1-9090-2) at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:264)
也许是因为位置表没有位置ID为0的记录。如果是这样,我怎样才能获得联系人列表,即使他们的位置为空?
答案 0 :(得分:0)
使用可选属性
@ManyToOne(optional=true)
@JoinColumn(name="locationid")
private LocationModel locationModel;
http://learningviacode.blogspot.in/2011/12/one-to-many-assocition-that-is-optional.html