我在网上尝试了其他所有选项。但无法同时在Tickets和Messages表(外键映射)中成功插入记录。
你能辨别出什么是错的吗?当我运行代码时,我只在ticket表中获取记录,而不是在messages表中。
以下是Ticket.class
@Entity
@Table(name = "ticket")
public class Ticket {
@Id
@Column(name = "ticket_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
int ticket_id;
@Column(name = "ticket_desc")
String ticket_desc;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "ticket")
Set<Message> message = new HashSet<Message>();
public int getTicket_id() {
return ticket_id;
}
public void setTicket_id(int ticket_id) {
this.ticket_id = ticket_id;
}
public String getTicket_desc() {
return ticket_desc;
}
public void setTicket_desc(String ticket_desc) {
this.ticket_desc = ticket_desc;
}
public Set<Message> getMessage() {
return message;
}
public void setMessage(Set<Message> message) {
this.message = message;
}
}
下面是Message.class
@Entity
@Table(name = "message")
public class Message {
@Id
@Column(name = "message_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int message_id;
@Column(name = "ticket_id")
private int ticket_id;
@Column(name = "message_text")
private String message_text;
@JoinColumn(name = "ticket_id", insertable = false, updatable = false)
@ManyToOne(cascade=CascadeType.ALL)
private Ticket ticket;
public Ticket getTicket() {
return ticket;
}
public void setTicket(Ticket ticket) {
this.ticket = ticket;
}
public int getMessage_id() {
return message_id;
}
public void setMessage_id(int message_id) {
this.message_id = message_id;
}
public int getTicket_id() {
return ticket_id;
}
public void setTicket_id(int ticket_id) {
this.ticket_id = ticket_id;
}
public String getMessage_text() {
return message_text;
}
public void setMessage_text(String message_text) {
this.message_text = message_text;
}
}
以下是test()
public static void test() {
Session session = HibernateSession.getHibernateSession();
Transaction t = session.beginTransaction();
Ticket ticket = new Ticket();
ticket.setTicket_desc("ticket description 2");
Set<Message> messages = new HashSet<Message>();
Message message = new Message();
message.setMessage_text("This is message text 2");
message.setTicket(ticket);
messages.add(message);
ticket.setMessage(messages);
session.persist(ticket);
t.commit();
}
你能辨别出什么是错的吗?当我运行代码时,我只在ticket表中获取记录,而不是在messages表中。
答案 0 :(得分:2)
原因是您的映射不会级联持久操作,请参阅:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "ticket")
Set<Message> message = new HashSet<Message>();
如果您希望进行级联操作,则需要指定
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "ticket")
Set<Message> message = new HashSet<Message>();
级联操作非常有用,但要注意它们的潜在副作用,特别是如果您修改了{* 1}},而您不打算将操作级联到Ticket
。
如果要分别管理Message
和Message
的持久性状态,则需要修改业务逻辑代码以保留Ticket
,然后保留Message
。