Annotation declaration of hibernate annotation

Source: Internet
Author: User

@ Entity

Annotate a POJO class into an object bean (persistent POJO class)

@ Table

Specify a specific table for the object bean ing. If the annotation is not declared, the system uses the default value (that is, the short class name of the object bean without the package name)

@ Id

Define an attribute in the Entity bean as an identifier)

@ GeneratedValue

This annotation defines the generation policy for this identifier (the default is the AUTO policy ):

AUTO-can be of the IDENTITY, SEQUENCE, or TABLE type, depending on different underlying databases.

TABLE-use the TABLE to save the id value

IDENTITY-increment naturally

SEQUENCE-SEQUENCE

@ Transient

The getter method or attribute annotated as @ Transient will not be persistent, and hibernate will ignore these fields and attributes.

@ Basic

All attributes with no annotation defined are equivalent to adding the @ Basic annotation to the annotation .. The @ Basic annotation can be used to declare the property acquisition policy (fetch strategy)

@ Temporal

In the core Java API, the time precision (temporal precision) is not defined ). Therefore, when processing time-type data, you also need to define the expected precision for storing it in the database.

In the database, data of the TIME type has three precision types: DATE, TIME, and TIMESTAMP (namely, simple DATE, TIME, or both ). You can use the @ Temporal annotation to adjust the precision.

@ Column

Map attributes in the object bean to columns in the table.

