Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the Hibernate one-to-many data association?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly talks about "what is Hibernate one-to-many data association". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what Hibernate one-to-many data association is.

Hibernate one-to-many data association. Refers to an one-way one-to-many data association where a user has multiple addresses and contains a collection of address classes TAddress in the user class TUser.

If Hibernate is used, the so-called one-to-many, many-to-one, many-to-many, one-to-one relationships should soon be understood. The following mainly introduces the one-to-many problem of Hibernate.

1. The TUser object assigns its own id to the addr.user_id, which causes the value of the addr attribute to change, and update occurs when the transaction is submitted.

1) when save the user

Insert into t_address (user_id, address, zipcode, tel) value (null, "HongKong", "233123", "1123")

2) when tx.commit ():

Update t_address user_id= "1", address= "HongKong", zipcode= "233123", tel= "1123" where id=2

In this way, a constraint violation occurs at the time of save user.

Adjustment method:

You can define datasheet fields without NOT NULL constraints. Either start by assigning a non-null value to the user_id at will (because you still need to update, it doesn't matter if it's incorrect), or remove the user_id field from the TAddress.hbm.xml (as this example does). But these are expedient measures, using two SQL statements to complete a database operation, the performance is poor. And two-way one-to-many solved the problem.

The following is a two-way association: modify the configuration file TUser.hbm.xml

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> id > key > set > class > hibernate-mapping >

Setting inverse= "true" indicates that the TUser class is used as a passive class, and the maintenance of the data association is left to the associated object TAddress to manage.

In the one-to-many model, setting the many side as the master is helpful to improve the performance. (it is difficult for the prime minister to remember everyone, but it is convenient for everyone to remember the prime minister)

TAddress.hbm.xml

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> id > class > hibernate-mapping >

two。 Make the following modifications to TAddress.java: remove the user_id field, add the user field, and the getter,setter method.

Package cn.blogjava.start; import java.io.Serializable; public class TAddress implements Serializable {private Integer id; private String address; private String zipcode; private String tel; private String type; private Integer idx; private TUser user; public TUser getUser () {return user;} public void setUser (TUser user) {this.user = user } public Integer getId () {return id;} public void setId (Integer id) {this.id = id;} public String getAddress () {return address;} public void setAddress (String address) {this.address = address;} public Integer getIdx () {return idx } public void setIdx (Integer idx) {this.idx = idx;} public String getTel () {return tel;} public void setTel (String tel) {this.tel = tel;} public String getType () {return type;} public void setType (String type) {this.type = type } public String getZipcode () {return zipcode;} public void setZipcode (String zipcode) {this.zipcode = zipcode;}}

3. Test code

Since TUser does not maintain associations, TAddress needs to maintain TUser on its own, so addr.setUser (user) is needed.

Package cn.blogjava.start; import java.util.HashSet; import java.util.Iterator; import java.util.List; import junit.framework.Assert; import junit.framework.TestCase; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class HibernateTest extends TestCase {Session session = null Protected void setUp () {try {Configuration config = new Configuration () .configure (); SessionFactory sessionFactory = config.buildSessionFactory (); session = sessionFactory.openSession ();} catch (HibernateException e) {e.printStackTrace () }} protected void tearDown () {try {session.close ();} catch (HibernateException e) {e.printStackTrace () }} / * / * object persistence test (Insert method) * / public void testInsert () {Transaction tran = null; try {TUser user = new TUser (); user.setName ("byf") User.setAge (new Integer (26)); TAddress addr = new TAddress (); addr.setTel ("1123"); addr.setZipcode ("233123"); addr.setAddress ("HongKong"); addr.setUser (user); TAddress addr2 = new TAddress () Addr2.setTel ("139"); addr2.setZipcode (" 116001 "); addr2.setAddress (" dalian "); addr2.setUser (user); TAddress addr3 = new TAddress (); addr3.setTel (" 136"); addr3.setZipcode ("100080"); addr3.setAddress ("beijing") Addr3.setUser (user); / / set association HashSet set = new HashSet (); set.add (addr); set.add (addr2); set.add (addr3); user.setAddress (set) Tran = session.beginTransaction (); / / insert user information session.save (user); session.flush (); tran.commit (); Assert.assertEquals (user.getId (). IntValue () > 0, true) } catch (HibernateException e) {e.printStackTrace (); Assert.fail (e.getMessage ()); if (tran! = null) {try {tran.rollback ();} catch (Exception E1) {e1.printStackTrace () } / * * / / * object read test (Select method) * / public void testSelect () {String hql = "from TUser where name='byf'"; try {List userList = session.createQuery (hql). List () TUser user = (TUser) userList.get (0); System.out.println ("user name is" + user.getName ()); for (Iterator iter = user.getAddress (). Iterator (); iter.hasNext ();) {TAddress addr = (TAddress) iter.next () System.out.println ("user address is" + addr.getAddress ());} Assert.assertEquals (user.getName (), "byf");} catch (Exception e) {e.printStackTrace (); Assert.fail (e.getMessage ()) At this point, I believe you have a deeper understanding of "what Hibernate one-to-many data association is". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report