Persistent classes)

Source: Internet
Author: User
Tags compact
Chapter 4 persistence class)

In applications, the customer and Order Classes used to implement business problem entities (for example, in e-commerce applications) are persistence classes. It cannot be considered that all persistent instances are in a persistent state. The status of an instance may also be instantaneous or out of management.

If these persistence classes follow some simple rules, Hibernate can work best. These rules are called the simple traditional Java object (pojo: plain old Java object) programming model. None of these rules are required. In fact, hibernate3 has almost no idea about your persistence class. You can use other methods to express the domain model: for example, useMapThe tree structure of the instance.

5.1. A simple pojo example

Most Java programs use a persistence class to represent cats.

package eg;import java.util.Set;import java.util.Date;public class Cat {    private Long id; // identifier    private Date birthdate;    private Color color;    private char sex;    private float weight;    private int litterId;    private Cat mother;    private Set kittens = new HashSet();    private void setId(Long id) {        this.id=id;    }    public Long getId() {        return id;    }    void setBirthdate(Date date) {        birthdate = date;    }    public Date getBirthdate() {        return birthdate;    }    void setWeight(float weight) {        this.weight = weight;    }    public float getWeight() {        return weight;    }    public Color getColor() {        return color;    }    void setColor(Color color) {        this.color = color;    }    void setSex(char sex) {        this.sex=sex;    }    public char getSex() {        return sex;    }    void setLitterId(int id) {        this.litterId = id;    }    public int getLitterId() {        return litterId;    }    void setMother(Cat mother) {        this.mother = mother;    }    public Cat getMother() {        return mother;    }    void setKittens(Set kittens) {        this.kittens = kittens;    }    public Set getKittens() {        return kittens;    }        // addKitten not needed by Hibernate    public void addKitten(Cat kitten) {    kitten.setMother(this);kitten.setLitterId( kittens.size() );         kittens.add(kitten);    }}

Here we should follow four main rules:

5.1.1. Declare accessors and mutators for persistent Fields)

CatThe access method is declared for all its persistent fields. Many other ORM tools persist instance variables directly. We believe that separating such implementation details from the persistence mechanism is much better. The method name in the following format is recognized for Hibernate Persistence JavaBeans-style attributes:Getfoo,IsfooAndSetfoo. If needed, you can always switch the access method of the specified attribute's indicator field.

AttributeNoTo be declared as public. Hibernate is used by default.ProtectedOrPrivateThe get/Set Method of to persist attributes.

5.1.2. Implement a default (No parameter) constructor)

CatThere is a construction method without parameters. All persistence classes must have a default constructor (which may not be public), so that hibernate can useConstructor. newinstance ()To instantiate them. In hibernate, we recommend that the constructor at least bePackage).

5.1.3. Provide an identifier property (optional)

CatThere is an attribute calledID. This property maps to the primary key field of the database table. This attribute can be called by any name. Its type can be any original type, the original type of packaging type,Java. Lang. StringOrJava. util. Date. (If your old-fashioned database tables have federated primary keys, you can even use a user-defined class that has these types of attributes. For more information, see the following section on Federated identifiers .)

The identifier property is optional. You don't need to worry about it, so that hibernate can track Object Recognition internally. This attribute is not recommended.

In fact, some functions only work for classes that declare the identifier property:

  • Communication re-Association (with sessions) of Managed Objects (cascade updates or cascade joins)-see section 11.11 "Transitive persistence )"

  • Session. saveorupdate ()

  • Session. Merge ()

