Hibernate--entity.hbm.xml

Source: Internet
Author: User

first, Brief

1. An object-relational mapping file that maps an XML file between an entity class and a relational database data Table.

2. With the Entity.hbm.xml mapping file, Hibernate can understand the relationship between persisted classes and data tables, as well as the correspondence between persisted class properties and data table Columns.

3. Map the primary key and map the association Relationship.

second, each node

<hibernate-mapping>    <class>        <ID></ID>        < propertyname=""></ property>        <Many-to-onename=""></Many-to-one>        <one-to-onename=""></one-to-one>        <Setname="">            <Key></Key>            <One-to-many></One-to-many>            <Many-to-many></Many-to-many>        </Set>        <Subclass></Subclass>        <Joined-subclass>            <Key></Key>        </Joined-subclass>        <Componentname=""></Component>        < anyId-type=""name="">            <columnname=""></column>            <columnname=""></column>        </ any>    </class></hibernate-mapping>

Description: multiple class nodes can be defined in a Entity.hbm.xml, but typically only one is Defined.

1.

(1) Package

If there are multiple class nodes within the Hibernate-mapping node, This property can be used to simplify development. Equivalent to a namespace.

In the case of a single class node:

<>    <name= "com.nucsoft.hibernate.News" Table = "news" Schema = "hibernate" >    </ class > </ hibernate-mapping >

In case of multiple class nodes:

<hibernate-mapping package= "com.nucsoft.hibernate">    <classname= "News"Table= "news"Schema= "hibernate">    </class>    <classname= "Users"Table= "users"Schema= "hibernate">    </class></hibernate-mapping>

2.<class>

(1) Name: class name, such as Com.nucsoft.hibernate.News.

(2) table: indicates, such as News. The Class name and table name do not necessarily Match.

(3) Schema: Library Name. such as Hibernate.

(4) dynamic-insert: Dynamic Insert. The default is False. Set to True to indicate that insert statements are generated dynamically when an object is inserted, and that the INSERT statement contains only those fields that are not null-valued.

① Default

@Test  public void testdynamicinsert () {    newnullnew  java.util.Date ());    Session.save (news);}

Console printing:

Hibernate:     insert     into        hibernate.news        (title, author, date)     values        (?, ?, ?)

② Set dynamic-insert= "true"

@Test  public void testdynamicinsert () {    newnullnew  java.util.Date ());    Session.save (news);}

Console printing:

Hibernate:     insert     into        hibernate.news        (title, date)     values        ( ?, ?)

Note: fields that are set to NULL do not have a non-empty constraint.

(5) dynamic-update: Dynamic Update. The default is False. Set to true to indicate that when an object is updated, an UPDATE statement is dynamically generated, and the UPDATE statement contains only the fields that need to be updated for all Values.

① Default

@Test  public void testdynamicupdate () {    news  = session.get (news).  Class, 205);    News.setauthor ("BB");}

Console printing:

Hibernate:     Update        hibernate.news     set        title=?,        author=?,        Date=?      where        ID=?

② Set dynamic-update= "true"

@Test  public void testdynamicupdate () {    news  = session.get (news).  Class, 206);    News.setauthor ("CC");}

Console printing:

Hibernate:     Update        hibernate.news     set        author=?      where        ID

(6) Select-before-update: Sets whether a persisted object executes a query before the Update. For example, an update to a free object, before updating, the query makes the free object become persisted object,

The UPDATE statement is no longer sent if the object is consistent with the corresponding record state in the Database. however, it affects performance.

3.<id>

Description

    • Hibernate uses the OID to establish the correspondence between objects in memory and records in a data table. The OID of the object corresponds to the primary key of the data table. Hibernate assigns a value to the primary key by using the identifier Generator.
    • Hibernate recommends using a proxy primary key in a data table, that is, a field that does not have any business meaning. The surrogate primary key is usually an integral type.
    • The <id> node is used to set the object identifier,<generator> child element is used to set the identity Fuzhou Generator. Hibernate provides the identifier generator Interface: identifiergenerator, which provides built-in implementations, and we can also define our own generators by implementing this Interface.

(1) name: The property name of the persisted class.

(2) column: The list name of the corresponding data table.

(3) the mapping type of the Type:hibernate.

(4) Unsaved-value: If there is an object with the same ID and Unsaved-value value, it will be considered as a temporary object.

