Getting Started with Hibernate (3): Property mapping & PRIMARY Key mapping

Source: Internet
Author: User
Tags generator modifier one table uuid
Attribute Mappings 1) @Column modifier Properties
Using the @Column to decorate the Pojo property, you can specify some mapping information at the same time, and the commonly used information is as follows (these @Column properties are optional):
Name Specify column names for this column
Length Specifies the maximum length of the column, default 255
Nullable Specifies whether this can be null, by default True
Unique Specifies whether the column has a unique constraint, false by default
Presicison Specifies the maximum number of significant digits supported by the column when it is listed as decimal
Scale Specifies the maximum number of digits supported by the column when it is listed as decimal
Table Specifies the name of the table to which the column belongs, and when more than one table is required to hold an entity, you specify the property
@Entity                
@Table (name= "users") public   
class users {
    @Id
    @GeneratedValue (strategy= generationtype.identity)  
    @Column (name= "user_id")   
    private int id;
    
    @Column (name= "user_name", length= ")
    private String name;
    ....
}

2) @Transient modify non-persisted properties
You can use @transient to decorate properties that do not participate in persisted mappings, and as additional information properties for that Po, the decorated properties are not mapped to the fields of the data table;
@Entity                
@Table (name= "users") public   
class users {
    @Id
    @GeneratedValue (strategy= generationtype.identity)  
    @Column (name= "user_id")   
    private int id;
  
    ....
    @Transient
    private String description; 
}
3) @Enumerated modifier enum Type properties
In some cases, the property of a persisted class is an enumeration type, that is, the property can only accept a few fixed values, in which case the @Enumerated may be used to decorate; @Enumerated There are 2 ways to store enumerations to the database, enumtype.ordinal ordinal storage, Enumtype. string strings are stored;

Define an enumeration class as follows:
@Entity                
@Table (name= "users") public   
class users {
    @Id
    @GeneratedValue (strategy= generationtype.identity)  
    @Column (name= "user_id")   
    private int id;
  
    ....
    @Enumerated (enumtype.ordinal)  //Use ordinal to store enumeration values
    @Column (name= "sex")
    private sex sex;
}
public enum sex{
    Male,female
}
@Entity                
@Table (name= "users") public   
class users {
    @Id
    @GeneratedValue (strategy= generationtype.identity)  
    @Column (name= "user_id")   
    private int id;
  
    ....
    @Enumerated (enumtype.ordinal)  //Use ordinal to store enumeration values
    @Column (name= "sex")
    private sex sex;
}
4) @Lob, @Basic properties that modify large data typesWhen you save a picture or a large piece of text, the database is usually saved using the Blob,clob type, the corresponding JDBC type is Java.sql.Blob, Java.sql.Clob, you can use @lob to decorate the big data type, when the persisted class's properties are byte[], Byte[], java.io.Serializable type, @Lob decorated property is mapped to the underlying Blob column, and when the properties of the persisted class are char[], character[], Java.io.String type, @Lob The modifier attribute is mapped to the underlying CLOB column;
User.java
@Entity                
@Table (name= "users") public   
class users {
    @Id
    @GeneratedValue (strategy= generationtype.identity)  
    @Column (name= "user_id")   
    private int id;
    ....
    @Lob
    @Column (name= "headshot")
    private byte[] headshot;
The process of saving a picture as in the following example
public class Usermanager {public static void main (string[] args) {Standardserviceregistry registry = new Stan
        Dardserviceregistrybuilder (). Configure ("Hibernate.cfg.xml"). Build ();
            try{sessionfactory sessionfactory = new Metadatasources (registry). Buildmetadata (). Buildsessionfactory ();
            Session session = Sessionfactory.opensession ();

            
            Transaction tran = Session.begintransaction ();
            Users user = new users ();
            
            User.setname ("Al-assad");
            Reads an image file from the local, saved to the entity file File = new file ("Headshot.png");
            byte[] content = new byte[(int) file.length ()];
            New FileInputStream (file). read (content);
            
            User.setheadshot (content);
            Session.save (user);
            
            Tran.commit ();
            Session.close ();

        Sessionfactory.close ();
            }catch (Exception ex) {Standardserviceregistrybuilder.destroy (registry);
 }
    }
}
5) @Temporal Properties of the modified date type
@Temporal A property that modifies a date type to map the Java.util.date,java.util.calendar class property in Java to a date, time, timestamp type data column in the database, where the value The Temporal.date property contains 3 values: A (date date type), Temporal.time (Time Time type), Temporal.timestamp (timestamp type);
@Entity                
@Table (name= "users") public   

class users {
   
    @Id                
    @GeneratedValue (strategy= generationtype.identity)  
    @Column (name= "user_id")   
    private int id;

    ...

    @Column (name= "create_date")
    @Temporal (temporaltype.date)
    private date createdate;

    ...
}

PRIMARY Key MappingsIn modern database modeling theory, it is recommended that you do not use physical primary keys that have practical significance, and use logical primary keys that have no practical meaning. The complexity of database maintenance has been reduced, Hibernate provides a large number of logical primary key constructors, and if the identity attributes of an entity class are basic types, basic types of wrapper classes, string,date, etc., you can simply use @Id to decorate;
If you want Hibernate to automatically generate primary key values, you will also need to @GeneratedValueTo decorate the identity property, which has the following properties (these are optional):
Strategy Specifies a primary key generation policy that contains the following 4 properties:
Generationtype.auto: Default value, automatically select the primary key generation strategy;
Generationtype.identity: For databases such as Mysql,sql Server, select the Auto-Grow primary key generation strategy;
Generationtype.sequence: For databases such as Oracle, select the SEQUENCE-based primary key generation strategy to be used together with @SequenceGenerator;
Generationtype.table: Use auxiliary table to generate primary key, use with @tablegenerator;
Generator When generating a policy using the Generationtype.sequence,generationtype.table primary key, the attribute needs to be applied @sequencegenerator, @TableGenerator generator;
Examples are as follows:
@Entity                
@Table (name= "users") public   

class users {
   
    @Id                
    @GeneratedValue (strategy= generationtype.identity)  
    @Column (name= "user_id")   
    private int id;

    ....
}
In addition to the Auto,indetity,sequence,table 4 JPA Standard primary key generation strategies, Hibernate also includes other primary key generation policies that use @GenericGeneratorThe callout contains the name, strategy 2 mandatory attributes, and the optional values commonly used by the Strategy property are as follows:
Increment Generates a unique property for the Short,int,long type and can only be used when no other process is inserting data into the same table, not for the cluster
Indentity Used in data tables supported by the Indentity primary key to return an identity value of type Short,int or long
Sequence Used in data tables supported by the sequence primary key to return an identity value of type Short,int or long
Hilo Use a low/high algorithm to efficiently generate an identity value of short,int or long, which is unique only in a particular database
Seqhilo Use a low/high algorithm to efficiently generate short,int or long identification values, given a database sequence name, and a historical primary key saved in sequence
Uuid Uses a 128-bit UUID algorithm to generate an identifier for the string type, which is unique in a network, and the UUID is encoded as a 32-bit hexadecimal string
Guid GUID string generated by using database in SQL server,mysql
Native Based on the ability of the underlying database to select the Identity,sequence,hilo
Examples of use are:
@Entity                
@Table (name= "users") public   

class users {
   
    @Id
    @GenericGenerator (name= "Fk_hilo", strategy= " Hilo ")
    @GeneratedValue (generator=" Fk_hilo ")  
    @Column (name=" user_id ")   
    private int id;

    ....
}


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.