首页 > 技术文章 > JPA实体关联关系,一对一以及转换器

Cassie-wang 2018-10-24 14:14 原文

  现有两张表

  room (rid,name,address,floor)

  room_detail (rid,roomid,type)

  需要创建房间实体,但是也要包含type属性

  

@Data  //lambok生成get,set方法
@Entity
@EqualsAndHashCode(callSuper=false, onlyExplicitlyIncluded = true) //此注解会生成equals(Object other) 和 hashCode()方法
@Table(name="room")
@SecondaryTable(name="room_detail",pkJoinColumns=@PrimaryKeyJoinColumn(name="roomid"))//关联的表,填写关联字段
public class RoomEntity implements Serializable{
    
    private static final long serialVersionUID = -7921327682701819877L;
@Column(nullable
=false,unique = true) private Long rid;
   private String name;
    private String address;
  
    /**房间类型**/
    @Column(table="room_detail")
    @Convert(converter=RoomTypeConverter.class)
    private RoomType type;
    

    /**楼层**/
    @Column(table="room_detail")
    private Integer floor;
    
}

@Converter 是JPA的转换器,枚举类型与数据库交互使用,比如房间类型 1代表客房,2代表办公室,数据库是1,2,展示需要客房,办公室,用转换器转

  自己实现接口AttributeConverter ,实现两个方法

例如

public class RoomTypeConverter implements AttributeConverter<RoomType, Integer> {

    @Override
    public Integer convertToDatabaseColumn(RoomType attribute) {
        // TODO Auto-generated method stub
        return attribute.getCode();
    }

    @Override
    public RoomType convertToEntityAttribute(Integer dbData) {
        // TODO Auto-generated method stub
        return RoomTypes.valueOf(dbData);
    }

}

RoomType是枚举类,就不贴代码了

推荐阅读