We recommend that you declare the same name for the persistence class. We also recommend that you use a type that can be null (that is, not the original type.

5.1.4. Use a non-final class (optional)

Proxy (proxies)It is an important function of hibernate. It depends on the conditions that the persistence class is non-final, or an interface declared as public by all methods is implemented.

You can use hibernate to persist a program that does not implement any interfaces.FinalClass, but you cannot use a proxy to delay associated loading, which limits your selection of performance optimization.

You should also avoid declaring in a non-final classPublic final. If you want to usePublic finalMethod class, you must setLazy = "false"To explicitly disable the proxy.

5.2. Implement inheritance (inheritance)

Child classes must also comply with the first and second rules. It starts from the superclassCatInherits the identity attribute.

package eg;public class DomesticCat extends Cat {        private String name;        public String getName() {                return name;        }        protected void setName(String name) {                this.name=name;        }}
5.3. Implementation Equals ()And Hashcode ()

If you have the following requirements, you must reloadEquals ()AndHashcode ()Method:

  • Want to put the persistent class instanceSetMedium (this is recommended when multi-value Association is expressed)

  • You want to reuse a takeover instance

Hibernate ensures that the persistence identifier (Database row) is equivalent to the Java identifier only within a specific session range. Therefore, if we wantSetWith clear semantics, we must implementEquals ()AndHashcode ().

ImplementationEquals ()/Hashcode ()The most obvious method is to compare the values of two object identifiers. If the values are the same, the two objects correspond to the same row of the database, so they are equal (if both are addedSetInSet). Unfortunately, this method cannot be used for the generated identifiers. Hibernate only assigns identifiers to those persistent objects. A newly created instance will not have any identifiers. In addition, if an instance is not saved (unsaved) andSet. IfEquals ()AndHashcode ()Is implemented based on the ID value, the hash code will change, in violationSet. We recommend that you go to the hibernate site to view all the discussions on this issue. Note that this is not a hibernate issue, but a general question of Java object identifiers and equal semantics.

We recommend that you useBusiness key equality)To achieveEquals ()AndHashcode (). If the business key value is equal,Equals ()The method only compares the attributes from the business key. A business key is identified in the real world (BornCandidate Key.

public class Cat {    ...    public boolean equals(Object other) {        if (this == other) return true;        if ( !(other instanceof Cat) ) return false;        final Cat cat = (Cat) other;        if ( !cat.getLitterId().equals( getLitterId() ) ) return false;        if ( !cat.getMother().equals( getMother() ) ) return false;        return true;    }    public int hashCode() {        int result;        result = getMother().hashCode();        result = 29 * result + getLitterId();        return result;    }}

Note that the business key does not have to be fixed as the primary key of the database (see section 12.1.3 "follow Object Identity (considering Object Identity )"). For business keys, immutable or unique attributes are good candidates.

5.4. Dynamic Model (dynamic models)

Note that the following features are currently based on lab considerations and may change in the future.

The persistence object in the runtime does not need to be represented like a pojo class or a JavaBean object. Hibernate also supports dynamic models (used during runtime)MapOfMap) And the entity representation like the dom4j tree model. In this way, you don't need to write persistence classes, just write the ing file.

Hibernate works in normal pojo mode by default. You can use configuration optionsDefault_entity_mode, For specificSessionfactoryTo set a default Object Representation mode. (See hibernate configuration attributes.
"Href =" http://docs.huihoo.com/hibernate/reference-v3_zh-cn/session-configuration.html#configuration-optional-properties "tppabs =" http://www.hibernate.org/hib_docs/v3/reference/zh-cn/html/session-configuration.html#configuration-optional-properties "> table 4.3" hibernate configuration attributes ".)

UseMap. First, in the ing file, declareEntity-nameTo replace (or add) a class name.

Note: although the target class name is used to declare the association, the associated target type can be a dynamic entity in addition to pojo.

In useDynamic-MapIsSessionfactoryAfter the default object mode is set, it can be used at runtime.MapOfMap.

Session s = openSession();Transaction tx = s.beginTransaction();Session s = openSession();// Create a customerMap david = new HashMap();david.put("name", "David");// Create an organizationMap foobar = new HashMap();foobar.put("name", "Foobar Inc.");// Link bothdavid.put("organization", foobar);// Save boths.save("Customer", david);s.save("Organization", foobar);tx.commit();s.close();

The advantage of dynamic ing is that the prototype can quickly change the time without the entity class implementation. However, you cannot perform type checks during the compilation period and may handle many runtime exceptions. Thanks to the hibernate ing, the schema of the data base can be easily normalized and rationalized, and the latest implementation of the correct domain model can be added later.

The entity representation mode can also be used in eachSessionBased on settings:

Session dynamicSession = pojoSession.getSession(EntityMode.MAP);// Create a customerMap david = new HashMap();david.put("name", "David");dynamicSession.save("Customer", david);...dynamicSession.flush();dynamicSession.close()...// Continue on pojoSession

Note thatEntitymodeCallGetsession ()YesSessionIn the API, insteadSessionfactory. In this way, the newSessionShares underlying JDBC connections, transactions, and other context messages. This means that you do not needSessionCallingFlush ()AndClose ()Similarly, the transaction and connection processing are handed over to the original unit of work.

For more information about XML Representation, see Chapter 19th.XML ing.

Todo: In the property and proxy packages, you can extend the file framework.

 

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.