Hiberate common annotations

 1. Declare the entity

        @Entity maps entity classes

            Annotate the entity. Any Hibernate mapping object must have this annotation

                @Entity(name="tableName")

                            name: optional, corresponding to a table in the database. If the table name is the same as the entity class name, it can be omitted

                Note: When using @Entity, you must specify the primary key property of the entity class


        @Table

           Declares that this object maps to the database table, through which you can specify the name of the table (talbe), catalog (Catalog) and schema for the entity. This annotation is not required, if not the system uses the default value (the short class name of the entity).

            @Table(name="",catalog="",schema="")
                Used in conjunction with @Entity, it can only be marked at the class definition of the entity, indicating the information of the database table corresponding to the entity.
                        name: optional, the name of the mapping table, the default table name is the same as the entity name, and the table name needs to be specified only in the case of inconsistency.
                        catalog Optional, indicating the Catalog name, defaults to Catalog("")
                        schema - Optional, indicating the Schema name, defaults to Schema("").

             Various database systems support and implement Catalog and Schema in various ways


         @Version

             This annotation can be used to add optimistic locking support in entity beans.

 2. Declare the primary key

        @Id

           Declare this property as the primary key. The property value can be created by should itself, but Hibernate recommends that it be generated by Hibernate 


        @GeneratedValue           

@GeneratedValue(strategy=GenerationType,generator=""): optional, used to define the primary key generation strategy

Strategy represents the primary key generation strategy, the values ​​are:
GenerationType.AUTO: Automatically selected according to the underlying database (default)
GenerationType.INDENTITY: Generated according to the Identity field of the database
GenerationType.SEQUENCE: Use Sequence to determine the value of the primary key
GenerationType.TABLE: Use the specified table to determine the value of the primary key, combined with @TableGenerator

3. Declare common properties

        @Column

           Declare the mapping relationship between this property and the database field.

1   @Column(nam=”category_name” length=20)
2    Public void getCategoryName(){
3      Return this.categoryName;
4  } 

        Notice:

          1. When POJO has attributes that do not need to be mapped, it must be modified with @Transitent. This annotation indicates that this attribute has no mapping relationship with the table, but is only a temporary attribute.

          2. The @Lob annotation indicates that the property is persisted as Blob or Clob type, depending on the type of the property.

        常用属性:
name:可选,表示数据库表中该字段的名称,默认情形属性名称一致
nullable: 可选,表示该字段是否允许为null,默认为true
unique: 可选,表示该字段是否为唯一标识,默认为false
length: 可选,表示该字段的大小,仅对String类型的字段有效,默认值225,主键不能使用默认值

insertable: 可选,表示在ORM框架执行插入操作时,该字段是否应出现INSERTRT语句中,默认为true updateable: 可选,表示在ORM框架执行更新操作时,该字段是否应该出现在UPDATE语句中,默认为true。对于已经创建就不可以更改的字段,该属性非常有用


      @Version

@Version注解来发现数据库记录的并发操作。当JPA运行时检测到一个并发操作也在试图更改同一条记录。它会抛出一个尝试提交的事务异常。

四、声明关联关系

        一对多关联关系

        @OneToMany(mappedBy=” person”,cascade=CascadeType.ALL,fetch=FetchType.LAZY)

         一对多声明

        @ManyToOne(cascade=CascadeType.REFRESH,)

        @JoinColumn

         多对一声明 ,声明为双向关联


        一对一关联关系

        @OneToOne(optional= true,cascade =CascadeType.ALL, mappedBy = “person”)
        一对一关联声明
        @OneToOne(optional = false, cascade = CascadeType.REFRESH)
        @JoinColumn(name = “Person_ID”, referencedColumnName = “personid”,unique = true)

        声明为双向关联


        多对多关联关系

        @ManyToMany(mappedBy= “students”)
        多对多关联声明。
        @ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
        @JoinTable(name = “Teacher_Student”,
        joinColumns = {@JoinColumn(name = “Teacher_ID”, referencedColumnName =“teacherid”)},
        inverseJoinColumns = {@JoinColumn(name = “Student_ID”, referencedColumnName =“studentid”)})

 实例:

        有如下两个实体,商品:Goods,分类Category。两者是多对一的关联关系。

        使用Hibernate Annotation注解如下

复制代码
 1 Goods.java
 2 
 3 @Entity
 4 @Table(name = "goods", catalog = "test")
 5 public class Goods implements java.io.Serializable {
 6 
 7     private static final long serialVersionUID = 1L;
 8     private String goodsId;
 9     private Category category;
10     private String goodsName;
11 
12     public Goods() {
13     }
14 
15     /*
16      * 主键
17      * 生成策略为自动增长
18      * 唯一、长度为20
19      */
20     @Id
21     @GeneratedValue
22     @Column(name = "goods_id", unique = true, nullable = false, length = 20)
23     public String getGoodsId() {
24         return this.goodsId;
25     }
26 
27     public void setGoodsId(String goodsId) {
28         this.goodsId = goodsId;
29     }
30 
31     /*
32      * 多对一关联关系
33      * 延迟加载:fetch = FetchType.LAZY
34      * 引用外键:category_id
35      * 
36      */
37     @ManyToOne(fetch = FetchType.LAZY,cascade=CascadeType.ALL)
38     @JoinColumn(name = "category_id")
39     public Category getCategory() {
40         return this.category;
41     }
42 
43     public void setCategory(Category category) {
44         this.category = category;
45     }
46 
47     @Column(name = "goods_name", nullable = false, length = 50)
48     public String getGoodsName() {
49         return this.goodsName;
50     }
51 
52     public void setGoodsName(String goodsName) {
53         this.goodsName = goodsName;
54     }
55 
56 }
复制代码

Category.java

