ITeye博客

一个完整的hibernate的one-to-many的例子

houzhe11 · 2009-10-10 14:18 · java技术 · 编程语言 · JDBC · .net · XML · Hibernate · Oracle · Markdown

前段时间一直在研究hibernate的one-to-many,看了不少资料也在本论坛上求教过,但由于本人对Hibernate研究的时间不是很长,所以花了不少时间和精力.昨天终于弄出来了,现在与大家分享,希望对初学者有帮助! 1、设置数据库,本人使用的数据库是Oracle 9i 设置hibernate.properties ## Oracle hibernate.dialect net.sf.hibernate.dialect.Oracle9Dialect #hibernate.dialect net.sf.hibernate.dialect.OracleDialect hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver hibernate.connection.username sa hibernate.connection.password sa hibernate.connection.url jdbc:oracle:thin:@xxx.xxx.xxx.xxx:1521:myoracle 2、假设一个用户可以同时有几个帐户,能通过帐户对应到用户,即为一个双向的one-to-many.这是引用我在论坛上发表的文章的回复,很谢谢geniouc给我的参考。 3、javaBean: customer & account 1. public class Customer { 2. private String cid; 3. private String custName; 4. private Set accounts= new HashSet(); 5. 6. public Customer(){ 7. } 8. public String getCid() { 9. return cid; 10. } 11. public void setCid(String cid) { 12. this.cid = cid; 13. } 14. public String getCustName() { 15. return custName; 16. } 17. public void setCustName(String custName) { 18. this.custName = custName; 19. } 20. 21. public Set getAccounts(){ 22. return accounts; 23. } 24. 25. public void setAccounts(Set accounts){ 26. this.accounts = accounts; 27. } 28. 29. } 30. 31. public class Account { 32. private long aid; 33. private String accNumber; 34. private Customer customer; 35. 36. public Account(){ 37. } 38. public long getAid() { 39. return aid; 40. } 41. public void setAid(long aid) { 42. this.aid = aid; 43. } 44. public String getAccNumber() { 45. return accNumber; 46. } 47. public void setAccNumber(String accNumber) { 48. this.accNumber = accNumber; 49. } 50. 51. public Customer getCustomer(){ 52. return customer; 53. } 54. 55. public void setCustomer(Customer customer){ 56. this.customer = customer; 57. } 58. } 4、xml配置文件中:(关系的建立) Account.hbm.xml 1. 2. 5. 6. 7. 8. 9. 10. 11. 12. 13. Customer.hbm.xml 1. 2. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 5、测试程序,Test.java 1. package one2many; 2. 3. import net.sf.hibernate.*; 4. import net.sf.hibernate.cfg.*; 5. 6. public class Test { 7. public static void main(String[] args) throws HibernateException { 8. 9. Configuration conf= new Configuration(); 10. conf.addClass(Account.class); 11. conf.addClass(Customer.class); 12. SessionFactory sessionFactory = conf.buildSessionFactory(); 13. 14. Customer cust = new Customer(); 15. cust.setCid("aa"); 16. cust.setCustName("Kelvin"); 17. 18. Account acc = new Account(); 19. acc.setAccNumber("acc"); 20. acc.setCustomer(cust); 21. 22. Account acc1 = new Account(); 23. acc1.setAccNumber("acc1"); 24. acc1.setCustomer(cust); 25. 26. cust.getAccounts().add(acc); 27. cust.getAccounts().add(acc1); 28. 29. Session session = sessionFactory.openSession(); 30. Transaction tx= session.beginTransaction(); 31. session.save(cust); 32. 33. tx.commit(); 34. session.close(); 35. 36. sessionFactory.close(); 37. } 38. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。