我不能使用带有注释的hibernate和jpa自动生成我的外键。一切似乎都没问题,条目保存在数据库中。所有日期都来自一个表单,当提交时,使用ModelAttribute创建一个User对象,然后将其保存在Database中。 这是我的豆子。还有什么我应该补充的吗?
@Entity
@Table(name="adress")
public class Adress implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="adress_id")
private Integer adressId;
@NotBlank(message="The city must be completed")
@Column(name="city")
@Size(min=5,max=30)
private String city;
@NotBlank(message="The street must be completed")
@Column(name="street")
@Size(min=5,max=30)
private String street;
@NotNull(message="The street number must be completed")
@NumberFormat
@Column(name="street_no")
private Integer streetNo;
@OneToOne
@JoinColumn(name="user_id")
private User user;}
和另一个:
@Entity
@Table(name="users")
public class User implements Serializable {
@Id
@Column(name="user_id")
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer userId;
@NotBlank(message="Username can't be blank")
@Size(min=5,max=30)
@Column(name="username")
private String username;
@NotBlank(message="Password field can't be blank")
@Size(min=5,max=30)
@Column(name="password")
private String password;
@NumberFormat
@NotNull(message="Age field must not be blank")
@Column(name="age")
private Integer age;
@Column(name="message")
@Size(min=0,max=100)
private String message;
@Column(name="date")
@DateTimeFormat(pattern="dd/mm/yyyy")
private Date dateCreated;
@OneToOne(mappedBy="user",cascade=CascadeType.ALL,fetch=FetchType.EAGER)
private Adress adress;
为他们提供+ getter和setter
public void save(T entity){
sessionFactory.getCurrentSession().save(entity);
}
答案 0 :(得分:1)
如果我理解正确并且您正在尝试让Hibernate在相关记录中设置外键,这可能有所帮助。尝试摆脱mappedBy,而是指定JoinColumn。这对我来说对一对多有用:
订单:
@Entity
@Table(name = "`order`")
public class Order implements Serializable {
@Id
@GeneratedValue
private Long id;
// Order columns...
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "order_id")
private Set<Item> items;
}
项目:
@Entity
@Table(name = "item")
public class Item implements Serializable {
@Id
@GeneratedValue
private Long id;
// Item columns...
@ManyToOne(optional = false)
@JoinColumn(name = "order_id", referencedColumnName = "id", nullable = false)
private Order order;
}
答案 1 :(得分:0)
在地址类
@OneToOne(mappedBy="adress")
private User user;
并在用户类
中@OneToOne(cascade=CascadeType.ALL,fetch=FetchType.EAGER,optional=false)
@PrimaryKeyJoinColumn
private Adress adress;