简体   繁体   中英

JPA persist not writing to database

I'm just trying to get to know JSF and JPA but whenever I try to persist an object into the database it seems to not write away. Here's the code I'm using:

@Named
@ManagedBean
@SessionScoped
public class BestemmingController implements Serializable{

@PersistenceUnit(unitName="RealDolmenTravelShopPU")
@PersistenceContext(unitName="RealDolmenTravelShopPU")

EntityManagerFactory emf = null;
public void submit(){


        try{
            emf = Persistence.createEntityManagerFactory("RealDolmenTravelShopPU");

            EntityManager em = emf.createEntityManager();

            //EntityTransaction et = em.getTransaction();
            //et.begin();

            Bestemming nieuweBestemming = new Bestemming();

            Land gezochtLand = em.find(Land.class, selectedLand);

            nieuweBestemming.setLand(gezochtLand);
            nieuweBestemming.setNaam(bestemmingNaam);

            em.persist(nieuweBestemming);

            //et.commit();
            //em.flush();
            em.close();
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            emf.close();
        }
    }

I tried using the EntityTransaction but it just stopped my application, without any errors or anything. So I left it out, but still it didn't write away. So then I tried calling flush seperately, but that didn't do anything either. I'm really stumped as to why this isn't working. It's probably some newbie mistake, but I would love it if someone here could help me out.

Thanks in advance!

First, are you able to write to the logs? Starting a transaction when specifying the persistence unit uses JTA will throw an exception, so it is likely you have just been missing exceptions in your container log files.

Second, this is a JTA PU, so it needs a JTA transaction started that the EM gets associated to, and you will want to inject the em rather than create a factory yourself. Check out the JPA application server examples here first to see how they are set up: http://wiki.eclipse.org/EclipseLink/Examples/JPA

Hey I found out why it was that the transaction wasn't running: the implementation I used didn't use JTA, it used a RESOURCE_LOCAL persistence unit. That was something I just looked over when I set up my project.

Good thing my buddy told me to check the server logs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM