JPA实体关联关系,一对一以及转换器
生活随笔
收集整理的這篇文章主要介紹了
JPA实体关联关系,一对一以及转换器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
現有兩張表
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> {@Overridepublic Integer convertToDatabaseColumn(RoomType attribute) {// TODO Auto-generated method stubreturn attribute.getCode();}@Overridepublic RoomType convertToEntityAttribute(Integer dbData) {// TODO Auto-generated method stubreturn RoomTypes.valueOf(dbData);}}RoomType是枚舉類,就不貼代碼了
轉載于:https://www.cnblogs.com/Cassie-wang/p/9843292.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的JPA实体关联关系,一对一以及转换器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 进程创建 033
- 下一篇: modelform save