I am complete new to Hibernate and I have a question in the following condition.
User Class
@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);
}
History Class
@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;
}
The 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 class
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 will insert an entry to the history_table, but I also need the user_history_table to be updated too. So, should I create another object, say user_history_obj and update it just like the history_table update or there is a hibernate way of doing it. Thnaks.