情形:两个表,cms_mode是主表,cms_model_field是子表,cms_model_field的model_id字段关联到cms_model的主键。



#
# Source for table cms_model
#

DROP TABLE IF EXISTS `cms_model`;
CREATE TABLE `cms_model` (
`model_id` int(11) NOT NULL,
`name` varchar(50) NOT NULL DEFAULT '',
`title` varchar(100) NOT NULL DEFAULT '' COMMENT '名称',
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT='CMS模型表';

#
# Source for table cms_model_field
#

DROP TABLE IF EXISTS `cms_model_field`;
CREATE TABLE `cms_model_field` (
`field_id` int(11) NOT NULL AUTO_INCREMENT,
`model_id` int(11) NOT NULL DEFAULT '0' COMMENT '模型ID',
`name` varchar(50) DEFAULT NULL COMMENT '名称',
`title` varchar(250) NOT NULL DEFAULT '' COMMENT '标题',
`priority` int(11) NOT NULL DEFAULT '0' COMMENT '权重',
`data_type` char(1) NOT NULL DEFAULT '1' COMMENT '数据类型(S-字符,N-数值,D-日期,T-备注)',
`is_reserved` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否保留',
PRIMARY KEY (`field_id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='CMS模型字段表';;


CmsModel.java:



@Entity
@Table(name = "cms_model")
@SuppressWarnings("serial")
public class CmsModel implements Serializable
{
@Id
@GeneratedValue
@Column(name = "model_id")
private Integer id;

@Column(name = "name")
private String name;

@Column(name = "title")
private String title;

@OneToMany(mappedBy = "model",
fetch = FetchType.LAZY)
private List<CmsModelField> fieldList;
}


CmsModelField.java:



@Entity
@Table(name = "cms_model_field")
@SuppressWarnings("serial")
public class CmsModelField implements Serializable
{
@Id
@GeneratedValue
@Column(name = "field_id")
private Integer id;

@Column(name = "name")
private String name;

@Column(name = "title")
private String title;

@Column(name = "data_type")
private String dataType;

@Column(name = "priority")
private Integer priority;

@Column(name = "is_reserved")
private Boolean reserved;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "model_id")
private CmsModel model;
}


@OneToMany Default: FetchType.LAZY默认是延迟抓取,不需要左联接。如果是FetchType.EAGER即时抓取,就会是左联接查询。

@ManyToOne Default: FetchType.EAGER默认是即时抓取,做连接。如果fetch=FetchType.LAZY不是左联接,在需要One的时候直接select。