@ Column (

Name = "columnName"; (1)

Boolean unique () default false; (2)

Boolean nullable () default true; (3)

Boolean insertable () default true; (4)

Boolean updatable () default true; (5)

String columnDefinition () default ""; (6)

String table () default ""; (7)

Int length () default 255; (8)

Int precision () default 0; (9)

Int scale () default 0; (10)

(1) name (optional) column name (default value: attribute name)

(2) unique (optional) whether to set unique constraints on the column (default value: false)

(3) nullable (optional) whether to set the value of this column to null (default value: true)

(4) insertable (optional) whether the column is used as a column in the generated insert Statement (default value: true)

(5) updatable (optional) whether the column is used as a column in the generated update Statement (default value: true)

(6) columnDefinition (optional) overwrites the SQL DDL fragment for this specific column (this may cause migration between different databases)

(7) table (optional) define the corresponding table (the primary table by default)

(8) Optional length, column length (default value: 255)

(9) precision (optional) decimal precision (0 by default)

(10) scale is optional. If the column's decimal value range (decimal scale) is available, set it here (default value 0)

Environment: JDK 1.6, eclipse 3.6, maven 3.0.4, hibernate 3.3.2, junit 4.7, mysql 5.1

Pom. xml list
 
<Project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

<ModelVersion> 4.0.0 </modelVersion>

<GroupId> com. fancy </groupId>

<ArtifactId> hibernate_annotation </artifactId>

<Packaging> war </packaging>

<Version> 1.0 </version>

<Name> hibernate_annotation Maven Webapp </name>

<Url> http://maven.apache.org </url>

 

<Dependencies>

 

<! -- Hibernate framework -->

<Dependency>

<GroupId> org. hibernate </groupId>

<ArtifactId> hibernate-core </artifactId>

<Version> 3.3.2.GA </version>

</Dependency>

<! -- Hibernate Dependency Start -->

<Dependency>

<GroupId> cglib </groupId>

<ArtifactId> cglib </artifactId>

<Version> 2.2 </version>

</Dependency>

<Dependency>

<GroupId> policsist </groupId>

<ArtifactId> javassist </artifactId>

<Version> 3.9.0.GA </version>

</Dependency>

<Dependency>

<GroupId> org. hibernate </groupId>

<ArtifactId> hibernate-annotations </artifactId>

<Version> 3.4.0.GA </version>

</Dependency>

<Dependency>

<GroupId> org. slf4j </groupId>

<ArtifactId> slf4j-log4j12 </artifactId>

<Version> 1.5.8 </version>

</Dependency>

<! -- Hibernate Dependency End -->

 

<! -- Mysql driver -->

<Dependency>

<GroupId> mysql </groupId>

<ArtifactId> mysql-connector-java </artifactId>

<Version> 5.1.17 </version>

</Dependency>


<! -- Junit -->

<Dependency>

<GroupId> junit </groupId>

<ArtifactId> junit </artifactId>

<Version> 4.7 </version>

<Scope> test </scope>

</Dependency>

 

</Dependencies>

 

<Build>

<FinalName> hibernate_annotation </finalName>

</Build>

 

</Project>

 

Note: The configuration of pom. xml here uses maven to manage jar packages. If you do not use maven, You need to manually import the relevant jar packages.

Entity bean
 
Package net. yeah. fancydeepin. po;


Import java. util. Date;

Import javax. persistence. Column;

Import javax. persistence. Entity;

Import javax. persistence. GeneratedValue;

Import javax. persistence. Id;

Import javax. persistence. Table;

Import javax. persistence. Temporal;

Import javax. persistence. TemporalType;

Import javax. persistence. Transient;

Import java. io. Serializable;

/**

*-----------------------------------------

* @ Description object class

* @ Author fancy

* @ Mailbox fancydeepin@yeah.net

* @ 2012-10-12 <p>

*-----------------------------------------

*/

@ Entity

@ Table (name = "user ")

Public class User implements Serializable {


Private static final long serialVersionUID = 1L;

/**

* ID, primary key

*/

Private Integer id;

/**

* User Name

*/

Private String name;

/**

* Nickname

*/

Private String nickName;

/**

* Email address

*/

Private String email;

/**

* Registration Date and Time

*/

Private Date registerDate;

/**

* Last Logon Time

*/

Private Date recentLoginTime;

/**

* Last Logon Time

*/

Private Date lastLoginDay;

 

@ Id

@ GeneratedValue

Public Integer getId (){

Return id;

}


@ Column (length = 18, nullable = false)

Public String getName (){

Return name;

}


@ Transient

Public String getNickName (){

Return nickName;

}


@ Column (name = "mail", length = 40, nullable = false)

Public String getEmail (){

Return email;

}


@ Temporal (TemporalType. TIMESTAMP)

@ Column (nullable = false)

Public Date getRegisterDate (){

Return registerDate;

}


@ Temporal (TemporalType. TIME)

Public Date getRecentLoginTime (){

Return recentLoginTime;

}


@ Temporal (TemporalType. DATE)

Public Date getLastLoginDay (){

Return lastLoginDay;

}


Public void setId (Integer id ){

This. id = id;

}


Public void setName (String name ){

This. name = name;

}


Public void setNickName (String nickName ){

This. nickName = nickName;

}


Public void setEmail (String email ){

This. email = email;

}


Public void setRegisterDate (Date registerDate ){

This. registerDate = registerDate;

}


Public void setRecentLoginTime (Date recentLoginTime ){

This. recentLoginTime = recentLoginTime;

}


Public void setLastLoginDay (Date lastLoginDay ){

This. lastLoginDay = lastLoginDay;

}


}

 

NOTE: Annotations can be declared on attributes or getter methods. However, we do not recommend that you use these two declaration methods in combination. On the contrary, avoid them as much as possible. In addition, attributes modified by static are not persisted to the database.

Hibernate. cfg. xml list
 
<Hibernate-configuration>

<Session-factory>


<! -- Database connection settings -->

<Property name = "connection. driver_class"> com. mysql. jdbc. Driver </property>

<Property name = "connection. url"> jdbc: mysql: // localhost: 3306/temp </property>

<Property name = "connection. username"> username </property>

<Property name = "connection. password"> password </property>

<! -- SQL dialect -->

<Property name = "dialect"> org. hibernate. dialect. MySQLDialect </property>


<! -- Enable Hibernate's automatic session context management -->

<Property name = "current_session_context_class"> thread </property>

 

<! -- Echo all executed SQL to stdout -->

<Property name = "show_ SQL"> true </property>

<Property name = "format_ SQL"> true </property>


<Mapping class = "net. yeah. fancydeepin. po. User"/>

</Session-factory>


</Hibernate-configuration>
 

 

Junit Test
 
Package junit. test;

Import java. util. Date;

Import net. yeah. fancydeepin. po. User;

Import org. hibernate. Session;

Import org. hibernate. cfg. AnnotationConfiguration;

Import org. hibernate. tool. hbm2ddl. SchemaExport;

Import org. junit. BeforeClass;

Import org. junit. Test;

/**

*-----------------------------------------

* @ Describe Junit Test

* @ Author fancy

* @ Mailbox fancydeepin@yeah.net

* @ 2012-10-12 <p>

*-----------------------------------------

*/

Public class TestApp {


Private static Session session = null;

 

@ BeforeClass

Public static void beforeClass () throws Exception {

 

Session = new AnnotationConfiguration (). configure (). buildSessionFactory (). getCurrentSession ();

}


@ Test

Public void createTable (){


New SchemaExport (new AnnotationConfiguration (). configure (). create (true, true );

}


@ Test

Public void insert (){


User user = new User ();

Date date = new Date ();

User. setName ("fancy ");

User. setEmail ("fancydeepin@yeah.net ");

User. setRegisterDate (date );

User. setRecentLoginTime (date );

User. setLastLoginDay (date );

Session. beginTransaction ();

Session. save (user );

Session. getTransaction (). commit ();

}


}
 

 

Execute createTable in the Junit test class, and print the output SQL statement in the background:


Drop table if exists user


Create table user (

Id integer not null auto_increment,

Name varchar (18) not null,

Mail varchar (40) not null,

RegisterDate datetime not null,

RecentLoginTime time,

LastLoginDay date,

Primary key (id)

)

 

Table structure generated in the database:

 

Execute the insert method in the Junit test class, and print the output SQL statement in the background:

Hibernate:
Insert
Into
User
(Mail, lastLoginDay, name, recentLoginTime, registerDate)
Values
(?, ?, ?, ?, ?)


Data in the database:


 

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.