如何使用2个级别的@MapKey注释?

时间:2011-01-16 12:37:28

标签: java hibernate hibernate-mapping

这个问题与我提出的其他question类似,但略有不同。

我有这个:

class A{

  private List<B> bs;

  ...
}

class B{

  private Long id;
  private C c;
  ...
} 

class C{

  private Long id;
  private String name;
  ...
} 

我想要这个:

class A{

  // the map should have b.c.name as key
  private Map<String,B> bs;

  ...
}

class B{

  private Long id;
  private C c;
  private A a;
  ...
} 

class C{

  private Long id;
  private String name;
  ...
} 

我不知道我是否清楚自己想要做什么,但它就像将一对多关系映射到一个地图一样简单,名称为C作为地图的关键,b为值。

提前致谢, Neuquino

3 个答案:

答案 0 :(得分:4)

简短的回答是你不能这样做。

但这里的解决方案可能适合您的问题:

在实体A中,仍然将实体B定义为List(或者甚至更好地设置为Set,以便不能同时包含相同的B)。

@OneToMany(mappedBy="a")
private Set<B> bs;

由于您不想公开普通列表,请省略as的getter和setter。

然后你可以为你的地图定义一个getter来实时构建地图:

// a transient field to cache the map
private transient Map<String, B> bsMappedByCName;

public Map<String, B> getBsMappedByCName() {
  if(bsMappedByCName == null) {
    bsMappedByCName = new HashMap<String, B>();
    for(B b : bs) {
      mapB(b);
    }
  }
  // return as unmodifiable map so that it is immutable for clients
  return Collections.unmodifiableMap(bsMappedByCName);
}

private void mapB(B b) {
  // we assume here that field c in class B and likely also field name in class C are not nullable. Further more both of this fields sould be immutable (i.e. have no setter).
  if(bsMappedByCName.put(b.getC().getName(), b) != null) {
    // multiple bs with same CName, this is an inconsistency you may handle 
  }      
}

要解决的最后一个问题是我们如何向A添加新B或删除一个。使用将地图返回为不可修改的策略,我们必须在A类中提供一些添加和卸载方法:

public void addB(B b) {
  bs.add(b);
  mapB(b);
}

public void removeB(B b) {
  bs.remove(b);
  bsMappedByCName.remove(b.getC().getName());
}

另一个选择是将return Collections.unmodifiableMap(...)替换为(受ObservaleCollection from apache启发):

return new Map<String, B>() {
  // implement all methods that add or remove elements in map with something like this
  public B put(String name, B b) {
    // check consistency
    if(!b.getC().getName().equals(name)) { 
      // this sould be handled as an error
    }
    B oldB = get(name);
    mapB(b);
    return oldB;
  }

  // implement all accessor methods like this
  public B get(String name) {
    return bsMappedByCName.get(name);
  }

  // and so on...
};

答案 1 :(得分:0)

我有一个解决你的赏金的方法。它真的适合我。

这是一个玩具示例,在@CollectionOfElements上使用次要弃用警告。 您可以通过将其替换为取代它的较新注释来克服它。

package com.wladimir.hibernate;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;

import org.hibernate.annotations.CollectionOfElements;

@Entity
public class A {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @CollectionOfElements
    @JoinTable
    private Map<String, B> bs = new HashMap<String, B>();

    public A() {
    }

    public Long getId() {
        return id;
    }

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

    public Map<String, B> getBs() {
        return bs;
    }

    public void setBs(Map<String, B> bs) {
        this.bs = bs;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "A [bs=" + bs + ", id=" + id + ", name=" + name + "]";
    }

}




package com.wladimir.hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
public class B {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @ManyToOne
    private C c;

    @ManyToOne
    private A a;

    public B() {
    }

    public Long getId() {
        return id;
    }

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

    public C getC() {
        return c;
    }

    public void setC(C c) {
        this.c = c;
    }

    public A getA() {
        return a;
    }

    public void setA(A a) {
        this.a = a;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "B [a=" + a.getName() + ", c=" + c.getName() + ", id=" + id
                + ", name=" + name + "]";
    }

}




package com.wladimir.hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class C {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    public C() {
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "C [id=" + id + ", name=" + name + "]";
    }
}


package examples.hibernate;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class PersistenceUtil {
    private static final SessionFactory sessionFactory;

    static {
        Log log = LogFactory.getLog(PersistenceUtil.class);

        try {
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (HibernateException ex) {
            // Make sure you log the exception, as it might be swallowed
            log.error("Initial SessionFactory creation failed.", ex);
            throw ex;
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}



package examples.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;

import com.wladimir.hibernate.A;
import com.wladimir.hibernate.B;
import com.wladimir.hibernate.C;

import java.util.List;

import examples.hibernate.domain.*;

public class Tester{
    private SessionFactory factory;

    public Tester(SessionFactory factory) {
        this.factory = factory;
    }

    @SuppressWarnings("unchecked")
    public void runABC(String operation) {
        Session session = factory.getCurrentSession(); // obtain/start unit of
        // work
        Transaction tx = null;
        try {
            tx = session.beginTransaction(); // start transaction

            if ("Create".equals(operation)) {
                A a = new A();
                a.setName("A " + System.nanoTime());

                C c = new C();
                c.setName("C " + System.nanoTime());
                session.save(c);


                B b = new B();
                b.setName("B " + System.nanoTime());

                b.setA(a);
                b.setC(c);

                a.getBs().put(b.getName(), b);

                session.save(b);

                B b2 = new B();
                b2.setName("B " + System.nanoTime());

                b.setA(a);
                b.setC(c);

                a.getBs().put(b.getName(), b);

                session.save(a);


            } else if ("Read".equals(operation)) {
                System.out.println("Reading data set.");
                List<A> as = (List<A>) session.createCriteria(A.class)
                        .addOrder(Order.asc("name")).list();
                for (A a : as) {
                    System.out.println(a);
                }
            }
            tx.commit(); // commit transaction & end unit of work

        } catch (RuntimeException ex) {
            if (tx != null)
                tx.rollback(); // abort transaction
            throw ex;
        }
    }


    // main application loop
    public static void main(String args[]) throws Exception {
        Tester app = new Tester(PersistenceUtil.getSessionFactory());

        String operation = null;
        if (args.length == 1) {
            operation = args[0];
        }

        app.runABC(operation);

    }
}

答案 2 :(得分:0)

如果这三个类都是实体,您可以尝试将其更改为Map&lt; String,C&gt; cs,从B关系中在C中放置一个反向字段,并将B-A关系改为C-A:


class A {
   // the map should have c.name as key
   @OneToMany
   private Map<String, C> cs;
   ...

   // This method is for getting the B for a key, like it was before.
   public B getB(String key) {
       return cs.get(key).getB();
   }
}

class B {

  private Long id;

  @OneToOne // Or perhaps @ManyToOne.
  private C c;
  ...
} 

class C {

  private Long id;
  private String name;

  @OneToOne(mappedBy="c") // Or perhaps maybe @OneToMany
  private B b;
  ...

  @ManyToOne(mappedby="cs")
  private A a;
} 

我假设这三个类是实体。如果C是Embeddable,那么我不知道该怎么做。