Persistence in java beans

Bean Persistence

A bean has the property of persistence when its properties, fields, and state information are saved to and retrieved from storage. Component models provide a mechanism for persistence that enables the state of components to be stored in a non-volatile place for later retrieval.

The mechanism that makes persistence possible is called serialization. Object serialization means converting an object into a data stream and writing it to storage. Any applet, application, or tool that uses that bean can then «reconstitute» it by deserialization. The object is then restored to its original state.

For example, a Java application can serialize a Frame window on a Microsoft Windows machine, the serialized file can be sent with e-mail to a Solaris machine, and then a Java application can restore the Frame window to the exact state which existed on the Microsoft Windows machine.

Any applet, application, or tool that uses that bean can then «reconstitute» it by deserialization.

All beans must persist. To persist, your beans must support serialization by implementing either the java.io.Serializable (in the API reference documentation) interface, or the java.io.Externalizable (in the API reference documentation) interface. These interfaces offer you the choices of automatic serialization and customized serialization. If any class in a class’s inheritance hierarchy implements Serializable or Externalizable , then that class is serializable.

Читайте также:  Как завершить код питон

Classes That Are Serializable

Any class is serializable as long as that class or a parent class implements the java.io.Serializable interface. Examples of serializable classes include Component , String , Date , Vector , and Hashtable . Thus, any subclass of the Component class, including Applet , can be serialized. Notable classes not supporting serialization include Image , Thread , Socket , and InputStream . Attempting to serialize objects of these types will result in an NotSerializableException .

The Java Object Serialization API automatically serializes most fields of a Serializable object to the storage stream. This includes primitive types, arrays,and strings. The API does not serialize or deserialize fields that are marked transient or static.

Controlling Serialization

You can control the level of serialization that your beans undergo. Three ways to control serialization are:

  • Automatic serialization, implemented by the Serializable interface. The Java serialization software serializes the entire object, except transient and static fields.
  • Customized serialization. Selectively exclude fields you do not want serialized by marking with the transient (or static ) modifier.
  • Customized file format, implemented by the Externalizable interface and its two methods. Beans are written in a specific file format.

Default Serialization: The Serializable Interface

The Serializable interface provides automatic serialization by using the Java Object Serialization tools. Serializable declares no methods; it acts as a marker, telling the Object Serialization tools that your bean class is serializable. Marking your class Serializable means you are telling the Java Virtual Machine (JVM) that you have made sure your class will work with default serialization. Here are some important points about working with the Serializable interface:

  • Classes that implement Serializable must have an access to a no-argument constructor of supertype. This constructor will be called when an object is «reconstituted» from a .ser file.
  • You don’t need to implement Serializable in your class if it is already implemented in a superclass.
  • All fields except static and transient fields are serialized. Use the transient modifier to specify fields you do not want serialized, and to specify classes that are not serializable.

Selective Serialization Using the transient Keyword

To exclude fields from serialization in a Serializable object mark the fields with the transient modifier.

Default serialization will not serialize transient and static fields.

Selective Serialization: writeObject and readObject

If your serializable class contains either of the following two methods (the signatures must be exact), then the default serialization will not take place.

private void writeObject(java.io.ObjectOutputStream out) throws IOException; private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;

You can control how more complex objects are serialized, by writing your own implementations of the writeObject and readObject methods. Implement writeObject when you need to exercise greater control over what gets serialized when you need to serialize objects that default serialization cannot handle, or when you need to add data to the serialization stream that is not an object data member. Implement readObject to reconstruct the data stream you wrote with writeObject .

The Externalizable Interface

Use the Externalizable interface when you need complete control over your bean’s serialization (for example, when writing and reading a specific file format). To use the Externalizable interface you need to implement two methods: readExternal and writeExternal . Classes that implement Externalizable must have a no-argument constructor.

Источник

Long Term Persistence of JavaBeans Components: XML Schema

The persistence scheme added in v 1.4 uses instances of the XMLEncoder class to write out files representing JavaBeans components (beans). Every file written by XMLEncoder uses the same XML schema, regardless of the beans the file contains. In this document we describe this schema so that implementations other than XMLEncoder and its corresponding reader, XMLDecoder , can be used to write and read compatible files.

This document presents the basic elements of each XML archive, followed by the tags necessary to represent objects. Next comes a section of abbreviations — tags that aren’t strictly necessary to write out an XML archive, but that make the archive shorter and easier to read. The final sections describe the top level of the XML archive, which can refer to properties of the decoder, and give a DTD for the XML schema.

You can find an example XML archive here: Browse.xml . This example is an archive of a simple application that accepts a URL and, using a JEditorPane , displays the HTML from that URL. You can read the archive and run the application using the following code:

For a ready-made program that reads XML archives, see TestInput.java . Sample scripts for running it on Win32 and UNIX are in xml.bat and xml , respectively.

