SSH Learning four hibernate multi-to-one relationship + DELETE and change

Source: Internet
Author: User


Many-to-one relationships are not difficult to implement, just to declare a foreign key on the "many" side, declaring the foreign key in the class's mapping file implementation.

Below take the teacher student as an example, the teacher is 1, the student is many

There is an interesting place in the student class, there is no declaration Teacherid this attribute, but as long as the configuration file declaration of foreign keys, then even if there is no foreign key in the class, the property of the configuration file is not Teacherid

Here are a few key files:
1, Student class (including student and additions and deletions)

Package Com.learn.po;import Org.hibernate.session;import Org.hibernate.transaction;import Com.ehr.dao.hibernateutil;public class Student {private int sid;public int getsid () {return SID;} public void Setsid (int sid) {this.sid = SID;} private string Nm;private Teacher teacher;public string getnm () {return nm;} public void Setnm (String nm) {this.nm = NM;} Public Teacher Getteacher () {return Teacher;} public void Setteacher (Teacher Teacher) {this.teacher = Teacher;} public static void Addstudent () {///The logic here is that the object of the teacher class is a member function of student, when inserting data into the student table,//Initialize student, need to use teacher object, For example, add small Shenyang need his teacher Zhaoben on, so first find Zhao Benshan, then can insert small Shenyang,//As for the foreign key, is Hibernate automatic maintenance Session session = Hibernateutil.getsessionfactory (). Opensession (); Teacher t = (Teacher) session.get (Teacher.class, 2); Student s = new Student (); S.SETNM ("Fanwei"); S.setteacher (t); Hibernateutil.addobject (s); Session.close ();} public static void getquery (int id) {Session session = Hibernateutil.getsessionfactory (). Opensession (); Student s = (Student) session.get (Student.class,1);/* Find Teacherid do not query at all, because it is a foreign key, but also in the cache */system.out.println (S.getteacher (). Getteacherid ());/* Here the automatically generated hibernate SQL statement will do an inner join query to find Name*/system.out.println (S.getteacher (). GETNM ());} public static void Changeteacher () {Session session = Hibernateutil.getsessionfactory (). Opensession (); Teacher t = (Teacher) session.get (Teacher.class, 3); Student s = (Student) session.get (Student.class, 1); S.setteacher (t); Session.begintransaction (). commit ();} public static void Deletestu () {Session session = Hibernateutil.getsessionfactory (). Opensession (); Student s = new Student (); S.setsid (2); Session.delete (s); Session.begintransaction (). commit ();} public static void Main (string[] args) {//addstudent ();//getquery (1);//changeteacher ();//deletestu ();}}

2. Student Mapping File

<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">

3, the Teacher class

Package Com.learn.po;import Org.hibernate.session;import Com.ehr.dao.hibernateutil;public class Teacher {private int Teacherid;private string Nm;public string getnm () {return nm;} public void Setnm (String nm) {this.nm = NM;} public int Getteacherid () {return teacherid;} public void Setteacherid (int teacherid) {this.teacherid = Teacherid;} public static void Addteacher () {Teacher t = new Teacher (); T.SETNM ("te1");//It's amazing here, what kind of class is it that the best hibernate recognizes? Then insert the corresponding table Hibernateutil.addobject (t); T.SETNM ("Te2"); Hibernateutil.addobject (t);} public static void  Main (String args[]) {<pre name= "code" class= "java" ><span style= "White-space:pre" > </span>addteacher ();
}}


4. Teacher Mapping File

<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">

5. Hibernate configuration file

<! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http// Hibernate.sourceforge.net/hibernate-configuration-3.0.dtd ">
6\hibernateutil.java

Package Com.ehr.dao;import Java.io.serializable;import Org.hibernate.*;import org.hibernate.cfg.*;import Org.hibernate.tool.hbm2ddl.schemaexport;public class Hibernateutil {private static final sessionfactory sessionfactory;static {try {//Create the sessionfactory from hibernate.cfg.xmlsessionFactory = new Configuration (). Configure (). Buildsessionfactory ();} catch (Throwable ex) {//Make sure your log the exception, as it might be swallowedSystem.err.println ("Initial sessionfacto Ry creation failed. "+ ex"; throw new Exceptionininitializererror (ex);}} public static Sessionfactory Getsessionfactory () {return sessionfactory;} public static Serializable AddObject (object o) {//Gets session object Serializable s = null; Session session = Hibernateutil.getsessionfactory (). Opensession ();//Open transaction Transaction tx = Session.begintransaction (); try {s = session.save (o);//Save the object to DB and return the primary key value of the new column//COMMIT transaction Tx.commit ();} catch (Exception e) {System.out.println ( E.getmessage ()); Tx.rollback ();} finally {session.close ();} RetuRN S;} public static void Main (string[] args) {configuration cfg =new configuration (). Configure (); Schemaexport e = new Schemaexport (CFG); E.create (true, True);}}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

SSH Learning four hibernate multi-to-one relationship + DELETE and change

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.