hibernate的继承映射
hibernate的继承映射有三种策略:joined_table、single_table、table_per_class
我们今天使用single_table作为例子
domain:
/** * * {好友类型的抽象父类信息} * @author jerome * @version 1.0.0 * */ @javax.persistence.Entity @javax.persistence.Table(name = "mag_friend_type_common") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "friend_type", discriminatorType=DiscriminatorType.INTEGER) public abstract class FriendSuper { // 主键 private Long ftcId; // 类型名称 private String ftcName; /** * the getter method of ftcId * @return the ftcId */ @Id @Column(name="ftd_id", length=20) @GeneratedValue(strategy = GenerationType.IDENTITY) public Long getFtcId() { return ftcId; } /** * the setter method of the ftcId * @param ftcId the ftcId to set */ public void setFtcId(Long ftcId) { this.ftcId = ftcId; }
/** * {实体类FriendTypeCommon,对应mag_friend_type_common表} * @author jerome * @version 1.0.0 * */ @javax.persistence.Entity //@DiscriminatorColumn(discriminatorType = DiscriminatorType.INTEGER) @DiscriminatorValue("0") @Cache(usage = CacheConcurrencyStrategy.READ_ONLY,region="personalEmp") public class FriendTypeCommon extends FriendSuper implements Serializable { private static final long serialVersionUID = 1L; }
/** * {实体类FriendTypeDiy,对应mag_friend_type_common表} * @author jerome * @version 1.0.0 * */ @javax.persistence.Entity //@DiscriminatorColumn(discriminatorType = DiscriminatorType.INTEGER) @DiscriminatorValue("1") public class FriendTypeDiy extends FriendSuper implements Serializable { // serialVersionUID private static final long serialVersionUID = 1L; // 外键,关联实体类UserMain private UserMain userMain; /** * the getter method of userMain * @return the userMain */ @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="user_id", nullable=false) public UserMain getUserMain() { return userMain; } /** * the setter method of the userMain * @param userMain the userMain to set */ public void setUserMain(UserMain userMain) { this.userMain = userMain; } }
junit测试得:
公共类型:
对FriendTypeCommon对象操作: Hibernate: select this_.ftd_id as ftd2_0_0_, this_.ftd_name as ftd3_0_0_ from mag_friend_type_common this_ where this_.friend_type=0 同学 朋友
自定义类型:
FriendTypeDiy: Hibernate: select this_.ftd_id as ftd2_0_1_, this_.ftd_name as ftd3_0_1_, this_.user_id as user4_0_1_, um1_.user_id as user1_1_0_, um1_.user_code as user2_1_0_, um1_.user_password as user3_1_0_, um1_.user_gender as user4_1_0_, um1_.user_date_of_birth as user5_1_0_, um1_.user_image as user6_1_0_, um1_.user_email as user7_1_0_, um1_.user_remark as user8_1_0_, um1_.user_name as user9_1_0_ from mag_friend_type_common this_ inner join mag_user_main um1_ on this_.user_id=um1_.user_id where this_.friend_type=1 and um1_.user_id=? 我的亲戚