我是Hibernate的新手,在以下情况下我有一个问题。
用户类
@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) );
App类
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更新一样更新它,或者有一种hibernate方式。 Thnaks。
答案 0 :(得分:1)
User
和History
之间的关系看起来有点像多对多,user_history作为连接表。
你最好以这种方式映射它。请参阅Hibernate Annotations Reference on mapping associations中@ManyToMany
部分。
这会更改user_history表的布局,方法是删除它自动生成的主键。但它可能值得一试,它可能会使表格以合理合理的方式填充这种关系。
修改强>
我现在不确定为什么我认为多对多,但是用连接表一对多映射可能没问题。创建History
对象后,如果将其添加到User
对象的userHistory集中,则会创建user_history_table条目并使用merge
User
保存对象