(4) Child node:<generator>. Sets the identity Fuzhou builder for the persisted class.

    • Class property, the fully qualified class name or abbreviation of the Generator. Abbreviations are generally used.

    • Increment: There is a concurrency problem and primary key duplication Occurs. Applies only to Tests.
    • Hilo: in Hibernate 4.2.2, the version is Obsolete. The org.hibernate.id.enhanced.SequenceStyleGenerator replaced it.

4.<property>

(1) name: Specifies the property name of the persisted class.

(2) type:hibernate Mapping Type. (Hibernate mapping type, A bridge of Java type and SQL Type)

(3) column: Specifies the field name of the mapped table, which can be defined as a child node.

(4) access: Specifies the default property access policy for Hibernate. The default is property, which is to use Getter/setter. If field is specified, the member variable is accessed through Reflection.

(5) unique: whether to add a unique Constraint.

(6) Update: Whether the value of this column can be Modified.

(7) index: specifies an index Name.

(8) scale: Specifies the number of decimal digits of the data column that the attribute is mapped to. Effective for double/float/decimal and so On.

(9) Formula: Sets an SQL expression that Hibernate will use to calculate the value of the derived Property.

Attention:

    • Derived property: not all properties of a persisted class are directly matched to the Table's fields, and the values of some properties of the persisted class must be evaluated at run Time.
    • Formula= "(sql)" parentheses are not limited.
    • The column and table names in the SQL statement should correspond to the column and table names in the database, not the persisted class name and attribute Name.

E: The Desc field of type String was added in News.

News.hbm.xml configuration:

NameFormula= "(select concat (title, ': ', author) from news n WHERE n.id = id)"/>  

Test:

@Test  public void Testformula () {    = (news) session.get (news).  Class, 1);    System.out.println (news.getdesc ());}

Console printing:

Hibernate:     Select        news0_.id as id1_0_0_,        news0_.title as title2_0_0_,        News0_.author as Author3_0 _0_,        news0_.date as date4_0_0_,        (SELECT            concat (news0_.title,            ': ',            news0_ . Author)         from            news n         WHERE            n.id =   news0_.id) as formula0_0_     from        hibernate.news news0_     where        news0_.id=?  DD:DD

You can see that the derived property is set in the same way as a subquery.

third, Mapping time, Date type

1. Basic knowledge

(1) in Java, the types that represent dates and times are: java.util.Date and java.util.Calendar. In addition, JDBC provides 3 extensions: java.sql.Date, java.sql.Time, java.sql.Timestamp.

Corresponds to the date, time, and timestamp types of standard SQL, respectively.

(2) in standard SQL, date types represent dates, time types represent times, TIMESTAMP types represent timestamps, and date and time information is Included.

(3) because Java.util.Date is the parent class of Java.sql.date,java.sql.time and java.sql.Timestamp, Java.util.Date can correspond to the standard SQL Date, time, The Timestamp type.

Based on the above, the Date type of the entity class can be set to the Java.util.Date Type.

(4) how to map java.util.Date to date,time,timestamp?

① under Eclipse, The data table is generated based on the entity and the mapping File.

Mapping can be done through the Property's type Attribute.

For example:

< propertyname= "date"type= "timestamp">    <columnname= "DATE" /></ property>< propertyname= "date"type= "data">    <columnname= "DATE" /></ property>< propertyname= "date"type= "time">    <columnname= "DATE" /></ property>

Where timestamp, date, time is neither a Java type nor a standard SQL type, but a hibernate mapping type.

② under Intellij idea, the Entity.hbm.xml and entity classes are generated according to the Table.

The resulting entity date type is a specific java.sql.date or java.sql.time or Java.sql.timestamp.

Here you need to change it to its parent class: Java.util.date.

It has been tested that the type attribute of the corresponding property is written and not written without affecting the final Result. Such as:

<name= "birthday">    <name= " Birthday "  sql-type=" timestamp "/></ property >

The inserted result is also a timestamp with a date and Time.

③ summary: under Eclipse, You must explicitly specify the Property's type attribute to make a precise mapping of the date Time. Under Intellij idea, you need to change the date and time type of the entity class to the Java.util.Date Type.

(5) Java type, Hibernate type, standard SQL type correspondence table

Iv. about Blob,clob There is no Explanation. objects that handle binary and large data types in a project are rarely stored through blobs and clob.

V. Summary

Describes how the entity classes and data tables are mapped, how the primary keys are generated, how they are mapped, and how the properties and columns are Mapped. A date-time mapping is also described.

Hibernate--entity.hbm.xml

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.