Kodo EJB: Implementing association Relationships between classes and classes

Source: Internet
Author: User
Tags define definition commit inheritance key mysql uppercase character mysql database

In addition to the inheritance relationship between objects and objects, there is also an association: including a pair of more than one or one pairs of many pairs of one and many pairs, because these relationships in the Kodo EJB implementation of the principle is basically similar, so this article mainly on a pair of related relations in depth, At the same time, through simple examples of analysis and practice in detail how to use the annotations provided in the Kodo EJB to define the association between classes and classes, the remaining One-to-many, Many-to-many and Many-to-many three relationships will only be explained at the end of the article, please refer to the implementation process of one-to-one relationship.

In an object-oriented world, a one-to-one relationship between Class A and Class B must meet the following criteria:

    1. Object A1 references an object B1

    2. Class A other object an cannot apply the same object B1

In a relational database, we typically use a unique foreign key to achieve one-to-one relationships, as illustrated in the following illustration.



Let's begin by introducing the knowledge associated with Kodo EJB and one-to-one relationship implementation, and to illustrate the need, we first define a virtual scene.

  Simulation Scene

We assume that to complete a library management system, the system needs to manage a lot of books, we need to record the basic information such as the number of books, titles, publication dates and other basic information, but also need to record the preface, order and other information.

Suppose we design the book as a Class (book) according to the above requirements, including the number and name of the books, two attributes, and design the preface information of the book into another Class (Bookextend), which includes the number of the book and two attributes of the preface information. Since a book has a preface and it is impossible to have other books the preface will be the same as him, so the book and the Bookextend naturally form a one-to-one relationship. The properties of these two classes, as well as the relationships between classes, are shown in the following illustration.



Note

1, in order to illustrate the simple, example design, each object only select the necessary attributes.

2, the above design only for the demonstration of the requirements and deliberately adopted, does not represent a reasonable design.

Kodo EJB and one-to-one relationship implementation related content

In Kodo EJBs, we can use simple onetoone annotations to declare a one-to-one relationship between classes and classes, and optionally, we can use joincolumn annotations to declare what fields are used between the tables of two classes to associate.

Onetoone

The Onetoone annotation provides 5 properties for developers to define the details of a one-to-one relationship between classes and classes.

  1. Targetentity

    The attribute of the class type.

    Defines the type of the relationship class, which defaults to the class type of the member property, so there is usually no need to provide a definition.

  2. Mappedby

    A property of type string.

    Defines a two-way relationship between classes. If there is a one-way relationship between classes, there is no need to provide a definition, and if there is a two-way relationship between classes and classes, we need to use this attribute to define the problem that might cause data consistency. For example, in the above demo scenario, we just define that the book class has bookextend attributes, and the bookextend does not have the book attribute, then they are one-way and how the book attribute is defined in Bookextend. Then the book and the Bookextend form a two-way relationship.

  3. Cascade

    Cascadetype[] Type.

    This property defines the cascading relationships between classes and classes. A defined cascade relationship is considered by the container to be the same for the current class object and its associated class object, and the relationship is recursively invoked. For example: The book and Bookextend have a cascading relationship, so deleting the book deletes the corresponding Bookextend object at the same time. If the bookextend also has a cascading relationship with other objects, such an operation will continue recursively.

    The value of the cascade can only be from cascadetype.persist (new Cascade), Cascadetype.remove (cascade Delete), Cascadetype.refresh (cascade refresh), Cascadetype.merge (cascade Update) Select one or more. Another option is to use Cascadetype.all to indicate that all four items are selected.

  4. Fatch

    Properties of the Fetchtype type.

    Selectable items include: Fetchtype.eager and Fetchtype.lazy. The former indicates that a relational class is loaded at the same time as the main class is loaded, which means that the relational class is loaded when it is accessed. The default value is Fetchtype.eager.

  5. Optional

    A Boolean type of property.

    Defines whether the association class must exist. If set to False, this property cannot be set to NULL. The default value is true.

Examples of onetoone usage

  Joincolumn

The Joincolumn annotation is used to define what fields the main class is associated with in the database by the primary key of the relationship class, which is optional, and if not provided, Kodo is associated with the object name _id and the associated table (in simple cases). For example, the bookextend of the class book in the demo scenario is not declared using the Joincolumn annotation, and when we use the Mapping tool tool provided by the Kodo EJB to generate the table, the book class corresponds to the table book that is automatically added to the column Bookextend_ ID, and its type will be the same as the primary key field ID type of the bookextend corresponding table.

