初学者:定义JPA一对一映射时出错

时间:2012-05-30 05:34:10

标签: java hibernate jpa

我有以下表格:

Login -> (id, username, password)
Members -> (member_id, name, address)

id与member_id有一对一的映射。

我写了两个模型

登录模式:

@Entity
@Table(name = "Login", uniqueConstraints = { @UniqueConstraint(columnNames = "username") })
public class Login {

private int id;
private String username;
private String password;
private Members members;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public int getId() {
    return id;
}

@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, optional = true)
@JoinColumn(name = "id", referencedColumnName = "member_id")
public Members getMembers() {a
    return members;
}

}

Memeber模型:

@Entity
@Table(name = "Members")
public class Members {
private int member_id;
private String name;
private String address;

@Id
@GeneratedValue(generator = "gen")
@GenericGenerator(name = "gen", strategy = "foreign", parameters = { @Parameter(name = "property", value = "Login") })
@Column(name = "member_id")
public int getMember_id() {
    return member_id;
}

private Login login;

@OneToOne(fetch = FetchType.LAZY, optional = true, cascade = CascadeType.ALL)
public Login getLogin() {
    return login;
}

}
为了简单起见,我放弃了一些吸气剂和固定剂。无论如何你能告诉我哪里出错了?我在更改注释值时会收到错误,例如找不到映射,持久化类未知等等。

错误

org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是org.springframework.beans.factory.BeanCreationException:在类路径资源[database / Hibernate.xml]中定义的名称为'sessionFactory'的bean创建错误:init方法的调用失败;嵌套异常是org.hibernate.AnnotationException:@OneToOne或@ManyToOne on org.sparsham.login.model.Login.members引用一个未知实体:org.sparsham.members.model.Members     org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)     org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)     javax.servlet.http.HttpServlet.service(HttpServlet.java:621)     javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

1 个答案:

答案 0 :(得分:1)

希望这可以解决您的最后一个问题。尝试这些更改。

登录模式:

@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, optional = true)
@PrimaryKeyJoinColumn
public Members getMembers() {a
    return members;
}

会员模特:

@Id
@GeneratedValue(generator = "gen")
@GenericGenerator(name = "gen", strategy = "foreign", parameters = { @Parameter(name =          "property", value = "login") })
@Column(name = "member_id")
public int getMember_id() {
    return member_id;
}

private Login login;

@OneToOne(fetch = FetchType.LAZY, optional = true, cascade = CascadeType.ALL, mappedBy="members")
@PrimaryKeyJoinColumn
public Login getLogin() {
    return login;
}

注意@GenericGenerator注释中的@Parameter部分,“login”可能区分大小写。