Hibernate - 如何使用整数列表?

时间:2018-04-22 16:03:53

标签: java hibernate

我有一个类型为List<Integer>的字段的实体,我在使用hibernate保存和加载时遇到了问题。

我发现了@ElementCollection(例如here),但我无法让它发挥作用。

这是我的实体:

@Entity
public class TestEntity {
    @Id
    private String id;
    @ElementCollection
    private List<Integer> integers;

    public TestEntity() {

    }

    public TestEntity(String id, List<Integer> integers) {
        this.id = id;
        this.integers = integers;
    }

    public String getId() {
        return id;
    }

    public List<Integer> getIntegers() {
        return integers;
    }
}

这是我的主要课程:

public class Main {
    public static void main(String[] args) {
        try (SessionFactory sessionFactory = createSessionFactory()) {
            try (Session session = sessionFactory.openSession()) {
                TestEntity entity = new TestEntity("id", Arrays.asList(1, 2, 3));
                session.persist(entity);
            }

            try (Session session = sessionFactory.openSession()) {
                TestEntity entity = (TestEntity) session.byId(TestEntity.class.getName()).load("id");
                System.out.println(entity.getIntegers().size());
            }
        }
    }

    private static SessionFactory createSessionFactory() {
        StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure()
                .build();

        return new MetadataSources(registry)
                .addAnnotatedClass(TestEntity.class)
                .buildMetadata()
                .buildSessionFactory();
    }
}

此代码因NullPointerException而失败,因为整数列表为null。我错过了什么?

2 个答案:

答案 0 :(得分:1)

private List<Integer> integers;
public void setIntegers(List<Integer> integers) {
         this.integers = integers; }

使用setter方法会有所帮助

  • 您收到 NullPointerException ,因为列表为空
  • 这可以通过使用setter
  • 来解决

答案 1 :(得分:0)

愚蠢的我,我在编写TestEntity时忘了打开一个交易:(

现在代码有效:

public static void main(String[] args) {
    try (SessionFactory sessionFactory = createSessionFactory()) {
        try (Session session = sessionFactory.openSession()) {
            Transaction transaction = session.beginTransaction();
            TestEntity entity = new TestEntity("id", Arrays.asList(1, 2, 3));
            session.persist(entity);
            transaction.commit();
        }

        try (Session session = sessionFactory.openSession()) {
            TestEntity entity = session.get(TestEntity.class, "id");
            System.out.println(entity.getIntegers().size());
        }
    }
}