The JPA annotations Persistence class is convenient and requires a jar package: Ejb3-persistence.jar. I use the following three classes to illustrate usage.
SH Original reprint Please specify: http://67566894.iteye.com/blog/659829
Java code
- @SuppressWarnings ("Serial")
- @Entity
- @Table (name= "t_x")
- public class X implements Serializable
- {
- @Id
- @GeneratedValue (strategy = Generationtype.auto)
- private int id;
- @Column (length= 32)
- private String name;
- @Transient//Indicates that this data does not establish a property in the database table
- Private String temp;
- @Temporal (Temporaltype.timestamp)//This is the type of time and seconds
- private date date;
- @OneToOne (cascade = cascadetype.all, Mappedby = "x")
- Private a A;
- }
- @SuppressWarnings ("Serial")
- @Entity
- @Table (name= "T_a")
- public class A implements Serializable
- {
- @Id
- @GeneratedValue (strategy = Generationtype.auto)
- private int id;
- @OneToMany (cascade = cascadetype.all, Mappedby = "a", Fetch = Fetchtype.eager)
- Private list<b> B = new arraylist<b> ();
- @OneToOne ()
- @JoinColumn (name = "x_id")//Add this sentence and the two sides will jointly maintain the relationship.
- private x x;
- }
- @SuppressWarnings ("Serial")
- @Entity
- public class B implements serializable{
- @Id
- @GeneratedValue (strategy = Generationtype.auto)
- protected int id;
- @ManyToOne ()
- @JoinColumn (name = "A_ID")
- protected A;
- }
Note that: Fetch = Fetchtype.eager This sentence in a class can only appear once, appear two times will error "cannot simultaneously fetch multiple bags", to change the other to fetch = Fetchtype.lazy delay loading is possible. It is also possible to resolve this error by changing the list set to set.
Other Highlights:
1, @Table (name= "t_x") This sentence can not write, do not write on the name of the class is a table
2, if you want to let the properties of two classes to generate a data table, in one class to add another class can: @Embedded
Private C C;
3. If you want a class to inherit all the properties of another class, write this in the parent class:
@SuppressWarnings ("Serial")
@Entity
@MappedSuperclass//Add this line
and change the private property of the parent class to protected.
4, the proposed in a one-to-many association in the "a" side with delay loading "many" side can be in the hql explicit "urgent left outer connection," and so to do hibernate can not access the database, you can also use "@BatchSize (size = 5)" To reduce the number of accesses to the database
1. @Id declaring properties as primary keys
2. @GeneratedValue indicates that the primary key is an auto-generated policy, which is typically used with @Id
3. @Entity any Hibernte mapping object to have a second comment
4. @Table (name = "TableName") class declares which table this object is mapped to
5. @Column (name = "Name", nullable=false,length=32) Declares database fields and class property correspondence
6. @Lob declaration field Clob or Blob type
7. @OneToMany (mappedby= "Order", Cascade = cascadetype.all, fetch = Fetchtype.lazy)
@OrderBy (value = "id ASC")
A one-to-many declaration, similar to the ORM product declaration, is clear at a glance.
@ManyToOne (Cascade=cascadetype.refresh,optional=false)
@JoinColumn (name = "order_id")
Declare as bidirectional association
8. @Temporal (value=temporaltype.date) do a date type conversion.
9. @OneToOne (optional= true,cascade = cascadetype.all, Mappedby = "Person")
One-to-one correlation statement
@OneToOne (optional = false, Cascade = Cascadetype.refresh)
@JoinColumn (name = "person_id", referencedcolumnname = "PersonID", unique = True)
Declare as bidirectional association
@ManyToMany (mappedby= "Students")
Many-to-many association claims.
@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")})
Many-to-many associations generally have an association table, which is declared!
A. @Transiten indicates that this property does not have a mapping relationship to the table and is a temporary property
The @Cache (usage= cacheconcurrencystrategy.read_write) indicates that this object applies a cache
JPA Specification
@Entity: Declaring a class as an entity bean with @Entity annotations
@Table: by @Table annotations You can specify a table for the entity bean mappings, the Name property represents the names of the tables for the entity, and if no @Table is defined, the system automatically uses the default: the class name of the entity (without the package name)
@Id: The primary key for marking properties
@Column: Represents a field in the table that the persisted property is mapped to, and if the property name is the same as the field name in the table, you can omit the @Column annotation, another two ways to mark it, one before the attribute and the other before the Getter method, for example:
@Column (name = "Employee_Name")
Private String employee_name; Or
@Column (name = "Employee_Name")
Public String Getemployee_name () {
return employee_name;
Both of these are positive solutions and are chosen according to your preferences. Elephants prefer the second, and they like to set the property name to be the same as the field name, which saves @column annotations and makes the code more concise.
@Temporal (temporaltype.date): If the attribute is a time type, because the data table has a more restrictive division of the time type, you must specify a time type, as shown in ④. 3 types of time are defined in the Javax.persistence.TemporalType enumeration:
Define the time precision mapped to the database by @Temporal:
@Temporal (temporaltype.date) Date
@Temporal (Temporaltype.time) time
@Temporal (Temporaltype.timestamp) both
@Temporal just a map as
@Transient
@Target ({METHOD, FIELD}) @Retention (RUNTIME)
Public @interface Transient {}
Indicates that a property or method cannot be persisted
@TableGenerator: The table generator, which saves the values of the current primary key in a single database table, and the value of the primary key is obtained each time from a specified table, the way in which the primary key is generated is very common. This method of generating a primary key can be applied to any database without worrying about the incompatibility of different databases. Elephants recommend this way to manage the primary key, it is convenient to centrally manage the primary key of the table, and replacing the database does not cause a big problem. Each attribute has the following meanings:
Name: Represents the names of the primary key generation policies for this table, which can be customized and referenced in the "generator" value set in @generatedvalue
Table: Represents the name of the tables that the table generation policy persists, saying that the simple point is a table that manages the other table's primary key, in this case the table named Generator_table
Pkcolumnname: The name of the column in the table builder that holds the primary key name for the other table, which corresponds to the field in the table.
Pkcolumnvalue: The Entity table corresponds to the primary key name in the generator table, this key name can be customized
Valuecolumnname: The column name in the table builder, the next value of the Entity table primary key, assuming that the employee_id maximum is 2 in the Employee table, then the key name value for the primary key of the entity table in the generator table is 3
Allocationsize: Represents the size of each primary key value increment, for example, set to 1, which automatically adds 1 after each new record is created, and defaults to 50
@Target ({METHOD, FIELD}) @Retention (RUNTIME)
Public @interface Onetomany {
String targetentity () default "";
Cascadetype[] Cascade () default {};
Fetchtype fetch () default LAZY;
String mappedby () default "";
}
String targetentity (Optional) The fully qualified class name of
The entity class is the target of the association.
Optional If the Collection property
is defined using Java generics. Must be
Specified otherwise.
The parameter type of the
Collection when defined
Using generics (generics generics), if you use generics, you can omit the specified targetentity
Cascadetype[] Cascade (Optional) the operations that should be cascaded
To the target of the association
No Operations is cascaded
Fetchtype Fetch (Optional) Whether the association should be
Lazy loaded or eagerly fetched.
Fetchtype.lazy Default to Lazy loading
String Mappedby (Optional) The field that owns the relationship
Refers to the name of the attribute associated with a multiple party
MAPPEDBY specifies that one end of the relationship does not need to be maintained??
@Target ({METHOD, FIELD}) @Retention (RUNTIME)
Public @interface Manytoone {
String targetentity () default "";
Cascadetype[] Cascade () default {};
Fetchtype fetch () default EAGER;
Boolean optional () default true;
}
Targetentity (Optional) The fully qualified class name of the entity class that is the target of the associationthe type O f The property that stores the association
Refers to the class of the entity type of a party, and the default is the type of the attribute. In fact, some can be omitted
Cascadetype[] Cascade (Optional) the operations that should be cascaded
To the target of the association No operations is cascaded
Fetchtype Fetch (Optional) Whether the association should be
Lazy loaded or eagerly fetched. Fetchtype.eager default is active load
Boolean optional (optional) Whether the association is optional.
If set to False then a non-null relationship must always exist.
True
@Target ({METHOD, FIELD}) @Retention (RUNTIME)
Public @interface Onetoone {
String targetentity () default "";
Cascadetype[] Cascade () default {};
Fetchtype fetch () default EAGER;
Boolean optional () default true;
String mappedby () default "";
Boolean USEPKASFK () default false;
}
The Joincolumn annotation is used to specify a mapped column for joining an entity association or a
Secondary table.
@Target ({TYPE, METHOD, FIELD}) @Retention (RUNTIME)
Public @interface Joincolumn {
String name () default "";
String referencedcolumnname () default "";
Boolean PrimaryKey () default false;
Boolean unique () default false;
Boolean nullable () default true;
Boolean insertable () default true;
Boolean updatable () default true;
String columndefinition () default "";
String secondarytable () default "";
}
@Target ({METHOD, FIELD}) @Retention (RUNTIME)
Public @interface Manytomany {
String targetentity () default "";
Cascadetype[] Cascade () default {};
Fetchtype fetch () default LAZY;
String mappedby () default "";
}
Annotation configuration for Ejb3persistence.jar javax.persistence