There are two properties in the Joincolumn annotation: Name and Referencedcolumnname properties.

    1. Name

      String type.

      It is used to specify the name of the field in the table corresponding to the main class that is associated with the primary key of the relational class, for example, in the previous example, we do not want to use the default bookextend_id field name to associate, and we can use the Joincolumn annotation Bookextend property in the book class. Set the Joincolumn annotation for the name you want, such as extendid or whatever.

    2. Referencedcolumnname

      String type.

      Specifies the name of the field in the association table that is associated with the primary table. is primarily used to set a situation that differs from a primary key field. For example, the Bookextend table is associated with an ID by default, but it now needs to be associated with another field, and we can provide that property.

Examples of joincolumn usage

  Write persistent classes that meet the requirements

Now we start by writing the book class and the Bookextend class that match the requirements in the simulation scenario based on what is described in the previous section, which is all the code for the two classes that the author wrote, and the code adds a lot of comments to make it easier to understand.

Book Class

Package Org.vivianj.kodo.examples.beans; Import Javax.persistence.Basic; Import Javax.persistence.CascadeType; Import Javax.persistence.Column; Import javax.persistence.Entity; Import Javax.persistence.GeneratedValue; Import Javax.persistence.GenerationType; Import Javax.persistence.Id; Import javax.persistence.Inheritance; Import Javax.persistence.InheritanceType; Import Javax.persistence.JoinColumn; Import Javax.persistence.OneToOne; /** * Book is used to characterize the books in the system, and he has three attributes
* ID-Book number, the book number will be automatically generated by the MySQL database
* Name-Title
* bookextend– extended information, and Bookextend is a one-to-one (onetoone) relationship/////////* Entity annotation indicates that the class is a persisted class, and the Name property is the unique name of the entity in the query, by default the class name/@Entity (name = "book")//The Name property of the table annotation specifies the name of the data table that the persisted class corresponds to, and the default datasheet name and class name remain the same, in order to
* Enhance the portability of the code, we recommend that in the Name property using the capital letter/* Inheritance annotation strategy determines the relationship between the persisted object and the datasheet, optionally including Single_table, joined, and Table_per _class, we use joined///////////////////* Table_per_class:strategy set to this option to indicate that each class uses a table, that is, the first case described above, * * Single_table:strategy set to the The item means that all classes and their subclasses share a single table, which is the second case described above. * * Joined:strategy set to this option means that each class uses the child table to save the child analogy to the parent class's extra attributes, which is the third case described above. * * @Inheritance ( Strategy = inheritancetype.joined) public class Book {/* Id note indicates that the field is an identity field//@Id/* Generatedvalue annotation defines how the identity field is generated, our demo department The ID is automatically generated by the MySQL database field, so select Generationtype.identity/@GeneratedValue (strategy = generationtype.identity)/* The Name property of the Column annotation defines the names of the data fields for the class attribute, and in order to maximize the independence of the system and the database, it is recommended to use uppercase/@Column (name = "ID") public int ID; /* Basic Note indicates that the property is a basic attribute//@Basic The Name property of the Column annotation defines the names of the data fields for the class attribute, and to maximize the independence of the system and the database, it is recommended to use the uppercase character/@Column (name = NAM E ") public String name = NULL; /* Use onetoone annotation to indicate that the property and book class form a one-to-one relationship, and the option property of the Onetoone annotation is set to true to indicate that the object can not exist. The Cascade property is set to Cascadetype.all, which means that the book and Bookextend objects are cascaded to create, update, delete, refresh/@OneToOne (optional=true,cAscade=cascadetype.all)/* Use joincolumn annotation to set the association field between two objects corresponding database tables * * * @JoinColumn (name= "Extendid", referencedcolumnname= " ID ") public bookextend bookextend; }

Bookextend class

Package Org.vivianj.kodo.examples.beans; Import Javax.persistence.Basic; Import Javax.persistence.Column; Import javax.persistence.Entity; Import Javax.persistence.GeneratedValue; Import Javax.persistence.GenerationType; Import Javax.persistence.Id; Import javax.persistence.Inheritance; Import Javax.persistence.InheritanceType; Import Javax.persistence.JoinColumn; /** * Bookextend is used to characterize the extended information of a book in the system, and he has two attributes:
* ID-Extended information number, extended information number will be automatically generated by MySQL database
* Name-Foreword information of the book
*//////////* Entity annotation indicates that the class is a persisted class the Name property is the unique name of the entity in the query, and the default is the name of the class name/@Entity/* Table Note Specifies the names of the data tables that the persisted class corresponds to, and the default datasheet name and class name are consistent for
* Enhance the portability of the code, we recommend that in the Name property using the capital letter/* Inheritance annotation strategy determines the relationship between the persisted object and the datasheet, optionally including
* Single_table, joined and Table_per_class, we use the joined */* Table_per_class:strategy set to this option to indicate that each class uses a table, which is the first case mentioned above. * Single_table:strategy set to this option indicates that all classes and their subclasses share a single table, that is, the second case described above. * * Joined:strategy set to this option means that each class uses the child table to save the child analogy to the parent class's extra properties. Which is the third case mentioned above. * * @Inheritance (strategy = inheritancetype.joined) public class Bookextend {/* Id note indicates that the field is an identity field/* @Id/* G The Eneratedvalue annotation defines how the identity field is generated, and the IDs in our demo system are automatically generated by the MySQL database field, so select Generationtype.identity/@GeneratedValue (strategy = generationtype.identity)/* The Name property of the Column annotation defines the names of the data fields for the class attribute, and in order to maximize the independence of the system and the database, it is recommended to use uppercase/@Column (name = "ID") public int id; /* Basic Note indicates that the property is a basic attribute//@Basic The Name property of the Column annotation defines the names of the data fields for the class attribute, and to maximize the independence of the system and the database, it is recommended to use the uppercase character/@Column (name = NAM E ") public String name = NULL; }
   Calling code

