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

How to realize one-to-many data association in Hibernate

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

Share

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

This article mainly explains "how to realize 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 "how to implement Hibernate one-to-many data association".

1. Data model

two。 Table definition sql

Use sample; DROP TABLE addresses; DROP TABLE user; CREATE TABLE T_User (id INT NOT NULL AUTO_INCREMENT, name VARCHAR (50), age INT, PRIMARY KEY (id)) CREATE TABLE T_Address (id INT NOT NULL AUTO_INCREMENT, address VARCHAR, zipcode VARCHAR, tel VARCHAR, type VARCHAR, user_id INT NOT NULL, idx INT, PRIMARY KEY (id), INDEX (user_id)) CONSTRAINT FK_T_Address_1 FOREIGN KEY (user_id) REFERENCES T_User (id))

POJO class

TUser.java

Package cn.blogjava.start; import java.util.Set; public class TUser implements java.io.Serializable {/ / Fields private Integer id; private Integer age; private String name; private Set address; / / Constructors public Integer getAge () {return age;} public void setAge (Integer age) {this.age = age } public Set getAddress () {return address;} public void setAddress (Set address) {this.address = address;} / * * default constructor * / public TUser () {} / * * constructor with id * / public TUser (Integer id) {this.id = id } / / Property accessors public Integer getId () {return this.id;} public void setId (Integer id) {this.id = id;} public String getName () {return this.name;} public void setName (String name) {this.name = name;}}

TAddress.java

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 userId; private Integer idx; 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 Integer getUserId () {return userId;} public void setUserId (Integer userId) {this.userId = userId } public String getZipcode () {return zipcode;} public void setZipcode (String zipcode) {this.zipcode = zipcode;}}

3. Configuration file

TUser.hbm.xml

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

TAddress.hbm.xml

Note: the user_id field is not configured.

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

4. Test code

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 testing (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"); TAddress addr2 = new TAddress (); addr2.setTel ("139") Addr2.setZipcode ("116001"); addr2.setAddress ("dalian"); TAddress addr3 = new TAddress (); addr3.setTel ("100080"); addr3.setZipcode ("100080"); addr3.setAddress ("beijing") / / set correlation 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 ());}

Description:

One problem is that because it is an one-way association, in order to maintain the relationship, we can only cascade and update the passive party through the master. If the field of the associated party is a NOT NULL attribute, a constraint violation may occur when Hibernate creates or updates the association relationship.

In the example, the user_id in the T _ addresses table is NOT NULL, if TAddress.hbm.xml maps all fields. Create a user and give her address information, and for the T_ addresses table, Hibernate one to many executes two sql statements to hold the address information.

To execute two SQL statements, it is because the association is one-way, that is, for the TAddress object, you do not know which TUser object you should associate with, so you can only set user_id to a null value.

After that, according to the configuration file

Key > set > at this point, I believe you have a deeper understanding of "how to achieve Hibernate one-to-many data association". 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