Hibernate Getting Started Tutorial

Source: Internet
Author: User

In the previous chapter we learned about Hibernate configuration and the operation of a single table, this chapter describes one-to-one configuration in hibernate

Hibernate Getting Started Tutorial chapter II

Hibernate one-to-one unilateral bilateral configuration, as well as additions and deletions

Pre-Knowledge:

1. Fetch, you can set fetch = "SELECT" and fetch = "Join"

Fetch = "Select" is the query at the time of the first one end of the entity, and then the query based on one end of the entity, will produce 1+n SQL statement;
Fetch = "Join" is the query when the use of outer joins to query, will not be inferior 1+n phenomenon.

2, The lazy policy can be used in:
* <class> tag: You can take a value true/false
* <property> tag, you can take the value True/false, this feature requires class enhancement
* <set>/<list> On the set, you can take a value of True/false/extra
* <one-to-one>/<many-to-one> and other labels, you can take the value false/proxy/no-proxy

Lazy everyone should be familiar with, that is, lazy loading, you can set the lazy = "true", lazy = "false" lazy = "proxy".
The main problem I'm going to talk about here is the use of lazy and fetch together:

1, when lazy= "true" fetch = "Select" Time, this time is the use of the delay strategy, began to query only one side of the entity, multi-terminal will not query, only when the use of the time will be issued SQL statements to query;
2, when lazy= "false" fetch = "Select" Time, this time is to make no delay policy, while querying out one end and multi-terminal, while generating 1+n SQL.
3, when lazy= "true"/lazy= "false" fetch = "join" time, I think this time delay is no use, because the use of the external connection query, at the same time the end and multi-terminal query out, the delay does not work.

3, the value of Cascade

All: Associated operations are performed in all cases.
None: Associated operations are not performed in all cases. This is the default value.
Save-update: The associated operation is performed when Save/update/saveorupdate is executed.
Delete: The associated operation is performed when the delete is executed.

Hibernate one-to-one configuration is divided into shared primary key and foreign key 2 in the way we first look at the foreign key way:

First, below we take class and monitor as an example to explain

1, Class class:

