JPA不持久化对象J2EE

时间:2017-05-30 20:47:07

标签: java jpa

我有一个使用JEE5的遗留应用程序,我添加了一个类" People"并手动添加"#34;在数据库中有很多记录(人们只有peopleid和一个字符串peopledesc)

如果我使用方法getAllPeople(),我会正确填充列表,每个数据都在那里

但是当我尝试使用persistPeople(People pep)通过代码保留新记录时它只是什么都没有

system.out.println显示添加到对象的描述,以便将新创建的对象传递给方法,但它不会保留在数据库中:(

控制台输出中没有显示错误。

People.java

@Entity
public class People implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int idpeople;

    private String desc;

persistence.xml

<persistence-unit name="PersistenceUnit" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>entities.People</class>

...

PeopleDAOImPL.JAVA 

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import residencias.dominio.Renovacion;


@Stateless
public class PeopleDAOImpl implements PeopleDAO {


   //EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersistenceUnit");


    @PersistenceUnit(unitName="PersistenceUnit")
    private EntityManagerFactory emf;


    @Override
    public void persistPeople(People pep) {
        EntityManager em = emf.createEntityManager();

        System.out.println("description is  :"+pep.getDesc());
        em.persist(pep);


    }


    @Override
    public List<People> getAllPeople() {



        EntityManager em = emf.createEntityManager();
        List<People> results = new ArrayList();
        Query queryPrincipal;

        try {


            queryPrincipal = em.createQuery("SELECT p FROM People p");




            results = queryPrincipal.getResultList();

            return results;

        } catch (Exception e) {
            System.out.println(results.size());
            return results;

        } finally {
            if (em != null) {
                emf.close();
                em.close();
            }
        }

    }

1 个答案:

答案 0 :(得分:0)

在调用查询期间,您没有义务在事务中运行,当您尝试持久化/更新实体的状态时,您必须在事务边界内运行该特定操作。

在您的情况下,您可以使用以下配置:

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class PeopleDAOImpl implements PeopleDAO {

    @PersistenceUnit(unitName="PersistenceUnit")
    private EntityManagerFactory emf;

    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void persistPeople(People pep) {
        EntityManager em = emf.createEntityManager();

        System.out.println("description is  :"+pep.getDesc());
        em.persist(pep);


    }