我是Hibernate的新手,我在以下情況下有問題。更新表A後休眠更新表B
用戶類
@Entity @Table (name="user_table") public class User implements Serializable{ /** * */ private static final long serialVersionUID = 1L; +getters and setters //access by field //primary key @Id @Column (name = "username") private String username; @Column (name = "password") private String password; @Column (name = "email") private String email; /** * Cascade all operations */ @OneToMany(cascade = CascadeType.ALL) @JoinTable(name = "user_history_table", joinColumns = { @JoinColumn(name = "username") }, inverseJoinColumns = { @JoinColumn(name = "history_id") } ) private Set userHistory = new HashSet(0); }
歷史課
@Entity @Table (name="history_table") public class History { +getters and setters //primary key @Id @Column (name = "history_id") private int id; @Column (name="url") private String url; @Column (name="region") private String region; @Column (name="source") private String source; @Column (name="target") private String target; @Column (name="cost") private double cost; @Column (name="balance") private double balance; }
的Schemate
create table user_table( username varchar(50) NOT NULL PRIMARY KEY, password varchar(20), email varchar(150) ); create table history_table( history_id INTEGER AUTO_INCREMENT PRIMARY KEY, url varchar(1000) NOT NULL, cur_timestamp timestamp default now(), region varchar (100) NOT NULL, source varchar(30) NOT NULL, target varchar(30) NOT NULL, cost decimal (10,2) NOT NULL, balance decimal (10,2) NOT NULL ); create table user_history_table( user_history_id INTEGER AUTO_INCREMENT PRIMARY KEY, username varchar(50) NOT NULL, history_id INTEGER NOT NULL, FOREIGN KEY (username) REFERENCES user_table(username), FOREIGN KEY (history_id) REFERENCES history_table(history_id) );
應用CL屁股
public class App { public static void main(String [] args){ SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); Session session = sessionFactory.getCurrentSession(); Transaction tx = session.beginTransaction(); System.out.println("Inserting Record"); History history = new History(); history.setBalance(1000); history.setCost(50.99); history.setRegion("region"); history.setSource("Source_test"); history.setTarget("Target_test"); history.setUrl("http://stackoverflow.com/"); session.save(history); tx.commit(); System.out.println("Done"); } }
App.java將插入到history_table的條目,但我還需要user_history_table進行過更新。所以,我應該創建另一個對象,說user_history_obj並更新它就像history_table更新或有休眠的方式做它。 Thnaks。
謝謝,@ManyToMany是有道理的,但我不認爲user_history_id主要需要被刪除。 – user200340
不,它可能不必被刪除,但我認爲如果你使用休眠來生成你的DDL,它不會被生成。 –
不,對不起。這並非多對多,因爲與該用戶關聯的history_table中存在餘額,時間戳和成本列。 – user200340