复制代码
 1 @Entity
 2 @Table(name = "category", catalog = "test")
 3 public class Category implements java.io.Serializable {
 4 
 5     private static final long serialVersionUID = -1877960009126534682L;
 6 
 7     private String categoryId;
 8     private String categoryName;
 9     private Set<Goods> goodses = new HashSet<Goods>(0);
10 
11     public Category() {
12     }
13 
14     /*
15      * 主键
16      * 生成策略为自动增长
17      * 唯一、长度为20
18      */
19     @Id
20     @GeneratedValue
21     @Column(name = "category_id", unique = true, length = 10)
22     public String getCategoryId() {
23         return this.categoryId;
24     }
25 
26     public void setCategoryId(String categoryId) {
27         this.categoryId = categoryId;
28     }
29 
30     @Column(name = "category_name", length = 20)
31     public String getCategoryName() {
32         return this.categoryName;
33     }
34 
35     public void setCategoryName(String categoryName) {
36         this.categoryName = categoryName;
37     }
38 
39     /*
40      * 一对多关联关系
41      * 级联关系:cascade=CascadeType.ALL
42      * 延迟加载:fetch = FetchType.LAZY
43      * 映射:mappedBy = "category"
44      */
45     @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "category")
46     public Set<Goods> getGoodses() {
47         return this.goodses;
48     }
49 
50     public void setGoodses(Set<Goods> goodses) {
51         this.goodses = goodses;
52     }
53 
54 }
复制代码 

参考资料:http://www.cnblogs.com/chenssy/p/3149210.html

@Repository

spring 自 2.0 版本开始,陆续引入了一些注解用于简化 Spring 的开发。@Repository注解便属于最先引入的一批,它用于将数据访问层 (DAO 层 ) 的类标识为 Spring Bean。具体只需将该注解标注在 DAO类上即可。同时,为了让 Spring 能够扫描类路径中的类并识别出 @Repository 注解,需要在 XML 配置文件中启用Bean 的自动扫描功能,这可以通过<context:component-scan/>实现。如下所示:

复制代码
 1 // 首先使用 @Repository 将 DAO 类声明为 Bean 
 2  package bookstore.dao; 
 3  @Repository 
 4  public class UserDaoImpl implements UserDao{ …… } 
 5 
 6  // 其次,在 XML 配置文件中启动 Spring 的自动扫描功能
 7  <beans … > 
 8     ……
 9  <context:component-scan base-package=”bookstore.dao” /> 
10 ……
11  </beans> 
复制代码

如此,我们就不再需要在 XML 中显式使用 <bean/> 进行Bean 的配置。Spring 在容器初始化时将自动扫描 base-package 指定的包及其子包下的所有 class文件,所有标注了 @Repository 的类都将被注册为 Spring Bean。

为什么 @Repository 只能标注在 DAO 类上呢?这是因为该注解的作用不只是将类识别为Bean,同时它还能将所标注的类中抛出的数据访问异常封装为 Spring 的数据访问异常类型。 Spring本身提供了一个丰富的并且是与具体的数据访问技术无关的数据访问异常结构,用于封装不同的持久层框架抛出的异常,使得异常独立于底层的框架。

@Service、@Controller 和 @Component 将类标识为Bean

Spring 2.5 在 @Repository的基础上增加了功能类似的额外三个注解:@Component、@Service、@Constroller,它们分别用于软件系统的不同层次:

  • @Component 是一个泛化的概念,仅仅表示一个组件 (Bean) ,可以作用在任何层次。
  • @Service 通常作用在业务层,但是目前该功能与 @Component 相同。
  • @Constroller 通常作用在控制层,但是目前该功能与 @Component 相同。

通过在类上使用 @Repository、@Component、@Service 和 @Constroller 注解,Spring会自动创建相应的 BeanDefinition 对象,并注册到 ApplicationContext 中。这些类就成了 Spring受管组件。这三个注解除了作用于不同软件层次的类,其使用方式与 @Repository 是完全相同的。

另外,除了上面的四个注解外,用户可以创建自定义的注解,然后在注解上标注 @Component,那么,该自定义注解便具有了与所@Component 相同的功能。不过这个功能并不常用。

当一个 Bean 被自动检测到时,会根据那个扫描器的 BeanNameGenerator 策略生成它的 bean名称。默认情况下,对于包含 name 属性的 @Component、@Repository、 @Service 和@Controller,会把 name 取值作为 Bean 的名字。如果这个注解不包含 name值或是其他被自定义过滤器发现的组件,默认 Bean 名称会是小写开头的非限定类名。如果你不想使用默认 bean命名策略,可以提供一个自定义的命名策略。首先实现 BeanNameGenerator接口,确认包含了一个默认的无参数构造方法。然后在配置扫描器时提供一个全限定类名,如下所示:

 <beans ...>  <context:component-scan base-package="a.b" name-generator="a.SimpleNameGenerator"/> </beans>  

与通过 XML 配置的 Spring Bean 一样,通过上述注解标识的Bean,其默认作用域是"singleton",为了配合这四个注解,在标注 Bean 的同时能够指定 Bean 的作用域,Spring2.5 引入了 @Scope 注解。使用该注解时只需提供作用域的名称就行了,如下所示:

  @Scope("prototype") @Repository public class Demo { … }  

如果你想提供一个自定义的作用域解析策略而不使用基于注解的方法,只需实现 ScopeMetadataResolver接口,确认包含一个默认的没有参数的构造方法。然后在配置扫描器时提供全限定类名:

  <context:component-scan base-package="a.b" scope-resolver="footmark.SimpleScopeResolver" /> 
 
 
 
 
转自:https://www.cnblogs.com/hoojjack/p/6568920.html

            https://www.imooc.com/article/17686

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325683815&siteId=291194637