In-to-one in Hibernate

xiaoxiao2021-03-05  22

Issue: Hibernate is a good thing, but I feel that this good stuff is not good driving, a one-to-one makes me spend a lot of time, now I finally have a little understanding, so I want to share my views, if there is a mistake , Please also criticize and correct!

1. About One-to-One

One-to-one relationship between the persistence object is defined by one-to-one element:

Name = "PropertyName" (1)

Class = "classname" (2)

Cascade = "all | none | save-update | delete" (3)

Constrained = "True | False" (4)

Outer-join = "True | False | Auto" (5)

Property-ref = "PropertyNameFromassociatedClass" (6)

Access = "Field | Property | ClassName" (7)

/>

(1) Name: The name of the property [Pojo]. (2) Class (Optional - default is the name of the associated class): the name of the class being associated. (3) Cascade (optional) indicates whether the operation is associated with the associated object from the parent object level. (4) Constrained (optional) Indicates that the database table corresponding to the corresponding table, and the database table corresponding to the associated object, constrained by a foreign key reference. This option affects Save () and delete () in the order of order execution (also used in Schema Export Tool). (5) Outer-join (optional - default is automatic): When Hibernate.Use_outer_join, this association allows external connection to capture. (6) Property-REF: (Optional) Specify an attribute of the associated class, this property will correspond to the foreign key. If not specified, the primary key of the other party is used [instance of the POJO class in Pojo]. (7) Access (option - default is Property): Hibernate is used to access the properties strategy.

2.one-to-one classification

Primary key association

The only foreign key association

The primary key association does not require additional table fields; the two lines are associated with this one-on-one relationship, then the two lines share the same primary keyword value. So if you want two objects to pass through the primary key, you must confirm that they are given the same identification value!

Another way is an outer key and a unique keyword.

3. Unique foreign key association operation inone-to-one

(1) Database DDL

## Table structure for table 'author' #

