Транзакция хранилища Deltaspike фиксируется, но в БД в Java SE ничего не сохраняется - PullRequest
0 голосов
/ 14 декабря 2018

Я использую репозитории DeltaSpike для сохранения сущности в Java SE, и я использую файловую базу данных H2.Проблема в том, что, хотя в консоли нет ошибок, в базе данных ничего не сохраняется.Я проверил содержимое базы данных с помощью автономного клиента.Я также пытался получить содержимое с помощью репозитория сразу после завершения сохранения, но не получил никакого результата.

Когда я пытаюсь сохранить его напрямую с помощью диспетчера сущностей (чистый JPA), он сохраняется, и я вижузапись при открытии файла в клиенте с графическим интерфейсом.

Структура проекта выглядит следующим образом:

enter image description here

Вот зависимости в pom.xml:

<dependencies>
    <dependency>
        <groupId>org.hibernate.common</groupId>
        <artifactId>hibernate-commons-annotations</artifactId>
        <version>5.0.4.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.1-api</artifactId>
        <version>1.0.2.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.3.6.Final</version>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.4.197</version>
    </dependency>
    <dependency>
        <groupId>org.apache.deltaspike.core</groupId>
        <artifactId>deltaspike-core-api</artifactId>
        <version>1.9.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.deltaspike.modules</groupId>
        <artifactId>deltaspike-jpa-module-api</artifactId>
        <version>1.9.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.deltaspike.modules</groupId>
        <artifactId>deltaspike-jpa-module-impl</artifactId>
        <version>1.9.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.deltaspike.core</groupId>
        <artifactId>deltaspike-core-impl</artifactId>
        <version>1.9.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.deltaspike.modules</groupId>
        <artifactId>deltaspike-data-module-api</artifactId>
        <version>1.9.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.deltaspike.modules</groupId>
        <artifactId>deltaspike-data-module-impl</artifactId>
        <version>1.9.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.deltaspike.cdictrl</groupId>
        <artifactId>deltaspike-cdictrl-api</artifactId>
        <version>1.9.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.deltaspike.cdictrl</groupId>
        <artifactId>deltaspike-cdictrl-weld</artifactId>
        <version>1.9.0</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.weld.se</groupId>
        <artifactId>weld-se-core</artifactId>
        <version>3.0.5.Final</version>
    </dependency>
</dependencies>

Файл persistence.xml имеет вид:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="sample-unit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>com.one.ehsan.test.deltaspike.domain.Person</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:h2:file:./data/test-h2-db"/>
            <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
            <!-- Hibernate properties -->
            <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.use_sql_comments" value="true"/>
            <property name="hibernate.show_sql" value="true"/>
        </properties>
    </persistence-unit>
</persistence>

Класс производителя для менеджера сущностей:

@ApplicationScoped
public class PersistenceProducer
{
    @Inject
    @PersistenceUnitName("sample-unit")
    private EntityManagerFactory entityManagerFactory;

    @Produces
    public EntityManager getEntityManager() {
        return entityManagerFactory.createEntityManager();
    }

    public void closeEntityManager(@Disposes EntityManager entityManager)
    {
        if (entityManager.isOpen())
        {
            entityManager.close();
        }
   }
}

Класс сущности:

@Entity
public class Person
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column
    private String firstName;

    @Column
    private String lastName;

    @Temporal(TemporalType.TIMESTAMP)
    @Column
    private Date createDate;

    // ... getter/setters omitted
}

Класс хранилища:

@Transactional
@Repository(forEntity = Person.class)
public abstract class PersonRepository extends AbstractEntityRepository<Person, Long>
{
    @Inject
    private EntityManager entityManager;
}

Служебный компонент, вызывающий хранилище:

public class PersonService
{
    @Inject
    private EntityManager entityManager;

    @Inject
    private PersonRepository personRepository;

    public Person save(Person person) {

        // I tried removing begin/commit and nothing changed
        entityManager.getTransaction().begin();
        Person result = personRepository.save(person);
        entityManager.getTransaction().commit();
        return result;
    }
}

Основной класс приложения:

public class Main
{
    private CdiContainer cdiContainer;

    public static void main(String[] args)
    {
        Main main = new Main();
        main.run();
    }

    public void run() {

        cdiContainer = CdiContainerLoader.getCdiContainer();
        cdiContainer.boot();

        persistPerson();

        cdiContainer.shutdown();
    }


    private void persistPerson()
    {
        PersonService personService = (PersonService) getBean(PersonService.class);

        Person person = new Person();
        person.setFirstName("Foo");
        person.setLastName("Bar");
        person.setCreateDate(new Date());

        personService.save(person);

    }

    private Object getBean(Class type)
    {
        BeanManager beanManager = cdiContainer.getBeanManager();
        Set<Bean<?>> personServiceBean = beanManager.getBeans(type);
        Bean<?> bean = beanManager.resolve(personServiceBean);
        CreationalContext<?> context = beanManager.createCreationalContext(bean);
        return beanManager.getReference(bean, type, context);
    }
}

Кто-нибудь знает, что могло быть упущено (возможно) в конфигурации DeltaSpike?Или это ожидаемое поведение в такой конфигурации?

...