Java standard version of EJB persistence (1)

Source: Internet
Author: User
Since the drafting of the EJB 3.0 specification, Java classes have always had a single and standard persistence mechanism in both client and server applications. Java 5's annotations (annotation) function is easy to use. This article describes how to use it.
Keep Java classes; there are already many ways to do this, and the emergence of a standard for all applications is likely to benefit all developers. However, the challenge is to bridge the gap between the java standard edition and the Enterprise Edition and form a standard API that can be used for enterprise applications running in hosted containers, it can also be used to manage your own, container-less standard applications. Now we have the JSR-220-Enterprise Java Beans 3.0 specification. With the development of JSR-220, it is divided into two parts: ejb3.0 persistence and EJB 3.0 Core (and others ).
Ejb3.0 persistence is different from the previous EJB persistence. It includes annotations (annotations) and various pojo persistence developer experiences in Java 5.0.
When compiling ejb3.0 persistence, its specifications are still in the "final draft" phase, and some contents may change. Even so, now is a good opportunity for you to study many implementations in the specifications. The reference implementation can be found in glassfish, and the other is the annotation and entitymanager project that implements hibernate.
Now let's start with the basic thing: how to keep a class continuous in Java SE. The following is a simple example:
public class Address {
private String street;
private String postcode;

public Address() {}

public String getStreet() { return street; }
public void setStreet(String street) { this.street = street; }

public String getPostcode() { return postcode; }

public void setPostcode(String postcode) { this.postcode = postcode; }
}
In order to put the class into an object that can be persistently maintained, we added the @ entity annotation at the beginning to make it persistent, as shown below:
import javax.persistence.Entity;

@Entity
public class Address {
Now, if your first response is "Hi, what is @ something", let me briefly introduce the annotation. Historically, Java has never been able to embed metadata in code. Javadoc is a source data used to generate documents. It is used to use the @ prefix mark in the comment block. This concept is built on XDoclet, which is used to carry their own metadata. Another alternative is to match XML files of classes. For example, in addition to using classes, Hibernate also uses a. HBM. xml file with the same name as the class to carry its own ing information. Both of these technologies are very useful, but for Java 5, people prefer to see a more verifiable and discoverable cohesion compiler at runtime; this is why annotations appears. In this article, you need to know what the annotation is, how to add metadata, and how to persistently map a class.
@ Entity annotation is used to mark the classes to be maintained. To facilitate retrieval, pojo provides a primary key for each requirement. A common method to do this is to introduce a long field as the key. So we will add this to the class:
private Long id;
@Id
@GeneratedValue
public Long getId() { return id; }
public void setId(Long id) { this.id=id; }
@ ID annotation indicates who the primary key field is, and @ generatedvalue annotation requires the persistence layer to generate a value for this field. This is all we need to do. Now we can start using address.
Address address=new Address();
address.setPostcode("ZZ9 99Z");
address.setName("John Doe");
To maintain the address, we need to obtain an entitymanager for each unit of work required to process the data. Persistence in Java EE and Java SE is quite different in this regard. In Java EE, there will be a lot of annotations for the surrounding framework to manage entities. In Java SE, this task is handed over to developers who can obtain entitymanager. We obtained an entitymanager from entitymanagerfactory.
EntityManagerFactory emf=null;

EntityManager em=emf.getEntityManager();
In the future, let's look back at where the entitymanagerfactory is obtained. Now, we assume it has been initialized and we can get the entitymanager from it. When you keep Java SE, you are still responsible for managing database transactions; you must start and end database transactions, so let's start from acquiring a transaction:
EntityTransaction tx=em.getTransaction();
tx.begin();
Now we need entitymanager to keep our address.
em.persist(address); 
Then execute the transaction and close entitymanager;
tx.commit();
em.close();
After completion, a person ID will be assigned to us, which will be written to the database. This method of obtaining and executing transactions is quite common for any code used to modify the Object Persistence State. To ensure reliability, if a problem like the following occurs, it should prompt an exception and perform rollback.
EntityManager em=emf.getEntityManager();
EntityTransaction tx=em.getTransaction();
try {
tx.begin();
// Do saves or modifications here
tx.commit();
} catch (Exception e) {
if(tx.isActive()) tx.rollback();
System.err.println("Error:"+e);
} finally {
em.close();
}
Assume that this code is placed around the example below for modifying the database. To retrieve data, you only need to obtain the entitymanager.
To retrieve the previously saved address, we can use the ID as a reference. We do not need transactions from entitymanager, so this process becomes very simple:
Address address2=em.find(Address.class,address.getId()); 
If we want to find an address by postal code, we can use ejbql, The EJB query language, to define the query and use entitymanager to create the query.
Query q=em.createQuery("select address from Address as address where postcode=:param"); 
This query will start to find the address that meets the postal code requirements (the address is kept, and the returned result is used as the address object), that is, the address that meets the "Param" parameter as "to be set. Now we can set this parameter:
q.setParameter("param",name); 
To obtain the results, call getresultlist for the query. If we want to get 0 or more results, or we only want to get 1 result.
List<Address> l=(List<Address>)q.getResultList(); 
or 
Address addresstochange=(Address)q.getSingleResult(); 
The last thing we need to do is to change the address and merge the changes into the database. Suppose we have found an address through the previous query.
addresstochange.setStreet("A Different Street");

em.merge(addresstochange);
… 
Related Article

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.