EntityManager的注入

来源:互联网 发布:ubuntu tty 中文乱码 编辑:程序博客网 时间:2024/04/29 05:49

 第一步:服务器数据源发布 

第二步:持久化单元配置

persistence.xml   放置到jar包的META-INF

 

<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="http://java.sun.com/xml/ns/persistence"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/persistence 

http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">

<persistence-unit name="my_u" transaction-type="JTA">

   <jta-data-source>java:MySqlDS</jta-data-source>

   <properties>

    <property name="hibernate.hbm2ddl.auto" value="update" />

    <property name="hibernate.show_sql" value="true" />

    <property name="hibernate.format_sql" value="true" />

   </properties>

</persistence-unit>

</persistence>

ANT

build.xml

 

<?xml version="1.0"?> 

<project name="EJB_JTA" default="ejbjar" basedir="."> 

<property environment="env" /> 

<property name="src.dir" value="${basedir}/src" /> 

<property name="jboss.home" value="${env.JBOSS_HOME}" /> 

<property name="jboss.server.config" value="default" /> 

<property name="build.dir" value="${basedir}/build" />  

<!-- Build classpath --> 

<path id="build.classpath"> 

   <fileset dir="${jboss.home}/client"> 

    <include name="*.jar" /> 

   </fileset> 

   <pathelement location="${build.dir}" /> 

</path>

<target name="undeploy" description="卸载EJB"> 

<delete file="${jboss.home}/server/${jboss.server.config}/deploy/${ant.project.name}.jar"/> 

</target>

<target name="prepare" depends="undeploy"> 

<delete dir="${build.dir}"/> 

<mkdir dir="${build.dir}" /> 

</target> 

<target name="compile" depends="prepare" description="编绎"> 

   <javac srcdir="${src.dir}" destdir="${build.dir}"> 

    <classpath refid="build.classpath" /> 

   </javac> 

<!-- -->

<copy file="${src.dir}/META-INF/persistence.xml" todir="${build.dir}/META-INF"/>

</target> 

<target name="ejbjar" depends="compile" description="创建EJB发布包"> 

   <jar jarfile="${basedir}/${ant.project.name}.jar" basedir="${build.dir}"> 

    <fileset dir="build"> 

     <include name="*"/> 

    </fileset> 

   </jar> 

</target> 

<target name="deploy" depends="ejbjar" description="发布EJB"> 

   <copy file="${basedir}/${ant.project.name}.jar" todir="${jboss.home}/server/${jboss.server.config}/deploy" /> 

</target> 

</project> 

 

 

第三步:注入EntityManager  (不是线程安全的)

 

@PersistenceContext(unitName="my_u")           //推荐的方式,EJB容器负责EntityManager 的生命周期

protected EntityManager entityManager;

 

@PersistenceUnit(unitName="my_u")

protected EntityManagerFactory entityManagerFactory ;

@PostConstruct

EntityManager entityManager=entityManagerFactory .createEntityManager();

@PreDestroy

entityManager.close();

原创粉丝点击