ejb3.0 数据源配制

 1.       首先在JBOSS的\server\default\deploy目录下建立XML文档,此文档的名称一般根据所使用的数据库而定,如mysql的为mysql-ds.xml ,db2的为db2-ds.xml。
 
       文档的内容一般如下:
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
  <local-tx-datasource>
      <jndi-name>DB2SAMPLE</jndi-name>
      <connection-url>jdbc:db2://127.0.0.1:50000/sample</connection-url>
      <driver-class>com.ibm.db2.jcc.DB2Driver</driver-class>
      <user-name>db2admin</user-name>
      <password>db2admin</password>
      <min-pool-size>0</min-pool-size>
        <metadata>
           <type-mapping>DB2</type-mapping>
        </metadata>
  </local-tx-datasource>
</datasources>
 
文档中配制了1个数据源,相信每项代表的意思都已经很清楚了。
 
 2.        在项目中的src/META-INF/下建立persistence.xml文档,
<?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="db2sample" transaction-type="JTA">
 //这就是我们在db2-ds.xml中建立的数据源名称
  <jta-data-source>java:/DB2SAMPLE</jta-data-source> 
//下面是一些属性设置
 <properties>
   <!--property name="hibernate.hbm2ddl.auto" value="create-drop"/-->
   <property name="hibernate.jdbc.fetch_size" value="20"/>
   <property name="hibernate.show_sql" value="true" />
   <property name="hibernate.format_sql" value="true"/>
   <property name="hibernate.dialect"
    value="org.hibernate.dialect.DB2Dialect" />
  </properties>
 </persistence-unit>
</persistence>
 
3.在程序中引用数据
package yr.ejb.c;
import java.util.List;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
@Stateless
@Remote(TeacherDao.class)
public class TeacherDaoBean implements TeacherDao {
 @PersistenceContext(name="db2sample")
 EntityManager em;
 @TransactionAttribute(TransactionAttributeType.REQUIRED)
 public void add(Teacher teacher) {
  System.out.println("开始执行方法");
  
   System.out.println("开始向数据库插入数据");
    em.persist(teacher);
   @SuppressWarnings("unused")
   int a = 5 / 0;
   System.out.println("向数据库插入数据完成");
  
 }
 public Teacher get(int teacherId) {
   Teacher teacher = em.find(Teacher.class, teacherId);
  teacher.getPersons().size();
  return teacher;
 }
 @SuppressWarnings("unchecked")
 public List<Teacher> getAllTeacher() {
  Query query = em
    .createQuery("select distinct t from Teacher t inner join fetch t.persons order by t.id");
  return (List<Teacher>) query.getResultList();
 }
}

你可能感兴趣的:(职场,数据源,休闲,配制)