隨筆-126  評論-247  文章-5  trackbacks-0

          @Entity

               將一個(gè) POJO 類注解成一個(gè)實(shí)體 bean ( 持久化 POJO 類 )

          @Table

              為實(shí)體 bean 映射指定具體的表,如果該注解沒有被聲明,系統(tǒng)將使用默認(rèn)值 ( 即實(shí)體 bean 不帶包名的短類名 )

          @Id

              將實(shí)體bean中的某個(gè)屬性定義為標(biāo)識(shí)符 ( identifier )

          @GeneratedValue

              該注解可以定義該標(biāo)識(shí)符的生成策略 ( 默認(rèn)是 AUTO 策略 ) :

              AUTO — 可以是 IDENTITY,或 SEQUENCE TABLE 類型,這取決于不同的底層數(shù)據(jù)庫。

              TABLE — 使用表保存id值

              IDENTITY — 自然遞增

              SEQUENCE — 序列

          @Transient

               被注解成 @Transient 的 getter 方法或?qū)傩裕瑢⒉粫?huì)被持久化,hibernate 會(huì)忽略這些字段和屬性。

          @Basic

              所有沒有定義注解的屬性,等價(jià)于在其上面添加了 @Basic 注解.。通過 @Basic注解可以聲明屬性的獲取策略 ( fetch strategy )

          @Temporal

              在核心的 Java API 中并沒有定義時(shí)間精度 ( temporal precision )。因此處理時(shí)間類型數(shù)據(jù)時(shí),你還需要定義將其存儲(chǔ)在數(shù)據(jù)庫中所預(yù)期的精度。

              在數(shù)據(jù)庫中,表示時(shí)間類型的數(shù)據(jù)有 DATE,TIME,和 TIMESTAMP 三種精度 ( 即單純的日期,時(shí)間,或者兩者兼?zhèn)?)。 可使用 @Temporal 注解來調(diào)整精度。

          @Column 

              將實(shí)體 bean 中的屬性映射到表中的列。

              @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 可選,列名(默認(rèn)值是屬性名)

          (2)     unique 可選是否在該列上設(shè)置唯一約束(默認(rèn)值false)

          (3)     nullable 可選是否設(shè)置該列的值可以為空(默認(rèn)值true)

          (4)     insertable 可選該列是否作為生成的insert語句中的一個(gè)列(默認(rèn)值true)

          (5)     updatable 可選該列是否作為生成的update語句中的一個(gè)列(默認(rèn)值true)

          (6)     columnDefinition 可選為這個(gè)特定列覆蓋SQL DDL片段 (這可能導(dǎo)致無法在不同數(shù)據(jù)庫間移植)

          (7)     table 可選定義對應(yīng)的表(默認(rèn)為主表)

          (8)     length 可選列長度(默認(rèn)值255)

          (9)     precision 可選列十進(jìn)制精度(decimal precision)(默認(rèn)值0)

          (10)  scale 可選如果列十進(jìn)制數(shù)值范圍(decimal scale)可用,在此設(shè)置(默認(rèn)值0)


          環(huán)境 : JDK 1.6,eclipse 3.6,maven 3.0.4,hibernate 3.3.2,junit 4.7,mysql 5.1

           pom.xml 清單   
          <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>javassist</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>



          注 : 此處配置 pom.xml 是使用 maven 來管理 jar 包,如果你沒有使用 maven,則需手動(dòng)導(dǎo)入相關(guān) jar 包。

           實(shí)體 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;

          /**

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

           * @描述 實(shí)體類

           * @作者 fancy

           * @郵箱 fancydeepin@yeah.net

           * @日期 2012-10-12 <p>

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

           */

          @Entity

          @Table(name = "user")

          public class User implements Serializable {

                   private static final long serialVersionUID = 1L;

             /**

              * ID,主鍵

              */

             private Integer id;

             /**

              * 用戶名

              */

             private String name;

             /**

              * 昵稱

              */

             private String nickName;

             /**

              * 郵箱地址

              */

             private String email;

             /**

              * 注冊日期時(shí)間

              */

             private Date   registerDate;

             /**

              * 最近登錄時(shí)間

              */

             private Date   recentLoginTime;

             /**

              * 上一次登錄時(shí)間

              */

             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;

             }

          }



          注 : 注解可以是在屬性或 getter 方法上進(jìn)行聲明,但不建議混合使用這兩種聲明方式,相反,應(yīng)該盡量避免。另外,由 static 修飾的屬性不會(huì)被持久化到數(shù)據(jù)庫。

           hibernate.cfg.xml 清單   
          <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;

          /**

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

           * @描述 Junit Test

           * @作者 fancy

           * @郵箱 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();

             }

          }
           



          在 Junit 測試類中執(zhí)行建表方法 createTable,后臺(tái)打印輸出的 SQL 語句 :

          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)

          )



          數(shù)據(jù)庫中生成的表結(jié)構(gòu) :



          在 Junit 測試類中執(zhí)行插入數(shù)據(jù)的方法 insert,后臺(tái)打印輸出的 SQL 語句 :

          Hibernate:
              insert
              into
                  user
                  (mail, lastLoginDay, name, recentLoginTime, registerDate)
              values
                  (?, ?, ?, ?, ?)


          數(shù)據(jù)庫中的數(shù)據(jù) :




          源碼下載 :   hibernate annotation 之 注解聲明.rar

          [ 解壓密碼 : http://www.aygfsteel.com/fancydeepin ]


            
          posted on 2012-10-12 11:38 fancydeepin 閱讀(10998) 評論(7)  編輯  收藏

          評論:
          # re: hibernate annotation 之 注解聲明 2012-10-14 13:57 | fancydeepin
          回復(fù) @撲克牌分析儀

          你想說的意思我沒看懂,抱歉~  回復(fù)  更多評論
            
          # re: hibernate annotation 之 注解聲明[未登錄] 2013-09-16 11:22 | 你好
          寫的很全,正好有問題  回復(fù)  更多評論
            
          # re: hibernate annotation 之 注解聲明 2014-07-16 14:15 | 高尚
          123123123123123  回復(fù)  更多評論
            
          # re: hibernate annotation 之 注解聲明 2014-07-16 14:15 | 高尚
          123123  回復(fù)  更多評論
            
          # re: hibernate annotation 之 注解聲明 2014-07-16 14:16 | 高尚
          123456  回復(fù)  更多評論
            
          # re: hibernate annotation 之 注解聲明 2014-07-16 14:16 | 高尚
          1231231231231231231231  回復(fù)  更多評論
            
          # re: hibernate annotation 之 注解聲明[未登錄] 2014-08-01 15:07 | 清風(fēng)
          boolean insertable() default true; (4)

          如果我寫成了false 那是不是以后所有的insert 這個(gè)值 就算我給他賦值了 他也沒辦法用給他賦的值,只能用見表時(shí)候的默認(rèn)值?  回復(fù)  更多評論
            

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 咸宁市| 宜兴市| 英超| 手机| 股票| 钦州市| 淅川县| 波密县| 康乐县| 哈尔滨市| 武川县| 平凉市| 星座| 泽库县| 邯郸市| 晋江市| 原平市| 灵武市| 开远市| 思茅市| 铜陵市| 余干县| 特克斯县| 宾阳县| 尤溪县| 留坝县| 平顶山市| 山东| 九江县| 亚东县| 行唐县| 曲水县| 木兰县| 邵东县| 民和| 大石桥市| 巢湖市| 蕲春县| 宁乡县| 荆州市| 桂东县|