Basic Elements

The element contains two informational attributes (not currently used by XMLDecoder ): the version attribute, which records the version of the Java platform that was used to write the archive, and the class attribute, which specifies the class of the decoder for which the document was written. The objects that the archive contains make up the body of this element and appear in the order they will be returned by calls to the decoder’s readObject method.

Objects

Objects are represented by the sequence of method calls that will be used to create them. Each element in the XML document represents a method call that either creates an object (an expression) or has a side effect on an object (a statement). Strings are treated as special kinds of expressions. Identifiers name objects so they can be referred to after their creation.

Strings are the atomic expressions of the XML document. The characters in a string form the body of an element with the tag. For example, the string «Hello, World» is represented by the following XML code:

Expressions and Statements

The class attribute can be used in tags to specify a class as the target of a static method. Constructors are represented as static methods that have the name new .

When an expression or statement contains expressions, the contained expressions are used as arguments to the method represented by the outer expression or statement. For example, to create an instance of the JButton class we can write the following:

Press me «Press me»JButton new JButton(«Press me»); new Press me Hello, world JButton b = new JButton(); b.setText(«Hello, world»);

When an expression contains tags (whether they denote expressions or statements) without class attributes, those tags must follow all other tags in the expression. Each non- expression is evaluated and the enclosing method is called with the results as arguments. The -tagged statements and expressions are then applied, in order, to the result.

For example, consider the following expression:

 JButton button1 = new JButton("Press me"); button1.setName("Greeting"); 

The ability to nest expressions and statements greatly reduces the number of identifiers that are needed to represent a given graph.

Identifiers

The following expression creates an identifier button1 , bound to an instance of the JButton class:

  idrefbutton1            JPanel panel1 = new JPanel(); JButton button1 = new JButton(); JLabel label1 = new JLabel(); panel1.add(button1); panel1.add(label1); label1.setLabelFor(button1); id 

For example, consider the following fragment:

    now long now = new Date().getTime(); 

Abbreviations

The preceding information is all you need to be able to write XML archives readable by XMLDecoder . To read all archives produced by XMLEncoder , however, you need to know about the abbreviations for primitives, null , Class objects, static constants, properties, indexes, and arrays.

The following tags represent both the primitive types and their corresponding wrapper classes:

  123  123 new Integer("123") 123 

Источник

Java Beans Persistence

In the world of software development, persistence is a crucial aspect. Persistence refers to the ability of an application to store and retrieve data from a database. Java Beans Persistence is a technology that helps Java developers to achieve this task easily and efficiently. In this blog post, we will discuss it in detail.

What is Java Beans Persistence?

Java Beans Persistence is a technology that enables Java developers to store and retrieve data from a database using Java Beans. Java Beans are reusable software components that manipulate visually by a builder tool.

Java Beans Persistence is also known as Java Persistence API (JPA), which is a specification to define the management of relational data in Java applications.

Why is Java Beans Persistence important?

Java Beans Persistence simplifies the process of working with a database. It provides a standard way to map Java objects to relational database tables. This means that developers can focus on writing Java code, without worrying about the underlying database structure. Developers can also take advantage of object-oriented programming concepts such as inheritance, polymorphism, and encapsulation.

How does Persistence in Java Beans work?

Java Beans Persistence works by mapping Java objects to database tables. This is done using a process called object-relational mapping (ORM). ORM is a technique that maps the data between a relational database and an object-oriented programming language. it provides a set of annotations that developers can use to define the mapping between Java objects and database tables.

Following is an example of how Java Beans Persistence works:

@Entity @Table(name = "employee") public class Employee < @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String department; // getters and setters >

In the code above, we have defined an Employee class with three fields: id, name, and department. The @Entity annotation specifies that this class should be mapped to a database table. The @Table annotation specifies the name of the table in the database. The @Id annotation specifies that the id field should be used as the primary key for the table. The @GeneratedValue annotation specifies that the id field should be generated automatically.

What are the benefits of Java Beans Persistence?

Java Beans Persistence has many benefits some of the important are given below:

  1. Simplified data access: It provides a standard way to access data from a database. This means that developers can write less code and focus on their business logic.
  2. Portability: It is platform-independent, which means that it can run on any operating system that supports Java.
  3. Increased productivity: It reduces the amount of code that developers need to write, which increases productivity and reduces development time.
  4. Easy maintenance: It provides a simple and easy-to-maintain codebase.

Conclusion

Java Beans Persistence is a powerful technology that simplifies the process of storing and retrieving data from a database. Developers can focus on writing Java code, without worrying about the underlying database structure. It provides a standard way to access data from a database, which makes it easier to maintain and more portable. If you’re a Java developer, Java Beans Persistence is a technology that you should definitely consider using.

Источник

Оцените статью