天天看点

hibernate实现继承关系Inheritance

使用@MappedSuperclass注解,可以在多个表之间共享父类的所有字段。但是有时候我们并不想有多个表。这时候hibernate提供了注解

@Inheritance(strategy = InheritanceType.SINGLE_TABLE)

@Entity(name = "Account")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public static class Account {

    @Id
    private Long id;

    private String owner;

    private BigDecimal balance;

    private BigDecimal interestRate;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

    public BigDecimal getBalance() {
        return balance;
    }

    public void setBalance(BigDecimal balance) {
        this.balance = balance;
    }

    public BigDecimal getInterestRate() {
        return interestRate;
    }

    public void setInterestRate(BigDecimal interestRate) {
        this.interestRate = interestRate;
    }
}

@Entity(name = "DebitAccount")
public static class DebitAccount extends Account {

    private BigDecimal overdraftFee;

    public BigDecimal getOverdraftFee() {
        return overdraftFee;
    }

    public void setOverdraftFee(BigDecimal overdraftFee) {
        this.overdraftFee = overdraftFee;
    }
}

@Entity(name = "CreditAccount")
public static class CreditAccount extends Account {

    private BigDecimal creditLimit;

    public BigDecimal getCreditLimit() {
        return creditLimit;
    }

    public void setCreditLimit(BigDecimal creditLimit) {
        this.creditLimit = creditLimit;
    }
}
           

他们产生的sql语句应该是

CREATE TABLE Account (
    DTYPE VARCHAR() NOT NULL ,
    id BIGINT NOT NULL ,
    balance NUMERIC(, ) ,
    interestRate NUMERIC(, ) ,
    owner VARCHAR() ,
    overdraftFee NUMERIC(, ) ,
    creditLimit NUMERIC(, ) ,
    PRIMARY KEY ( id )
)
           

举个例子

DebitAccount debitAccount = new DebitAccount();
debitAccount.setId( L );
debitAccount.setOwner( "John Doe" );
debitAccount.setBalance( BigDecimal.valueOf(  ) );
debitAccount.setInterestRate( BigDecimal.valueOf( d ) );
debitAccount.setOverdraftFee( BigDecimal.valueOf(  ) );

CreditAccount creditAccount = new CreditAccount();
creditAccount.setId( L );
creditAccount.setOwner( "John Doe" );
creditAccount.setBalance( BigDecimal.valueOf(  ) );
creditAccount.setInterestRate( BigDecimal.valueOf( d ) );
creditAccount.setCreditLimit( BigDecimal.valueOf(  ) );

entityManager.persist( debitAccount );
entityManager.persist( creditAccount );
           
###对应的sql
INSERT INTO Account (balance, interestRate, owner, overdraftFee, DTYPE, id)
VALUES (, , 'John Doe', , 'DebitAccount', )

INSERT INTO Account (balance, interestRate, owner, creditLimit, DTYPE, id)
VALUES (, , 'John Doe', , 'CreditAccount', )