hibernate annotation笔记
程序员文章站
2022-04-17 10:53:45
...
school和userMember是一对多关系,一些基本配置就不写了:
SchoolInfo.java
@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")//实体类和数据库表名不一致时,才用这个
SchoolInfo.java
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.
}