注解映射必须满足两大条件:Hibernate3.2以上版本和JSEE 5。
@Entity 类注释,所有要持久化的类都要有
Java代码
@Entity
public class Org implements java.io.Serializable {
}
@Entitypublic class Org implements java.io.Serializable {}
@Id 主键
Java代码
@Id
@GeneratedValue
private String orgId;
private String orgName;
@Id @GeneratedValue private String orgId; private String orgName;
@Column(name="...") 该属性对应表中的字段是什么,没有name表示一样
@Table 对象与表映射
@UniqueConstraint 唯一约束
@Version 方法和字段级,乐观锁用法,返回数字和timestamp,数字为首选
@Transient 暂态属性,表示不需要处理
@Basic 最基本的注释。有两个属性:fetch是否延迟加载,optional是否允许null
@Enumerated 枚举类型
@Temporal 日期转换。默认转换Timestamp
@Lob 通常与@Basic同时使用,提高访问速度。
@Embeddable 类级,表可嵌入的
@Embedded 方法字段级,表被嵌入的对象和@Embeddable一起使用
@AttributeOverrides 属性重写
@AttributeOverride 属性重写的内容和@AttributeOverrides一起嵌套使用
@SecondaryTables 多个表格映射
@SecondaryTable 定义辅助表格映射和@SecondaryTables一起嵌套使用
@GeneratedValue 标识符生成策略,默认Auto
表与表关系映射
@OneToOne:一对一映射。它包含五个属性:
targetEntity:关联的目标类
Cascade:持久化时的级联操作,默认没有
fetch:获取对象的方式,默认EAGER
Optional:目标对象是否允许为null,默认允许
mappedBy:定义双向关联中的从属类。
单向:
@JoinColumn:定义外键(主表会多一字段,做外键)
@OneToMany:一对多映射;@ManyToOne:多对一映射
单向一对多:
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="book_oid")/**book:表;oid:book表的主键;无name会按此规则自动生成*/
单向多对一:
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="author_oid")
关联表格一对多:
@OneToMany(cascade=CascadeType.ALL)
@JoinTable(joinColumn={@JoinColumn(name="BOOK_OBJECT_OID")},inverseJoinColumns={@JoinColumn(name="AUTHER_OBJECT_OID")})
双向一对多或多对一:
不需要多一张表,只是使用mappedBy:使用在One一方,值为One方类名表示Many的从属类。
Java代码
@Entity
public class Org implements java.io.Serializable {
// Fields
@Id
@GeneratedValue
private String orgId;
private String orgName;
@OneToMany(mappedBy = "org")
private List<Department> departments;
// Constructors
...
// Property accessors
...
}
@Entitypublic class Org implements java.io.Serializable { // Fields @Id @GeneratedValue private String orgId; private String orgName; @OneToMany(mappedBy = "org") private List<Department> departments; // Constructors... // Property accessors...}
Java代码
@Entity
public class Department implements java.io.Serializable {
// Fields
@Id
@GeneratedValue
private String id;
private String name;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="org_orgId")
private Org org;
@OneToMany(mappedBy = "department")
private List<Employee> employees;
// Constructors
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public Org getOrg() {
return org;
}
public void setOrg(Org org) {
this.org = org;
}
/** default constructor */
.
.
.
}
@Entitypublic class Department implements java.io.Serializable { // Fields @Id @GeneratedValue private String id; private String name; @ManyToOne(fetch=FetchType.EAGER) @JoinColumn(name="org_orgId") private Org org; @OneToMany(mappedBy = "department") private List<Employee> employees; // Constructors public List<Employee> getEmployees() { return employees; } public void setEmployees(List<Employee> employees) { this.employees = employees; } public Org getOrg() { return org; } public void setOrg(Org org) { this.org = org; } /** default constructor */ . . . }
Java代码
@Entity
public class Employee implements java.io.Serializable {
// Fields
@Id
@GeneratedValue
private String employeeId;
private String employeeName;
private String passWord;
private Integer age;
private Integer sex;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="department_id")
private Department department;
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
/** default constructor */
...
// Property accessors
...
}
@Entitypublic class Employee implements java.io.Serializable { // Fields @Id @GeneratedValue private String employeeId; private String employeeName; private String passWord; private Integer age; private Integer sex; @ManyToOne(fetch=FetchType.EAGER) @JoinColumn(name="department_id") private Department department; public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } /** default constructor */ ... // Property accessors ...}
双向多对多:@ManyToMany.单向多对多这里不在赘述(没有太多实际意义)
这个比较简单,看下代码就明白了:
Java代码
@Entity
public class Book implements java.io.Serializable {
@Id
private int id;
private String name;
private float money;
@ManyToMany(cascade = CascadeType.ALL)
private List<Author> authors;
public List<Author> getAuthors() {
return authors;
}
public void setAuthors(List<Author> authors) {
this.authors = authors;
}
...
}
@Entitypublic class Book implements java.io.Serializable { @Id private int id; private String name; private float money; @ManyToMany(cascade = CascadeType.ALL) private List<Author> authors; public List<Author> getAuthors() { return authors; } public void setAuthors(List<Author> authors) { this.authors = authors; } ...}
Java代码
@Entity
public class Author implements java.io.Serializable {
@Id
private int id;
private String name;
private int age;
@ManyToMany(mappedBy="authors")
private List<Book> books;
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
...
}
@Entitypublic class Author implements java.io.Serializable { @Id private int id; private String name; private int age; @ManyToMany(mappedBy="authors") private List<Book> books; public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } ...}
需要注意的是:注释最好加在属性上,不要加在get方法上,那样做有时候就会出错。比如:@ManyToMany的时候就会报错!
注意import javax.xx.Entity ,而不是org.hibernate.xx.Entity。
Descn属性不存在于数据库中,用@Transient 注明
------------------------------------------
1,需要: Hibernate库文件,Hibernate Annotations库,ejb3-persstence.jar(Java 持久化API)
sessionFactory=new AnnotationConfiguration().buildSessionFactory();
------------------------------------------
2,<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="annotatedClasses">
<list>
<value>com.onjava.modelplanes.domain.PlaneType</value>
</list>
</property>
</bean>
------------------------------------------
1,@Entity
@Table(name = "teacher_info")
@IdClass(UUIDHexGenerator.class)
public class UserMember implements java.io.Serializable
2,@entity通过getters/setters方法访问,或直接访问他的成员变量。
@Entity(access = AccessType.PROPERTY)
@Entity(access = AccessType.FIELD)
------------------------------------------
映射标识符
1,@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private String id;
2,@Id(generate=GeneratorType.SEQUENCE, generator='SEQ_STORE')
3,@Id(generate=GeneratorType.IDENTITY)
------------------------------------------
映射属性
1,@Transient
2,@Column(name="PLANE_ID", length=80, nullable=true)
3,@Basic(fetch = FetchType.LAZY)
4,@Serialized 凡标识@Serialized的属性将被序列化
public Country getCountry() { ... }
5,@Lob标识了存储对象可能是个CLOB或者BLOB。
@Lob(type=LobType.CLOB)
public String getFullText(){return fullText;}
@Lob(type = LobType.BLOB)
public byte[] getFullCode() {return fullCode;}
@Version 定义乐观锁机制使用
------------------------------------------
关联关系:
一、一对一:
1,@OneToOne(mappedBy = "address")
public User getUser() {
return user;
}
1、两边都定义了@OneToOne,但都没有定义mappedBy,则user和address表都会生成到对方的外键,双方都是这个关系的拥有者。
2、两边都定义了@OneToOne,如果user定义了mappedBy,则在address表生成到user的外键,address是这个关系的拥有者;如果address定义
了mappedBy,则在user表生成到address的外键,user是这个关系的拥有者。
二、一对多,多对一:
2,@ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
3,@OneToMany(mappedBy="planeType",cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@OrderBy("name")
public List<ModelPlane> getModelPlanes() {
return modelPlanes;
}
其中定义mappedBy的是@OneToMany,也就是说One这一方是关系的拥有者。Many一方的表中生成到关联类的外键。
三、@ManyToMany
private Set authors = new HashSet<Author>();
@ManyToMany
public Set<Author> getAuthors(){
return authors;
}
private Set books = new HashSet<Book>();
@ManyToMany(mappedBy="authors")
public Set<Book> getBooks(){
return books;
}
@ManyToMany会生成中间表,具体表名和字段可以通过@AssociationTable来定义,默认的就可以了,同样关系的非拥有者,需要定义mappedBy属性。
------------------------------------------
命名查询
你也可以通过注解,利用@NameQueries和@NameQuery注解,如下:
@NamedQueries(
{
@NamedQuery(name="planeType.findAll",query="select p from PlaneType p" ),
@NamedQuery(name="planeType.delete",query="delete from PlaneType where id=:id" )
}
)
------------------------------------------
内嵌对象(组件)
@Embedded({
@AttributeOverride(name='iso2', column = @Column(name='bornIso2') ),
@AttributeOverride(name='name', column = @Column(name='bornCountryName') )
})
Country bornIn;
...
}
@Embeddable(access = AccessType.FIELD)
public class Address implements Serializable {
String city;
Country nationality;
}
@Embeddable
public class Country implements Serializable {
private String iso2;
private String name;
public String getIso2() { return iso2; }
public void setIso2(String iso2) { this.iso2 = iso2; }
@Column(name='countryName')
public String getName() { return name; }
public void setName(String name) { this.name = name; }
...
}
------------------------------------------
自定义的主键生成策略
@javax.persistence.GeneratedIdTable(
name='GEN_TABLE',
table = @Table(name='GENERATOR_TABLE'),
pkColumnName = 'key',
valueColumnName = 'hi'
)
@javax.persistence.TableGenerator(
name='EMP_GEN',
tableName='GEN_TABLE',
pkColumnValue='EMP',
allocationSize=20
)
@javax.persistence.SequenceGenerator(
name='SEQ_GEN',
sequenceName='my_sequence'
)
package org.hibernate.test.metadata;
school和userMember是一对多关系
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.Formula;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "school_info")
public class SchoolInfo implements java.io.Serializable {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
private String id;//hibernate的uuid机制,生成32为字符串
@Column(name = "actcodeId", updatable = false, nullable = true, length = 36)
private String actcodeId;
@Formula("select COUNT(*) from school_info")
private int count;
@Temporal(TemporalType.TIMESTAMP)//不用set,hibernate会自动把当前时间写入
@Column(updatable = false, length = 20)
private Date createTime;
@Temporal(TemporalType.TIMESTAMP)
private Date updateTime;// 刚开始我默认insertable=false,但会读取出错提示如下:
// Value '0000-00-00' can not be represented as java.sql.Timestamp
// mappedBy="school"就相当于inverse=true,(mappedBy指定的是不需要维护关系的一端)
// 应该注意的是mappedBy值对应@ManyToOne标注的属性,我刚开始写成"schoolId",让我郁闷了好一会
@OneToMany(mappedBy = "school", cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = UserMember.class)
// 用范性的话,就不用targetEntity了
private List users = new ArrayList();
}
@GeneratedValue(strategy=GenerationType.AUTO)我们常用的自增长机制,我这里采用的是hibernate的uuid生成机制.
需要注意的是import javax.xx.Entity ,而不是org.hibernate.xx.Entity。
郁闷的是我上面用到@Formula,生成的sql竟然是'select COUNT(*) from school_info as formula0_ from school_info schoolinfo0_,当然不能执行了,寻求正解中~!!!!!!!!!
UserMember.java(前面引入的包已经贴过了,下面就不贴了)
@Entity
@Table(name = "teacher_info")//实体类和数据库表名不一致时,才用这个
public class UserMember implements java.io.Serializable {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
private String id;
@Column(updatable = false, nullable = false, length = 20)
private String logonName;
@Temporal(TemporalType.TIMESTAMP)
@Column(updatable = false, length = 20)
private Date createTime;
@Temporal(TemporalType.TIMESTAMP)
private Date updateTime;
@ManyToOne(cascade = { CascadeType.MERGE })
@JoinColumn(name = "schoolId")
private SchoolInfo school;
//注意该类就不用声明schoolId属性了,如果不用@JoinColumn指明关联的字段,hibernate默认会是school_id.
@Entity 类注释,所有要持久化的类都要有
Java代码
@Entity
public class Org implements java.io.Serializable {
}
@Entitypublic class Org implements java.io.Serializable {}
@Id 主键
Java代码
@Id
@GeneratedValue
private String orgId;
private String orgName;
@Id @GeneratedValue private String orgId; private String orgName;
@Column(name="...") 该属性对应表中的字段是什么,没有name表示一样
@Table 对象与表映射
@UniqueConstraint 唯一约束
@Version 方法和字段级,乐观锁用法,返回数字和timestamp,数字为首选
@Transient 暂态属性,表示不需要处理
@Basic 最基本的注释。有两个属性:fetch是否延迟加载,optional是否允许null
@Enumerated 枚举类型
@Temporal 日期转换。默认转换Timestamp
@Lob 通常与@Basic同时使用,提高访问速度。
@Embeddable 类级,表可嵌入的
@Embedded 方法字段级,表被嵌入的对象和@Embeddable一起使用
@AttributeOverrides 属性重写
@AttributeOverride 属性重写的内容和@AttributeOverrides一起嵌套使用
@SecondaryTables 多个表格映射
@SecondaryTable 定义辅助表格映射和@SecondaryTables一起嵌套使用
@GeneratedValue 标识符生成策略,默认Auto
表与表关系映射
@OneToOne:一对一映射。它包含五个属性:
targetEntity:关联的目标类
Cascade:持久化时的级联操作,默认没有
fetch:获取对象的方式,默认EAGER
Optional:目标对象是否允许为null,默认允许
mappedBy:定义双向关联中的从属类。
单向:
@JoinColumn:定义外键(主表会多一字段,做外键)
@OneToMany:一对多映射;@ManyToOne:多对一映射
单向一对多:
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="book_oid")/**book:表;oid:book表的主键;无name会按此规则自动生成*/
单向多对一:
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="author_oid")
关联表格一对多:
@OneToMany(cascade=CascadeType.ALL)
@JoinTable(joinColumn={@JoinColumn(name="BOOK_OBJECT_OID")},inverseJoinColumns={@JoinColumn(name="AUTHER_OBJECT_OID")})
双向一对多或多对一:
不需要多一张表,只是使用mappedBy:使用在One一方,值为One方类名表示Many的从属类。
Java代码
@Entity
public class Org implements java.io.Serializable {
// Fields
@Id
@GeneratedValue
private String orgId;
private String orgName;
@OneToMany(mappedBy = "org")
private List<Department> departments;
// Constructors
...
// Property accessors
...
}
@Entitypublic class Org implements java.io.Serializable { // Fields @Id @GeneratedValue private String orgId; private String orgName; @OneToMany(mappedBy = "org") private List<Department> departments; // Constructors... // Property accessors...}
Java代码
@Entity
public class Department implements java.io.Serializable {
// Fields
@Id
@GeneratedValue
private String id;
private String name;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="org_orgId")
private Org org;
@OneToMany(mappedBy = "department")
private List<Employee> employees;
// Constructors
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public Org getOrg() {
return org;
}
public void setOrg(Org org) {
this.org = org;
}
/** default constructor */
.
.
.
}
@Entitypublic class Department implements java.io.Serializable { // Fields @Id @GeneratedValue private String id; private String name; @ManyToOne(fetch=FetchType.EAGER) @JoinColumn(name="org_orgId") private Org org; @OneToMany(mappedBy = "department") private List<Employee> employees; // Constructors public List<Employee> getEmployees() { return employees; } public void setEmployees(List<Employee> employees) { this.employees = employees; } public Org getOrg() { return org; } public void setOrg(Org org) { this.org = org; } /** default constructor */ . . . }
Java代码
@Entity
public class Employee implements java.io.Serializable {
// Fields
@Id
@GeneratedValue
private String employeeId;
private String employeeName;
private String passWord;
private Integer age;
private Integer sex;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="department_id")
private Department department;
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
/** default constructor */
...
// Property accessors
...
}
@Entitypublic class Employee implements java.io.Serializable { // Fields @Id @GeneratedValue private String employeeId; private String employeeName; private String passWord; private Integer age; private Integer sex; @ManyToOne(fetch=FetchType.EAGER) @JoinColumn(name="department_id") private Department department; public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } /** default constructor */ ... // Property accessors ...}
双向多对多:@ManyToMany.单向多对多这里不在赘述(没有太多实际意义)
这个比较简单,看下代码就明白了:
Java代码
@Entity
public class Book implements java.io.Serializable {
@Id
private int id;
private String name;
private float money;
@ManyToMany(cascade = CascadeType.ALL)
private List<Author> authors;
public List<Author> getAuthors() {
return authors;
}
public void setAuthors(List<Author> authors) {
this.authors = authors;
}
...
}
@Entitypublic class Book implements java.io.Serializable { @Id private int id; private String name; private float money; @ManyToMany(cascade = CascadeType.ALL) private List<Author> authors; public List<Author> getAuthors() { return authors; } public void setAuthors(List<Author> authors) { this.authors = authors; } ...}
Java代码
@Entity
public class Author implements java.io.Serializable {
@Id
private int id;
private String name;
private int age;
@ManyToMany(mappedBy="authors")
private List<Book> books;
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
...
}
@Entitypublic class Author implements java.io.Serializable { @Id private int id; private String name; private int age; @ManyToMany(mappedBy="authors") private List<Book> books; public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } ...}
需要注意的是:注释最好加在属性上,不要加在get方法上,那样做有时候就会出错。比如:@ManyToMany的时候就会报错!
注意import javax.xx.Entity ,而不是org.hibernate.xx.Entity。
Descn属性不存在于数据库中,用@Transient 注明
------------------------------------------
1,需要: Hibernate库文件,Hibernate Annotations库,ejb3-persstence.jar(Java 持久化API)
sessionFactory=new AnnotationConfiguration().buildSessionFactory();
------------------------------------------
2,<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="annotatedClasses">
<list>
<value>com.onjava.modelplanes.domain.PlaneType</value>
</list>
</property>
</bean>
------------------------------------------
1,@Entity
@Table(name = "teacher_info")
@IdClass(UUIDHexGenerator.class)
public class UserMember implements java.io.Serializable
2,@entity通过getters/setters方法访问,或直接访问他的成员变量。
@Entity(access = AccessType.PROPERTY)
@Entity(access = AccessType.FIELD)
------------------------------------------
映射标识符
1,@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private String id;
2,@Id(generate=GeneratorType.SEQUENCE, generator='SEQ_STORE')
3,@Id(generate=GeneratorType.IDENTITY)
------------------------------------------
映射属性
1,@Transient
2,@Column(name="PLANE_ID", length=80, nullable=true)
3,@Basic(fetch = FetchType.LAZY)
4,@Serialized 凡标识@Serialized的属性将被序列化
public Country getCountry() { ... }
5,@Lob标识了存储对象可能是个CLOB或者BLOB。
@Lob(type=LobType.CLOB)
public String getFullText(){return fullText;}
@Lob(type = LobType.BLOB)
public byte[] getFullCode() {return fullCode;}
@Version 定义乐观锁机制使用
------------------------------------------
关联关系:
一、一对一:
1,@OneToOne(mappedBy = "address")
public User getUser() {
return user;
}
1、两边都定义了@OneToOne,但都没有定义mappedBy,则user和address表都会生成到对方的外键,双方都是这个关系的拥有者。
2、两边都定义了@OneToOne,如果user定义了mappedBy,则在address表生成到user的外键,address是这个关系的拥有者;如果address定义
了mappedBy,则在user表生成到address的外键,user是这个关系的拥有者。
二、一对多,多对一:
2,@ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
3,@OneToMany(mappedBy="planeType",cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@OrderBy("name")
public List<ModelPlane> getModelPlanes() {
return modelPlanes;
}
其中定义mappedBy的是@OneToMany,也就是说One这一方是关系的拥有者。Many一方的表中生成到关联类的外键。
三、@ManyToMany
private Set authors = new HashSet<Author>();
@ManyToMany
public Set<Author> getAuthors(){
return authors;
}
private Set books = new HashSet<Book>();
@ManyToMany(mappedBy="authors")
public Set<Book> getBooks(){
return books;
}
@ManyToMany会生成中间表,具体表名和字段可以通过@AssociationTable来定义,默认的就可以了,同样关系的非拥有者,需要定义mappedBy属性。
------------------------------------------
命名查询
你也可以通过注解,利用@NameQueries和@NameQuery注解,如下:
@NamedQueries(
{
@NamedQuery(name="planeType.findAll",query="select p from PlaneType p" ),
@NamedQuery(name="planeType.delete",query="delete from PlaneType where id=:id" )
}
)
------------------------------------------
内嵌对象(组件)
@Embedded({
@AttributeOverride(name='iso2', column = @Column(name='bornIso2') ),
@AttributeOverride(name='name', column = @Column(name='bornCountryName') )
})
Country bornIn;
...
}
@Embeddable(access = AccessType.FIELD)
public class Address implements Serializable {
String city;
Country nationality;
}
@Embeddable
public class Country implements Serializable {
private String iso2;
private String name;
public String getIso2() { return iso2; }
public void setIso2(String iso2) { this.iso2 = iso2; }
@Column(name='countryName')
public String getName() { return name; }
public void setName(String name) { this.name = name; }
...
}
------------------------------------------
自定义的主键生成策略
@javax.persistence.GeneratedIdTable(
name='GEN_TABLE',
table = @Table(name='GENERATOR_TABLE'),
pkColumnName = 'key',
valueColumnName = 'hi'
)
@javax.persistence.TableGenerator(
name='EMP_GEN',
tableName='GEN_TABLE',
pkColumnValue='EMP',
allocationSize=20
)
@javax.persistence.SequenceGenerator(
name='SEQ_GEN',
sequenceName='my_sequence'
)
package org.hibernate.test.metadata;
school和userMember是一对多关系
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.Formula;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "school_info")
public class SchoolInfo implements java.io.Serializable {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
private String id;//hibernate的uuid机制,生成32为字符串
@Column(name = "actcodeId", updatable = false, nullable = true, length = 36)
private String actcodeId;
@Formula("select COUNT(*) from school_info")
private int count;
@Temporal(TemporalType.TIMESTAMP)//不用set,hibernate会自动把当前时间写入
@Column(updatable = false, length = 20)
private Date createTime;
@Temporal(TemporalType.TIMESTAMP)
private Date updateTime;// 刚开始我默认insertable=false,但会读取出错提示如下:
// Value '0000-00-00' can not be represented as java.sql.Timestamp
// mappedBy="school"就相当于inverse=true,(mappedBy指定的是不需要维护关系的一端)
// 应该注意的是mappedBy值对应@ManyToOne标注的属性,我刚开始写成"schoolId",让我郁闷了好一会
@OneToMany(mappedBy = "school", cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = UserMember.class)
// 用范性的话,就不用targetEntity了
private List users = new ArrayList();
}
@GeneratedValue(strategy=GenerationType.AUTO)我们常用的自增长机制,我这里采用的是hibernate的uuid生成机制.
需要注意的是import javax.xx.Entity ,而不是org.hibernate.xx.Entity。
郁闷的是我上面用到@Formula,生成的sql竟然是'select COUNT(*) from school_info as formula0_ from school_info schoolinfo0_,当然不能执行了,寻求正解中~!!!!!!!!!
UserMember.java(前面引入的包已经贴过了,下面就不贴了)
@Entity
@Table(name = "teacher_info")//实体类和数据库表名不一致时,才用这个
public class UserMember implements java.io.Serializable {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
private String id;
@Column(updatable = false, nullable = false, length = 20)
private String logonName;
@Temporal(TemporalType.TIMESTAMP)
@Column(updatable = false, length = 20)
private Date createTime;
@Temporal(TemporalType.TIMESTAMP)
private Date updateTime;
@ManyToOne(cascade = { CascadeType.MERGE })
@JoinColumn(name = "schoolId")
private SchoolInfo school;
//注意该类就不用声明schoolId属性了,如果不用@JoinColumn指明关联的字段,hibernate默认会是school_id.
相关推荐
hibernate注释详解 内含hibernate各种注释说明
【Hibernate注释深入解析】 在Java开发中,Hibernate是一个广泛使用的对象关系映射(ORM)框架,它允许开发者使用面向对象的方式操作数据库。在Hibernate中,注释是一种强大的工具,可以简化配置,使得代码更加简洁...
**hibernate注释源程序详解** 在Java领域,Hibernate是一个非常重要的对象关系映射(ORM)框架,它简化了数据库操作,使开发者能够用Java对象来操作数据库。本篇文章将深入探讨Hibernate中的注释(Annotation)使用...
### Hibernate注释方法描述数据库映射 #### 一、概述 Hibernate 是一款强大的对象关系映射(ORM)框架,它简化了 Java 开发者与数据库交互的过程。在 Hibernate 中,可以利用注解来描述实体类与数据库表之间的映射...
以上就是关于Hibernate注释的基本知识,它们在Java对象和数据库表之间的映射中起着至关重要的作用,简化了开发过程,并提供了更灵活的持久化管理。通过合理使用这些注解,开发者能够有效地控制对象的生命周期,处理...
Hibernate 注释语法的简单讲解,个人的学习总结笔记
使用hibernate注解,必须要使用库hibernate-commons-annotations,hibernate-core,hibernate-jpa,ejb3-persistence,javassist等
一、Hibernate注释基础 1. `@Entity`: 这个注释标记一个Java类为持久化实体,意味着这个类的实例将在数据库中有一个对应的表。例如: ```java @Entity public class User { // ... } ``` 这会告诉Hibernate,User...
**Hibernate 5.2.4 环境搭建与源码解析** Hibernate 是一个流行的 Java 对象关系映射(ORM)框架,它极大地简化了数据库操作。在本教程中,我们将详细探讨如何搭建 Hibernate 5.2.4 的开发环境,并理解其源码。 ...
使用hibernate注释的核心优点是我们不需要创建映射(*.hbm.xml)文件直接创建对象关联。 在这里,hibernate注释用于提供元数据。步骤如下: 1.为MySQL添加连接驱动程序的jar文件(如果数据库是MySQL)和注释2.创建持久化...
总结,`Hibernate-tools`是Hibernate生态中不可或缺的一部分,它极大地提高了开发效率,同时也为处理中文注释提供了有效方案。通过合理配置和使用,我们可以避免乱码问题,并生成符合规范的带有丰富注释的实体类代码...
《Hibernate注释与枚举映射详解》 Hibernate作为Java领域中最流行的ORM(对象关系映射)框架之一,极大地简化了数据库操作。本篇将详细探讨`hibernate-annotations-3.4.0.GA`和`hibernate-entitymanager-3.4.0.GA`...
通过阅读《Hibernate注释.doc》和《Hibernate注释大全.txt》这两个文档,你可以获得更详细的信息,深入理解Hibernate注解的使用场景和配置细节。同时,参考提供的博文链接...
例如,`@Column`、`@Table`、`@Id`等,这些都是Hibernate注释类型,它们提供了关于数据库列、表和主键的信息。例如: ```java /** * @Table(name="users") * @Id * @GeneratedValue(strategy=GenerationType....
hibernate@注解方式配置实体类时,利用javadoc接口生成数据库表及字段的注释说明,支持oracle、sqlserver、db2、mysql数据库。因用到java\lib\tools.jar,需要将该jar放入工程lib下(或者tomcat\lib下、或加入...
《Hibernate注解详解》 Hibernate 是一款强大的Java对象关系映射(ORM)框架,它极大地简化了数据库操作。在Hibernate中,注解是用于描述Java类及其属性如何映射到数据库表的重要工具。本文将全面解析Hibernate中的...
hibernate-distribution-3.3.2.GA-dist.zip:是Hibernate的core,核心包。 hibernate-annotations-3.4.0.GA.zip:Hibernate注释包。 slf4j-1.5.8.zip:Hibernate做日志时用到该日志框架。
《注释驱动的Hibernate实战详解》 在Java的持久化框架中,Hibernate以其强大的功能和易用性,深受开发者喜爱。然而,随着Java技术的发展,传统的XML配置方式逐渐被注解(Annotation)所取代,使得代码更加简洁、...