Create Table Author (Author_id Char (20) Not Null Default ', Person_id Char (20) Default Null, Primary Key (Author_ID) ENGINE = InnoDB Default CHARSET = GB2312;

## Table structure for table 'Person' #

Create Table Person (Person_id Char (20) Not Null Default ', Name Char (20) Default Null, Primary Key (Person_ID)) Engine = InnoDB Default Charset = GB2312; (2) Mapping file

Author.hbm.xml

Person.hbm.xml

(2) Pojo file

AbstractAuthor.java

Package Po;

Import java.io.serializable;

Public Abstract Class AbstractAuthor Implements Serializable {/ ** The Cached Hash Code Value for this Instance. Settting to 0 Triggers Re-Calculation. * / Private INT HashValue = 0;

/ ** The Composite Primary key value. * / Private java.lang.string authorid;

/ ** The value of the simple personid property. * / Private java.lang.string Personid;

/ ** * Simple constructor of abstractauthor instances. * / Public abstractAuthor () {}

/ ** * Constructor of AbstractAuthor Instances Given a Simple Primary Key. * @Param Authorid * / Public AbstractAuthor (java.lang.string authorid) {this.setauthorid (Authorid);}

/ ** * Return the simple primary key value that identifies this object * @return java.lang.String * / public java.lang.String getAuthorId (). {Return authorId;} / ** * Set the simple primary key value that Identifies this object. * @Param authorid * / public void setauthorid (java.lang.string authorid) {this.hashvalue = 0; this.authorid = authorId;}

/ ** * Return the value of the person_id column. * @Return java.lang.string * / public java.lang.string getPersonid () {Return this.PersonId;}

/ ** * set the value of the person_id column. * @Param Personid * / public void setPersonid (java.lang.string personid) {this.personid = personid;}

/ ** * Implementation of the equals comparison on the basis of equals comparison on the basis of equals. * @Param rhs * @return boolean * / public boolean equals (object rhs) {if (rhs == null) Return False; if ( (RHS InstanceOf Author) RETURN FALSE; Author That = (Author) RHS; IF (this.getauthorid ()! = null && That.getAuthorid ()! = null) {if (! this.getauthorid (). Equals. That.getAuthorid ())) {Return false;}} Return true;

/ ** * Implementation of the hashCode method conforming to the Bloch pattern with * the exception of array properties (these are very unlikely primary key types). * @Return int * / public int hashCode () {if (this.hashValue == 0) {int result = 17; int authoridvalue = this.getauthorid () == null? 0: this.getauthorid (). Hashcode (); result = result * 37 authoridValue; this.hashvalue = result;} return.. Author.javaPackage Po;

Import java.io.serializable;

Public Class Author Extends AbstractAuthor Implements Serializable {Private Person Person; / ** * Simple Constructor Of Author Instances. * / Public Author () {}

/ ** * Constructor of author instances given a simple primary key. * @Param authorid * / public author (java.lang.string authorid) {super (authorid);

/ * Add customer void setPerson (PERSON PERSON) {this.Person = Person;} public person getPerson ()}

}

AbstractPerson.java

Package Po;

Import java.io.serializable;

Public Abstract Class AbstractPerson Implements Serializable {/ ** The Cached Hash Code Value for this Instance. Settting to 0 Triggers Re-Calculation. * / Private INT HashValue = 0

/ ** The composite primary key value. * / Private java.lang.string personId;

/ ** The value of the simple name property. * / Private java.lang.string name

/ ** * Simple constructor of abstractperson instances. * / Public abstractPerson () {}

/ ** * Constructor of AbstractPerson instances given a simple primary key * @param personId * / public AbstractPerson (java.lang.String personId) {this.setPersonId (personId);}. / ** * Return the simple primary key value that Identifies this object. * @Return java.lang.string * / public java.lang.string getPersonid () {returnent pERSONID;

/ ** * SET the Simple Primary Key Value That Identifies this Object. * @Param Personid * / Public Void SetPersonid (Java.lang.String Personid) {this.hashvalue = 0; this.Personid = personId;}

/ ** * Return the value of the name column. * @Return java.lang.string * / public java.lang.string getName () {Return this.name;}

/ ** * set the value of the name column. * @Param name * / public void setName (java.lang.string name) {this.name = name;}

/ ** * Implementation of the equals comparison on the basis of equals comparison on the basis of equals. * @Param rhs * @return boolean * / public boolean equals (object rhs) {if (rhs == null) Return False; if ( RHS InstanceOf Person) Return False; Person That = (Person) RHS; if (this.getPersonid ()! = null && That.getPersonId ()! = null) {if (! this.getPersonid (). Equals. That.getPersonid ())) {Return false;}} Return True;

/ ** * Implementation of the hashCode method conforming to the Bloch pattern with * the exception of array properties (these are very unlikely primary key types). * @Return int * / public int hashCode () {if (this.hashValue == 0) {int result = 17; int correnceValue = this.getPersonid () == null? 0: this.getPersonid (). Hashcode (); result = result * 37 personidValue; this.hashvalue = result;} return. Hashvalue;}}.

Import java.io.serializable;

Public Class Person Extends AbstractPerson Implements Serializable {Private Author Author; / ** * Simple Constructor of Person Instances. * / Public Person () {}

/ ** * Constructor of Person Instances Given a Simple Primary Key. * @Param Personid * / Public Person (Java.lang.String Personid) {Super (Personid);

/ * Add Customized Code Below * / Public Void SetAuthor (this.author = Author;} public author getAuthor () {Return Author;

}

(3) Test file

TESTOO.JAVA

Package test;

IMPORT Po.Person;

Import net.sf.hibernate. *; import net.sf.hibernate.cfg. *;

Public class testoo {private session sessions = null;

/ ** * @param args * / public static void main (String [] args) {// TODO Auto-generated method stub try {Configuration cfg = new Configuration () configure ();. SessionFactory sessions = cfg.buildSessionFactory () Session session = sessions.opensions (); transaction tx = session.begintransaction (); person Person = new person (); person.setPersonId ("1"); Person.SetName ("Blake stone"); author author = new Author (); Author.SetAuthorid ("11"); Author.SetPerson (Person);

Session.save (Person); session.save (author); System.out.Print ("I will dead if i don't get success success!"); tx.commit (); session.close ();} catch Exception E) {system.out.println (e);}}}

(4) Share joy

Run the test class, data is added normally to the database.

(5) In-depth discussion

a. Because the primary key uses the assigned mode, you must specify the ID;

b. If only session.save (author); will generate cascade errors [COULD NOT SYNCHRONIZE DATABASE State with session net.sf.hibernate.hibernateException: Batch Update Row Count WRONG: 0], look at the executed SQL statement [ Hibernate: INSERT INTO AUTHOR (Person_ID, Author_ID) VALUES (?,?) Hibernate: Update Person Set Name =? Where Person_ID =?] I understand it, because the Person table is still empty, of course, the execution of Update will fail! Although the solution is simple, it is worth thinking about it! Although the setter method is performed on Person, don't forget that he is still VO instead of Po!

转载请注明原文地址:https://www.9cbs.com/read-32612.html

New Post(0)