摘自:http://www.javaeye.com/topic/95822
school和userMember是一对多关系:
SchoolInfo.java
1import javax.persistence.CascadeType;
2import javax.persistence.Column;
3import javax.persistence.Entity;
4import javax.persistence.FetchType;
5import javax.persistence.GeneratedValue;
6import javax.persistence.Id;
7import javax.persistence.OneToMany;
8import javax.persistence.Table;
9import javax.persistence.Temporal;
10import javax.persistence.TemporalType;
11
12import org.hibernate.annotations.Formula;
13import org.hibernate.annotations.GenericGenerator;
14
15@Entity
16@Table(name = "school_info")
17public class SchoolInfo implements java.io.Serializable {
18
19 @Id
20 @GeneratedValue(generator = "system-uuid")
21 @GenericGenerator(name = "system-uuid", strategy = "uuid")
22 private String id;//hibernate的uuid机制,生成32为字符串
23
24 @Column(name = "actcodeId", updatable = false, nullable = true, length = 36)
25 private String actcodeId;
26
27 @Formula("select COUNT(*) from school_info")
28 private int count;
29
30 @Temporal(TemporalType.TIMESTAMP)//不用set,hibernate会自动把当前时间写入
31 @Column(updatable = false, length = 20)
32 private Date createTime;
33
34 @Temporal(TemporalType.TIMESTAMP)
35 private Date updateTime;// 刚开始我默认insertable=false,但会读取出错提示如下:
36 // Value '0000-00-00' can not be represented as java.sql.Timestamp
37
38 // mappedBy="school"就相当于inverse=true,(mappedBy指定的是不需要维护关系的一端)
39 // 应该注意的是mappedBy值对应@ManyToOne标注的属性,我刚开始写成"schoolId",让我郁闷了好一会
40 @OneToMany(mappedBy = "school", cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = UserMember.class)
41 // 用范性的话,就不用targetEntity了
42 private List<usermember> users = </usermember>new ArrayList<usermember>(); </usermember>
43
44}
45
@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(前面引入的包已经贴过了,下面就不贴了)
1 @Entity
2 @Table(name = "teacher_info")//实体类和数据库表名不一致时,才用这个
3 public class UserMember implements java.io.Serializable {
4
5 @Id
6 @GeneratedValue(generator = "system-uuid")
7 @GenericGenerator(name = "system-uuid", strategy = "uuid")
8 private String id;
9
10 @Column(updatable = false, nullable = false, length = 20)
11 private String logonName;
12
13 @Temporal(TemporalType.TIMESTAMP)
14 @Column(updatable = false, length = 20)
15 private Date createTime;
16
17 @Temporal(TemporalType.TIMESTAMP)
18 private Date updateTime;
19
20 @ManyToOne(cascade = { CascadeType.MERGE })
21 @JoinColumn(name = "schoolId")
22 private SchoolInfo school;
23 //注意该类就不用声明schoolId属性了,如果不用@JoinColumn指明关联的字段,hibernate默认会是school_id.
24
25 }
posted on 2009-07-26 13:40
jiafang83 阅读(3176)
评论(1) 编辑 收藏