【问题标题】:Using Entitymanager inside Enumeration in entity class在实体类的枚举中使用 Entitymanager
【发布时间】:2012-04-20 09:02:50
【问题描述】:

我有以下问题。也许设计不是那么好,但我想不出更好的。

我有一个实体类Device.java

@Entity (name = "device")
public class Device {

public enum DeviceType {
    STROM,
    LICHT,
    TEMPERATUR,
    LUFTFEUCHTIGKEIT,
    BEWEGUNG,
    DIMMEN
};

public static enum HomematicAttribute {
    STATE,
    TEMPERATURE,
    HUMIDITY,
    LOWBATTERY,
    MOVEMENT,
    LEVEL
}

@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private Integer id;

    // Some other fields and getter and setter

我在那个类/实体中有这个枚举

public static enum HomematicDeviceName {
    LICHT_FRONT("HM_DEVICE_LICHT_FRONT", DeviceType.DIMMEN, HomematicAttribute.LEVEL), 
    LICHT_GANG("HM_DEVICE_LICHT_GANG", DeviceType.DIMMEN, HomematicAttribute.LEVEL), 
    ...

    // constructor and getters

    @PersistenceContext
    EntityManager em;

    @EJB
    private DatabaseServiceLocal databaseService;

    public Device getDevice() {
        if(em == null) System.out.println("Entitymanager ist null innerhalb der Enumeration ...");
        if(databaseService == null) System.out.println("databaseService ist null innerhalb der Enumeration ...");

        System.out.println("----");
        return (Device) em.createNamedQuery(Device.findByIdentifier).setParameter("identifier", databaseKey).getSingleResult();
    }
}

em 和 databaseService 都为空。目标是从枚举和其他方式中获取实体。我不想与实体合作。相反,我想使用枚举,但有时我需要实体。所以我想我可以做这样的事情来从我的枚举中获取设备实体。

有人有想法吗?

谢谢, 豪克

【问题讨论】:

    标签: java annotations ejb entity enumeration


    【解决方案1】:

    依赖注入仅支持由容器创建的对象,例如 EJB。这是依赖框架(包括 Spring 和 Google Guice)的通常工作方式。

    您可以将服务(当前未使用?)或 EntityManager 作为参数传递。

    【讨论】:

    • 依赖注入在枚举中也很好。但是将它传递给方法的想法并没有那么糟糕。不是很好,但至少应该可以。谢谢!!
    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    相关资源
    最近更新 更多