Hibernate为同一个表扩展实体

Hibernate为同一个表扩展实体

本文介绍了Hibernate为同一个表扩展实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个字段的表
我想要两个对象。



第一个只有field1

  @Entity(name =simpleTableObject)
@Table(name =someTable)
public class SimpleTableObject
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name =id)
保护长ID;

@Column(name =field1)
private String field1;

第二个有两个字段



<$ p
$ @Entity(name =tableObject)
@Table(name =someTable)
public class TableObject
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name =id)
保护长ID;

@Column(name =field1)
private String field1;

@Column(name =field2)
private String field2;

我使用
<$ p $加载每一个
public class get(Class aClass)
{
ClassMetadata hibernateMetadata = sessionFactory @Transactional(readOnly = true)
@SuppressWarnings(unchecked .getClassMetadata(ACLASS);
if(hibernateMetadata == null)
{
return null;

if(hibernateMetadata instanceof AbstractEntityPersister)
{
AbstractEntityPersister persister =(AbstractEntityPersister)hibernateMetadata;
String tableName = persister.getTableName();
if(tableName!= null)
{
return sessionFactory.getCurrentSession()。
createQuery(from+ tableName).list();
}
}
返回null;
}

我想要做的是有 TableObject 扩展 SimpleTableObject 。如果你想在你需要的表中保存公共字段意味着假设你有类A和类A, B和你有一些常见的领域像created_by,updated_by,并且你想在这两个实体中保存field1,field2:
IN数据库级别:

 查询>从A选择*; 
+ ---- ++ ------------------------ +
| id | created_by | updated_by |
+ ---- + ------------ + ------------ +
| 3 | xyz | abc |
+ ---- + ------------ + ------------ +
查询>从B选择*;
+ ---- ++ ------------------------ +
| id | created_by | updated_by |
+ ---- + ------------ + ------------ +
| 3 | xyz | abc |
+ ---- + ------------ + ------------ +

对于这种类型的结构,您应该使用@MappedSuperclass作为@Dragan Bozanovic建议

但是如果您想要Parent子关系和希望为每个类生成表,然后你可以使用
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
它将为每个类创建表
例如:假设您有2个类Payment和CreditCard,付款是CreditCard的父类。

  @Entity 
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Payment {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private int id;
@Column(nullable = false)
私人双重金额;

public int getId(){
return id;
}

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

public double getAmount(){
return amount;
}

public void setAmount(double amount){
this.amount = amount;
}
}


@实体
公共类CreditCard延伸付款{
私人字符串ccNumber;
私人日期expireDate;

public String getCcNumber(){
return ccNumber;
}

public void setCcNumber(String ccNumber){
this.ccNumber = ccNumber;
}

public Date getExpireDate(){
return expireDate;
}

public void setExpireDate(Date expireDate){
this.expireDate = expireDate;


现在您将保存日期:

  public class TestConcreteClasses {
public static void main(String [] args){
Payment payment = new Payment();
payment.setAmount(52.6);
createData(付款);
CreditCard creditCard =新CreditCard();
creditCard.setAmount(10);
creditCard.setCcNumber(2536985474561236);
creditCard.setExpireDate(new Date());
createData(creditCard);



private static void createData(Payment instance){
Session session = HibernateUtil.getSession();
session.beginTransaction();
session.save(instance);
session.getTransaction()。commit();


然后数据将保存为像

 查询>从付款中选择*; 
+ ---- + -------- +
| id |数额|
+ ---- + -------- +
| 1 | 52.6 |
+ ---- + -------- +
1行(0.00秒)

从CreditCard中选择*
+ ---- + -------- + ------------------ + ------------ --------- +
| id |数额| ccNumber | expireDate |
+ ---- + -------- + ------------------ + ------------ --------- +
| 2 | 10 | 2536985474561236 | 2017-03-12 14:10:15 |
+ ---- + -------- + ------------------ + ------------ --------- +
1行(0.00秒)

hibernate中有3种类型的继承,这里是继承hibernate doc
,你应该根据你的要求选择它们中的任何一个。

I have a table with two fieldsI would like to have two objects.

First one only has field1

@Entity(name = "simpleTableObject")
@Table(name = "someTable")
public class SimpleTableObject
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    protected long id;

    @Column(name = "field1")
    private String field1;

Second one has all two fields

@Entity(name = "tableObject")
@Table(name = "someTable")
public class TableObject
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    protected long id;

    @Column(name = "field1")
    private String field1;

    @Column(name = "field2")
    private String field2;

I load each one using

@Transactional(readOnly = true)
@SuppressWarnings("unchecked")
public List get(Class aClass)
{
    ClassMetadata hibernateMetadata = sessionFactory.getClassMetadata(aClass);
    if (hibernateMetadata == null)
    {
        return null;
    }
    if (hibernateMetadata instanceof AbstractEntityPersister)
    {
        AbstractEntityPersister persister = (AbstractEntityPersister) hibernateMetadata;
        String                  tableName = persister.getTableName();
        if (tableName != null)
        {
            return sessionFactory.getCurrentSession().
                    createQuery("from " + tableName).list();
        }
    }
    return null;
}

What I would like to do is have TableObject extend SimpleTableObject. How would I go about doing that?

解决方案

If you want save common fields in your required tables means suppose you have class A and B and you have some common filed like created_by,updated_by and you want to save field1,field2 in both entity:IN database level:

query> select * from A;
+----++------------------------+
| id | created_by | updated_by |
+----+------------+------------+
|  3 |    xyz     | abc        |
+----+------------+------------+
query> select * from B;
 +----++------------------------+
| id | created_by | updated_by |
+----+------------+------------+
|  3 |    xyz     | abc        |
+----+------------+------------+

for this type of structure you should use @MappedSuperclass as @Dragan Bozanovic suggested

But if you want Parent Child relation and want generate table per class then you can use@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)it will create table per classe.g: Suppose you have 2 class Payment and CreditCard, Payment is parent class for CreditCard.

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Payment {
    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    private int id;
    @Column(nullable = false)
    private double amount;

    public int getId() {
        return id;
    }

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

    public double getAmount() {
        return amount;
    }

    public void setAmount(double amount) {
        this.amount = amount;
    }
}


@Entity
public class CreditCard extends Payment {
private String ccNumber;
private Date expireDate;

    public String getCcNumber() {
        return ccNumber;
    }

    public void setCcNumber(String ccNumber) {
        this.ccNumber = ccNumber;
    }

    public Date getExpireDate() {
        return expireDate;
    }

    public void setExpireDate(Date expireDate) {
        this.expireDate = expireDate;
    }
}

Now you will save date :

public class TestConcreteClasses {
    public static void main(String[] args) {
        Payment payment = new Payment();
        payment.setAmount(52.6);
        createData(payment);
        CreditCard creditCard = new CreditCard();
        creditCard.setAmount(10);
        creditCard.setCcNumber("2536985474561236");
        creditCard.setExpireDate(new Date());
        createData(creditCard);

    }

    private static void createData(Payment instance) {
        Session session = HibernateUtil.getSession();
        session.beginTransaction();
        session.save(instance);
        session.getTransaction().commit();
    }
}

then data will save like

query> select * from Payment;
+----+--------+
| id | amount |
+----+--------+
|  1 |   52.6 |
+----+--------+
1 row in set (0.00 sec)

 select * from CreditCard;
+----+--------+------------------+---------------------+
| id | amount | ccNumber         | expireDate          |
+----+--------+------------------+---------------------+
|  2 |     10 | 2536985474561236 | 2017-03-12 14:10:15 |
+----+--------+------------------+---------------------+
1 row in set (0.00 sec)

There are 3 types of inheritance used in hibernate, here is hibernate doc for inheritancehttps://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/InheritanceType.html, you should pick any of them according to your requirement.

这篇关于Hibernate为同一个表扩展实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 09:32