public class Clazz implements java.io.Serializable {//fieldsprivate Integer classid;private String classname;private Mon Itor monitor;//constructors/** default constructor */public Clazz () {}/** Full constructor *///property Accessorspublic Integer GetClassID () {return this.classid;} Public Clazz (String className, monitor monitor) {This.classname = Classname;this.monitor = monitor;} public void Setclassid (Integer classId) {this.classid = classId;} Public String GetClassName () {return this.classname;} public void Setclassname (String className) {this.classname = ClassName;} Public monitor Getmonitor () {return monitor;} public void Setmonitor (monitor monitor) {this.monitor = monitor;}}

2, the class configuration file Clazz.hbm.xml


3. Class Leader

public class Monitor implements java.io.Serializable {//fieldsprivate Integer monitorid;private clazz clazz;private stri Ng monitorname;//constructors/** default constructor */public Monitor () {}/** full constructor */public Monitor (Clazz CLA ZZ, String monitorname) {this.clazz = Clazz;this.monitorname = Monitorname;} Property Accessorspublic Integer Getmonitorid () {return this.monitorid;} public void Setmonitorid (Integer monitorid) {this.monitorid = Monitorid;} Public Clazz Getclazz () {return this.clazz;} public void Setclazz (Clazz clazz) {this.clazz = Clazz;} Public String Getmonitorname () {return this.monitorname;} public void Setmonitorname (String monitorname) {this.monitorname = Monitorname;}}
4. class Monitor configuration fileMonitor.hbm.xml


Second, data operation

1. Add Data

Add data public static void Fun1 () {Session session = Hibernatesessionfactory.getsessionfactory (). Opensession (); Transaction trans = Session.begintransaction (); Clazz C = new Clazz (); C.setclassname ("Applied Mathematics"); Session.save (c); Monitor m = new monitor (); M.setmonitorname ("Zhang Yi"); M.setclazz (c); Session.save (m); Trans.commit (); Session.close ();}

2. Query data

Query data public static void Fun2 () {Session session = Hibernatesessionfactory.getsessionfactory (). Opensession (); Clazz C = (clazz) session.get (clazz.class,1);//monitor m = (Monitor) session.get (Monitor.class, 1); System.out.println (C.getmonitor (). Getmonitorname ());}

3. Delete data

Delete data public static void Fun3 () {Session session = Hibernatesessionfactory.getsessionfactory (). Opensession (); Transaction trans = Session.begintransaction (); Clazz C = (clazz) session.get (clazz.class,4); Session.delete (c); Trans.commit (); Session.close ();}
Note: Fun3 () will be an error sometimes, for example, now there is a class record in the database, a monitor record, the monitor application of the class ID, then in the fun3 you directly deleted a class, then there are foreign key constraints, so there will be error, how to solve it? I we need to be inConfigure the association in Clazz.hbm.xml

<one-to-one class= "Com.sunny.entity50.Monitor" name= "Monitor" cascade= "All"/> //Cascade Write as delete is also possible

If so you also have to be careful, if you accidentally deleted a class, then the class of the monitor's record is not, so the association or to use with caution, we finally catch the wrong way to solve or judge the way to solve

4. Modification

The modification simply does not post the code, as the previous chapter changes, see my previous article

Description

1, about such a foreign key way of one-to-one configuration is said, in said, Hibernate affairs, hibernate error when we commit, if commit failed, then database operation is unsuccessful, will be error, below I code to demonstrate a situation

public static void Fun5 () {Session session = Hibernatesessionfactory.getsessionfactory (). Opensession (); Transaction trans = Session.begintransaction (); Clazz C = new Clazz (); C.setclassname ("Applied Mathematics"); Session.save (c); Monitor m = new monitor (); M.setmonitorid (2); M.setmonitorname ("Zhang Yi"); M.setclazz (c); Session.save (m); Trans.commit (); Trans.rollback ();//Test Place Session.close ();}
My intention is to measure Hibernate's affairs, I want to let me just insert the data in the database rollback, but unfortunately the code error;

The error is as follows:

Exception in thread ' main ' org.hibernate.TransactionException:Transaction not successfully started
At Org.hibernate.transaction.JDBCTransaction.rollback (jdbctransaction.java:183)
At Com.sunny.test.Demo50.fun5 (demo50.java:53)
At Com.sunny.test.Demo50.main (demo50.java:23)

The meaning is that my business is not open, can my business name open Ah, in fact, when we commit successfully, Hibernate will turn off the transaction, all reported the above error, if the commit failed, then the transaction is not closed , Here's what we need to pay attention
2, if you want to configure a single-sided relationship in the corresponding configuration file and the relationship between the code is deleted.

Ii. How to configure the primary key association

Take the student and the rice card for example, a student a meal card

1. Student Class

public class Student  implements Java.io.Serializable {    //fields         private Integer studentid;     Private String studentname;     Private card card;    Constructors    /** Default constructor *    /Public Student () {    }    /** Full constructor *    /Public Student (String studentname, card) {        this.studentname = studentname;        This.card = card;    }    Property accessors public    Integer Getstudentid () {        return this.studentid;    }        public void Setstudentid (Integer studentid) {        this.studentid = StudentID;    }    Public String Getstudentname () {        return this.studentname;    }        public void Setstudentname (String studentname) {        this.studentname = studentname;    }    Public Card Getcard () {        return this.card;    }        public void Setcard (card) {        this.card = card;    }   }
2, student configuration file Student.hbm.xml
<?xml version= "1.0" encoding= "Utf-8"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd "><!--     mapping file autogenerated by MyEclipse persistence tools-->< hibernate-mapping>    <class name= "com.sunny.entity51.Student" table= "Student" catalog= "test100" >        <id name= "StudentID" type= "Java.lang.Integer" >            <column name= "student_id"/> <generator            class = "Identity" ></generator>        </id>        <property name= "Studentname" type= "java.lang.String" >            <column name= "student_name" length= "/>        </property> <one-to-one name=        " card " class= "Com.sunny.entity51.Card" ></one-to-one>    </class>
3, Rice Card class

public class Card implements java.io.Serializable {//Fields private Integer studentid;     Private Student Student;    Private String Cardnum; Constructors/** Default constructor */Public card () {}/** Minimal constructor */Public card (Student Stu    Dent) {this.student = student;        }/** Full Constructor */public Card (Student Student, String cardnum) {this.student = Student;    This.cardnum = Cardnum;    }//Property accessors Public Integer Getstudentid () {return this.studentid;    } public void Setstudentid (Integer studentid) {this.studentid = StudentID;    } public Student Getstudent () {return this.student;    } public void Setstudent (Student Student) {this.student = Student;    } public String Getcardnum () {return this.cardnum;    } public void Setcardnum (String cardnum) {this.cardnum = Cardnum; }}

4. Rice Card Configuration file

<?xml version= "1.0" encoding= "Utf-8"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ HIBERNATE-MAPPING-3.0.DTD "><!--mapping file autogenerated by MyEclipse persistence Tools-->
Second, the database operation

Here are just a few examples of insertions, and the others are similar to the above.

public static void Fun1 () {Session session = Hibernatesessionfactory.getsessionfactory (). Opensession (); Transaction trans  = Session.begintransaction (); Student stu = new Student (); Stu.setstudentname ("Tomcat"); Session.save (Stu); Card c  = new card (); C.setcardnum ("123456"); C.setstudent (Stu); Session.save (c); Trans.commit ();}

Previous post: http://blog.csdn.net/zhangpan19910604/article/details/46654233



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

Hibernate Getting Started Tutorial

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.