package com.hohai.juncao;

import java.io.Serializable;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.Init;
import javax.ejb.LocalHome;
import javax.ejb.PostActivate;
import javax.ejb.PrePassivate;
import javax.ejb.Remove;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;

@LocalHome(SendingSessionStdHome.class)
@TransactionManagement(TransactionManagementType.BEAN)
public class SendingSessionStdBean implements Serializable {

	private static final long serialVersionUID = 1L;
	
	@PersistenceContext
	EntityManager em;
	
	@Resource
	private UserTransaction userTransaction;
	
	@Init
    public void create() {
		System.out.println("Bean instance created!");
    }
	
	public void createEntity(){
		try {
		TranEntityStd data = new TranEntityStd();
		userTransaction.begin();
		data.setId(1);
		data.setName("Previous Data");
		em.persist(data);
		userTransaction.commit();
		} catch (Exception e){			
		}
	}
	
	public TranEntityStd updateEntityWithSleep(String name) {
	
		TranEntityStd data = null;
		try {
		data = em.find(TranEntityStd.class, 1);
		userTransaction.begin();
		data.setName(name);
		} catch (Exception e){		
			e.printStackTrace();
		}
		return data;
	}

	public void mergeEntity(TranEntityStd data) {
		try {
		em.merge(data);
		userTransaction.commit();
		System.out.println("About to sleep...");
		} catch (Exception e){		
			e.printStackTrace();
		}
	}
	
	public TranEntityStd getEntity() {
	
		TranEntityStd data = null;
		data = em.find(TranEntityStd.class, 1);
		return data;
	}

	@PrePassivate
	public void passivate(){
		System.out.println("Idle bean just got passivated!");
	}
	
	@PostActivate
	public void reactivate(){
		System.out.println("Idle bean just got activated again!");
	}
	
	@Remove
	public void removeBean(){
		System.out.println("Idle bean just got removed!");
	}
	
	@PreDestroy
	public void destroy(){
		System.out.println("Idle bean just got destroyed!");
	}
}