xUtils系列之DbUtils-Foreign注解

Foreign注解定义:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Foreign {
    String column() default "";

    String foreign();
}

DbUtils解析部分:
else if (ColumnUtils.isForeign(field)) {
   Foreign column = new Foreign(entityType, field);
   if (!columnMap.containsKey(column.getColumnName())) {
       columnMap.put(column.getColumnName(), column);
   }
}

在Foreign.java中:
Column column = TableUtils.getColumnOrId(columnType, foreignColumnName);
columnValue = column.getColumnValue(fieldValue);

Table table = this.getTable();
if (table != null && columnValue == null && column instanceof Id) {
    table.db.saveOrUpdate(fieldValue); //@Foreign中foreign必须为外键所在类的主键
}

columnValue = column.getColumnValue(fieldValue);

注意:
1.@Foreign中column不能和类中其它的Column名称相同,否则会造成列名重复异常

2.@Foreign中foreign必须为外键所在类的主键

3.xUtils官方所带例子中,有一个例子是foreign为非主键,这个是错误的.

4.假如有两个类Child和Parent,Child的字段parentId是Parent主键的外键,
  当使用DbUtils.save(child)是,DbUtils会自动保存与Child关联的Parent.
  此时如果再调用DbUtils.save(parent),会造成重复数据

用法:
@Table(name = "parent", execAfterTableCreated = "CREATE UNIQUE INDEX index_name ON parent(name,email)")
public class Parent{

	private int id;

	<snip>
}


@Table(name = "child")  // 建议加上注解, 混淆后表名不受影响
public class Child extends EntityBase {

    private int id;
	
    //@Foreign(column = "parentId", foreign = "id")
    //public ForeignLazyLoader<Parent> parent;

    @Foreign(column = "parentId", foreign = "id")
    public Parent parent;

    <snip>
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值