In the code above, we are ready to meet the required persistence class, let's look at how the two classes are invoked in the Kodo EJB to complete the creation, modification, and deletion of the book class and Bookextend class.

Due to the length of the relationship, these do not describe how to compile, strengthen these classes and prepare the appropriate configuration file to complete the development of the entire project environment, this part of the content please refer to my other article " Kodo EJB: Persistence layer Framework conforming to EJB3 specification

   Cascade New Object

The following code shows the case where the book class object and the Bookextend class object are persisted at the same time as the persist method that calls the book class only. Note the part that is identified in bold.
/* Obtain an EJB entity Manager/Entitymanagerfactory EMF = persistence.createentitymanagerfactory (null); Entitymanager em = emf     . Createentitymanager (persistencecontexttype.extended);/* Start transaction/em.gettransaction (). Begin ();    
   cascading Update object state

The following code demonstrates the need to call the book class's Merge method to update both the book class object and the Bookextend class object state. Note the part that is identified in bold.
/* Obtain an EJB entity Manager/Entitymanagerfactory EMF = persistence.createentitymanagerfactory (null); Entitymanager em = emf     . Createentitymanager (persistencecontexttype.extended);/* Start transaction/em.gettransaction (). Begin ();    /* Create a new book object/book book = novel Book (); /* Set the id attribute of the book object * * book.id= 1; Book.name = "Kodo Introduction"; * * Create a new Bookextend object/bookextend bookextend = Bookextend (); /* Set Object Properties * * bookextend.id=1; Bookextend.name = "Kodo is divided into Kodo ejb and Kodo JDO ..."; /* Establish the relationship between the object * * book.bookextend = bookextend; /* Persisted object, only needs to call the book object's merge method, does not need to handle the Bookextend object separately/em.merge (book); /* End Transaction/em.gettransaction (). commit (); Em.close ();  
Cascading Delete Objects
/* Obtain an EJB entity Manager/Entitymanagerfactory EMF = persistence.createentitymanagerfactory (null); Entitymanager em = emf     . Createentitymanager (persistencecontexttype.extended);/* Start transaction/em.gettransaction (). Begin (); /* Use the query to delete objects, you can not add objects to memory, improve efficiency * * Query q = Entitymanager     . CreateQuery ("Delete from book C WHERE c.id=:id"); int id = Book.id; /* Set the deleted book object's primary KEY value * * * Q.setparameter ("id", id); /* When the method is invoked, the Bookextend object corresponding to the book object will be deleted at the same time. * Q.executeupdate (); /* End Transaction/em.gettransaction (). commit (); Em.close ();  
   Several other related relationships

A pair of many

We can use Onetomany annotations to describe a one-to-many relationship between classes and classes, Onetomany annotations have four attributes: Targetentity, Mappedby, Cascade, and Fetch. The specific meaning of these four attributes corresponds to the same attribute one by one of the onetoone annotation annotation, please refer to the contents in the previous section.

More to one

We can use Manytoone annotations to describe a many-to-many relationship between classes and classes, Manytoone annotations have four attributes: Targetentity, Cascade, Fetch, and optional. The specific meaning of these four attributes corresponds to the same attribute one by one of the onetoone annotation annotation, please refer to the contents in the previous section.

Many to many

We can use Manytomany annotations to describe a many-to-many relationship between classes and classes, Manytomany annotations have four attributes: Targetentity, Mappedby, Cascade, and Fetch. The specific meaning of these four attributes corresponds to the same attribute one by one of the onetoone annotation annotation, please refer to the contents in the previous section.

   Summary

In addition to inheriting relationships between objects and objects, there are also related relationships, including a pair of one or one pairs, multiple pairs of one and many-to-many relationships, in this article, the author takes a one-to-one relationship as an example, combined with simple examples, describes in detail how to use annotations to describe the relationship between classes and classes in a Kodo EJB framework. and implements cascading properties of class operations. The last simple description of the Kodo EJB in the implementation of a One-to-many, Many-to-many and Many-to-many need to use the annotation, the specific implementation please refer to the contents of the document to complete their own.

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.