引用
转载:http://blog.sina.com.cn/s/blog_7a8f609501014j34.html
使用hibernate 注解配置实体类的关联关系,在many-to-one,one-to-one关联中,一边引用自另一边的属性,如果属性值为某某的数据在数据库不存在了,hibernate默认会抛出异常。解决此问题,加上如下注解就可以了:
@NotFound(action=NotFoundAction.IGNORE),意思是找不到引用的外键数据时忽略,NotFound默认是exception
下面贴出hibernate 注解的实例代码
view plaincopy to clipboardprint?
@Entity
@Table(name = "ICT_COMPUTER_LOCATION")
public class IctComputerLocation {
private static final long serialVersionUID = 1L;
private Integer id;
private String idcNum;
private Integer ictBaseId;
private IctBase ictBase;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "IDC_NUM")
public String getIdcNum() {
return idcNum;
}
public void setIdcNum(String idcNum) {
this.idcNum = idcNum;
}
@Column(name = "ICT_BASE_ID")
public Integer getIctBaseId() {
return ictBaseId;
}
public void setIctBaseId(Integer ictBaseId) {
this.ictBaseId = ictBaseId;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ICT_BASE_ID", referencedColumnName = "ID", unique = false, nullable = false, insertable = false, updatable = false)
@NotFound(action=NotFoundAction.IGNORE)
public IctBase getIctBase() {
return ictBase;
}
public void setIctBase(IctBase ictBase) {
this.ictBase = ictBase;
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/hardwin/archive/2009/07/08/4330779.aspx
对象A一对多对象B,现在要查询对象A,条件中包含对象B的属性,但对象A的属性B可能为Null,这时候怎么写条件?
比如对象A是用户:
Java code
@Entity
@Table(name = "base_staff")
public class User {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
@Column(name = "logname")
private String logname;
@Column(name = "logpass")
private String logpass;
@ManyToOne
@JoinColumn(name = "gender")
@NotFound(action=NotFoundAction.IGNORE)
private Gender gender;
@Column(name = "birthdate")
private Date birthdate;
@ManyToOne
@JoinColumn(name = "user_status")
@NotFound(action=NotFoundAction.IGNORE)
private UserStatus status;
@Column(name = "note")
private String note;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "sys_user_role",
joinColumns = { @JoinColumn(name = "user_id") },
inverseJoinColumns = { @JoinColumn(name = "role_id") })
@NotFound(action=NotFoundAction.IGNORE)
private Set roles;
……
}
对象B是性别:
Java code
@Entity
@Table(name = "code_gender")
public class Gender {
@Id
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
}
UserDao:
Java code
Query query = session.createQuery("from User u" +
" where u.name like :key" +
" or u.gender.name like :key" +
" or u.logname like :key" +
" or u.status.name like :key" +
" or u.note like :key" +
" order by u.id");
query.setParameter("key", "%" + key + "%");
query.setFirstResult(offset);
query.setMaxResults(size);
List list = query.list();
这种情况查询不到User的gender为null的数据。想要得到那些数据应该怎么些HQL呢?