An example of a one-to-one correlated query annotation @onetoone

Source: Internet
Author: User

The related query of the table is more complicated, the application of the scene is many, this article according to own experience explains the @onetoone annotation attribute in the project application. The intention of a blog to change the additions and deletions to write together, but in the change encountered some problems, it is very interesting, so write down the second special talk about changes.

One, one-way @onetoone instance detailed

Suppose a scene where a person can only adopt a pet, according to the person can find the pet, and look at the pet information, the relationship is one-way.

Create a data table structure for people and pets. : Person,pet Database Build table.

Create an entity.

Person.java

Package Com.my.model;import Java.io.serializable;import Javax.persistence.cascadetype;import Javax.persistence.column;import Javax.persistence.entity;import Javax.persistence.fetchtype;import Javax.persistence.foreignkey;import Javax.persistence.generatedvalue;import Javax.persistence.id;import Javax.persistence.joincolumn;import Javax.persistence.onetoone;import Javax.persistence.table;import Org.hibernate.annotations.cascade;import org.springframework.beans.factory.annotation.Autowired; @Entity @table ( name = ' person ') public class person implements serializable{@Id//ID automatically generated @generatedvalue@column (name = "id") Private Long I D; @Column (name = "name") Private String name;//cascade: Table cascade operation @onetoone (Fetch=fetchtype.lazy,cascade = Cascadetype.all //JPA Note: One-to-two relationship//referencedcolumnname: Reference column name, default is the list's primary key//nullable= can be empty,//insertable: Whether it can be inserted,//updatable: Whether it can be updated columndefinition= column definition,//foreignkey= foreign key @JoinColumn (name= "pet_id", referencedcolumnname= "id", Nullable=false) Private Pet Pet; @OverridepublicString toString () {return "person [id=" + ID + ", name=" + name + ", pet=" + pet + "]";}} 

Pet.java

Package Com.my.model;import Java.io.serializable;import Javax.persistence.column;import javax.persistence.Entity; Import Javax.persistence.generatedvalue;import javax.persistence.id;import javax.persistence.Table; @Entity @table ( Name = "Pet") public class pet  implements serializable{@Id//ID auto-generated @generatedvalue@column (name = "id") Private Long ID ; @Column (name = "Pet_name") private string PetName; @Column (name = "Pet_class") private string petclass;//omit Set,get method. @Overridepublic String toString () {return "Pet [id=" + ID + ", petname=" + PetName + ", petclass=" + Petclass + "]";}}

The interface definition for annotation @onetoone is as follows:

Public interface Onetoone extends Annotation {public abstract Class targetentity ();p ublic abstract cascadetype[] Cascade ( );p ublic abstract fetchtype Fetch ();p ublic abstract Boolean optional ();p ublic abstract String mappedby ();p ublic Abstract Boolean orphanremoval ();}

Attributes of the annotation @onetoone:

Cascade: An association property that defines the operation of a Cascade object after the current class object has been manipulated. In this example, the definition is: Cascadetype.all, the current class additions and deletions after the change, the association class followed by additions and deletions to investigate.

Fetch attribute: A property of type Fetchtype.  Selectable items include: Fetchtype.eager and Fetchtype.lazy. Fetchtype.eager indicates that the relationship class (in this case the OrderItem class) is loaded at the same time that the main class is loaded, fetchtype.lazy that the relationship class is loaded when it is accessed. The default value is Fetchtype.lazy.

Mappedby: A domain that has an association, if the relationship is a one-way, two-way relational table, then the party having the relationship has the ability to establish, release, and update the relationship with the other party, and the other party has no, only passive management, this attribute is defined in the relationship's owner. Bidirectional @onetoone, bidirectional @onetomany, bidirectional @manytomany.

Interface definitions for annotation @joincolumn:

Public interface Joincolumn extends Annotation {public abstract string name ();p ublic abstract String referencedcolumnname ();p Ublic Abstract Boolean unique ();p ublic Abstract Boolean nullable ();p ublic Abstract Boolean insertable ();p ublic Abstract Boolean updatable ();p ublic abstract String columndefinition ();p ublic Abstract String table ();p ublic Abstract ForeignKey ForeignKey ();}

Attributes of the annotation @joincolumn:

Name property: The names of the foreign key columns, by default: The field name of the referencing entity + "_" + the name of the referenced primary key column. General can also be customized, generally see the name of the meaning, you can use the default value.

Referencedcolumnname Property: Reference column, the default value is the primary key of the associated table. For example, if you can define pet_name as a reference column, then the value of the name of the pet is associated with this column.

Create class: Tablerelationcontroller

Package Com.my.controller;import Javax.annotation.resource;import Org.springframework.web.bind.annotation.requestbody;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.restcontroller;import Com.alibaba.fastjson.jsonobject;import Com.my.model.goodinfoentity;import com.my.service.tablerelationservice;/** * Seven correspondence for the test table * @author BY_WW * */@ Restcontroller@requestmapping (value = "/tablerelation") public class Tablerelationcontroller {@Resourceprivate Tablerelationservice tablerelationservice;//increased @RequestMapping (value = "/save") public Long Save (@RequestBody jsonobje    CT record) throws Exception {return tablerelationservice.save (record);        }//query @RequestMapping (value = "/query") public jsonobject query (@RequestBody jsonobject record) throws Exception {    Return Tablerelationservice.getpet (record); }//Delete @RequestMapping (value = "/delete") public Long Delete (@RequestBody jsonobject record) throws Exception {return tablerelationservice.delete (record);        }//Change @RequestMapping (value = "/update") Public Long update (@RequestBody jsonobject record) throws Exception {    Return tablerelationservice.update (record); }}

To create the Tablerelationservice class:

Package Com.my.service;import Javax.annotation.resource;import Javax.persistence.entitymanagerfactory;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.service;import Org.springframework.transaction.annotation.transactional;import Com.alibaba.fastjson.json;import Com.alibaba.fastjson.jsonobject;import Com.my.dao.personjpa;import Com.my.dao.petjpa;import Com.my.model.Person; Import Com.my.model.Pet; @Servicepublic class Tablerelationservice {@Resourceprivate PERSONJPA personjpa;@  Resourceprivate PETJPA PETJPA;  Private Sessionfactory sessionfactory;      @Autowired public void Someservice (Entitymanagerfactory factory) {if (Factory.unwrap (sessionfactory.class) = = null) {    throw new NullPointerException ("Factory is not a hibernate factory");  } this.sessionfactory = Factory.unwrap (Sessionfactory.class); Public Long Save (Jsonobject record) {//assemble personperson person = nEW person ();p Erson.setname (record.getstring ("PersonName")); Jsonobject petobj = Record.getjsonobject ("pet"), if (null! = Petobj) {Pet pet = new Pet ();p Et.setpetname (petobj.getstring ( "PetName"));p Et.setpetclass (petobj.getstring ("Petclass"));p Erson.setpet (PET);} Personjpa.save (person); return 4l;} Public Jsonobject Getpet (Jsonobject record) {Person person = Personjpa.findone (Record.getlongvalue ("id")); System.out.println (Person.tostring ()); return (Jsonobject) Json.tojson (person);}  Public Long Delete (Jsonobject record) {Personjpa.delete (Record.getlongvalue ("id")); return 4l;} @Transactionalpublic Long Update (Jsonobject record) {Session session = Sessionfactory.getcurrentsession ();//Session         Session = Sessionfactory.opensession ();                  Session.begintransaction ();                 Person Personrecord = Session.get (Person.class, record.getlongvalue ("id"));                Personrecord.setname (record.getstring ("PersonName"));    Jsonobject petobject = Record.getjsonobject ("pet");    if (petobject! = null) {//If the pet here is empty pet Petrecord = null;        if (personrecord.getpet () = null) {Petrecord = Session.get (Pet.class, Personrecord.getpet (). GetId ());          } petrecord.setpetname (Petobject.getstring ("PetName"));                  Petrecord.setpetclass (petobject.getstring ("Petclass")); }personjpa.save (Personrecord); return 4l;}}

Note: It is important to note that if there is no configuration, an exception will occur when the associated table changes.

Org.hibernate.HibernateException:Could not obtain transaction-synchronized Session for current thread

This is required in the spring transaction implementation to determine whether the transaction in the current thread is synchronized, and when there is no transaction, the method that determines whether the synchronization is returned false because the get returns the initial null value, resulting in the throw of a could not obtain Transaction-synchronized Session for the exception of the current thread, there are two workarounds:

1) Add things to control.

@Transactional

2) Regenerate session.

Session session = Sessionfactory.opensession ();

In the configuration file:

spring.jpa.properties.hibernate.current_session_context_class= Org.springframework.orm.hibernate4.SpringSessionContext

  

Test: Postman Send request:

Increase:

{"PersonName": "Steven", "pet": {"PetName": "Wang Wang", "Petclass": "Dog"}}

 

Inquire:

{"id": 19}

 

{"    id": +,    "pet": {        "id": "        petclass": "Dog",        "PetName": "Wang Wang"    },    "name": "Steven"}

Delete:

{"id": 19}

 

Change:

This changes the Petname,petclass

{"id": +, "personname": "Steven",  "pet": {    "petname": "Steven4",    "Petclass": "Cow"    }}

  

An example of a one-to-one correlated query annotation @onetoone

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.