weblogic(10.3.4)控制台中出现奇怪的hibernate错误

时间:2011-09-28 11:23:28

标签: hibernate jsf-2 ejb-3.0 primefaces weblogic-10.x

我有followgin配置文件,在获取Hibernate会话时遇到异常。 hibernate.cfg.xml中是否存在问题或缺少属性?

persistence.xml

<persistence version="2.0"
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_2_0.xsd">

<persistence-unit name="test" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>test-ds</jta-data-source>

 <properties>
    <property name="hibernate.jndi.url" value="t3://127.0.0.1:7001" />
    <property name="hibernate.connection.datasource" value="test-ds" />
    <property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.WeblogicTransactionManagerLookup" />
    <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
    <property name="hibernate.hbm2ddl.auto" value="update" />
    <property name="hibernate.current_session_context_class" value="jta" />
</properties>

<!-- For WebLogic AppSer. -->
<class>test.model.BaseEntity</class>
<class>test.model.InvoiceDetail</class>
<class>test.model.InvoiceMovement</class>
<class>test.model.InvoicePaymentItem</class>
<class>test.model.Job</class>
<class>test.model.Member</class>

</persistence-unit>


hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration>
<session-factory>
    <property name="hibernate.jndi.url">t3://127.0.0.1:7001</property>
    <property name="hibernate.connection.datasource">test-ds</property>
    <property name="hibernate.transaction.manager_lookup_class">org.hibernate.transaction.WeblogicTransactionManagerLookup</property>
    <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="hibernate.current_session_context_class">jta</property>

    <mapping class="test.model.BaseEntity" />
    <mapping class="test.model.InvoiceDetail" />
    <mapping class="test.model.InvoiceMovement" />
    <mapping class="test.model.InvoicePaymentItem" />
    <mapping class="test.model.Job" />
    <mapping class="test.model.Member" />
</session-factory>

我还在weblogic配置文件中添加了类路径jpa2.0 jars,并通过weblogic管理控制台创建了名为test-ds的数据源和名为test-ds的jndi名称。我将所有模型操作方法组装到了ModelOperations类中。该类的标题如下:

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class ModelOperations implements ModelOperationsLocal {

    @PersistenceContext(unitName = "beyazfatura")
    private EntityManager em;  
...  

在本课程中,我有一个方法如下:

@Override
@SuppressWarnings("unchecked")
public List<Member> getMembers(int first, int pageSize, String sortField,
        String sortOrder, Map<String, String> filters, Date beginDate,
        Date endDate) {
    Session session = null;
    List<Member> memberList = null;
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        Criteria crit = session.createCriteria(Member.class);

        Criterion betweenDate = null;
        if (beginDate != null) {
            if (endDate == null) {
                endDate = new Date();// now
            }
            betweenDate = Restrictions.between("createTime", beginDate,
                    endDate);
        }

        if (betweenDate != null) {
            crit.add(betweenDate);
        }

       // sorting
        if (sortField != null && !sortField.isEmpty()) {
            if (!sortOrder.equalsIgnoreCase("UNSORTED")) {
                if (sortOrder.equalsIgnoreCase("ASCENDING")) {
                    crit = crit.addOrder(Order.asc(sortField));
                } else {
                    crit = crit.addOrder(Order.desc(sortField));
                }
            }
        }

        // filtering
        if (filters != null && !filters.isEmpty()) {
            Iterator<Entry<String, String>> iterator = filters.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> entry = iterator.next();
                Class<?> type = Member.class.getDeclaredField(
                        entry.getKey()).getType();
                try {
                    if (type.isEnum()
                            || Number.class.isAssignableFrom(type)) {
                        crit = crit.add(Restrictions.eq(
                                entry.getKey(),
                                type.getDeclaredMethod("valueOf",
                                String.class).invoke(null,
                                entry.getValue())));
                    } else {
                        crit = crit.add(Restrictions.like(entry.getKey(),
                                entry.getValue(), MatchMode.START));
                    }
                } catch (Exception ex) {
                    // Aim: return the list anyway.
                    LOG.warn(ex, ex);
                }
            }
        }

        if (first != -1) {
            crit = crit.setFirstResult(first);
        }

        if (pageSize != -1) {
            crit = crit.setMaxResults(pageSize);
        }

        memberList = crit.list();
    } catch (Exception e) {
        LOG.error(e, e);
    } finally {
        session.close();
    }

    return memberList;
}

@Override
public Long getMemberCount(Date beginDate, Date endDate) {
    Session session = null;
    Long returnValue = 0L;
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        Criteria crit = session.createCriteria(Member.class);

        Criterion betweenDate = null;
        if (beginDate != null) {
            if (endDate == null) {
                endDate = new Date();// now
            }
            betweenDate = Restrictions.between("createTime", beginDate,
                    endDate);
        }

        if (betweenDate != null) {
            crit.add(betweenDate);
        }

        crit.setProjection(Projections.rowCount());
        if(crit.list() != null){
            returnValue = (Long) crit.list().get(0);
        } else {
            returnValue = 0L;
        }
    } catch (Exception e) {
        LOG.error(e, e);
    } finally {
        session.close();
    }
    return returnValue;
}

这是HibernateUtil类:

public class HibernateUtil {

    private static final Logger LOG = Logger.getLogger(HibernateUtil.class);
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable e) {
            LOG.error(e, e);
            throw new ExceptionInInitializerError(e);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}  

我从一个支持bean(数据表)调用getMember和getMemberCount方法。我在backing-bean中注释了modeloperations类。为了使用@EJB注释,我将jsf2.war部署为weblogic中的libray。托管bean和LazyDataModel的标题如下:

Backing-bean标题:

@ManagedBean(name = "memberManagement")
@SessionScoped
public class MemberManagement {

    @EJB
    private ModelOperationsLocal modelOperations;
    private static final Logger LOG = Logger.getLogger(MemberManagement.class);
    private MemberLazyDataModel memberModel;  

    @PostConstruct
    public void initModel() {
        memberModel = new MemberLazyDataModel(pageSize, beginDate, endDate,
            modelOperations);
    }

LazyDataModel

public class MemberLazyDataModel extends LazyDataModel<Member> {

    private ModelOperationsLocal modelOperations;
    private static final Logger LOG = Logger.getLogger(MemberLazyDataModel.class);
    private int pageSize;
    private Date beginDate;
    private Date endDate;

    public MemberLazyDataModel() {
    }

    public MemberLazyDataModel(int pageSize, Date beginDate, Date endDate,
        ModelOperationsLocal modelOperations) {
        this.pageSize = pageSize;
        this.beginDate = beginDate;
        this.endDate = endDate;
        this.modelOperations = modelOperations;
        super.setPageSize(pageSize);
        super.setRowCount(modelOperations.getMemberCount(beginDate, endDate).intValue());
    }

    @Override
    public List<Member> load(int first, int pageSize, String sortField,
        SortOrder sortOrder, Map<String, String> filters) {
        super.setRowCount(modelOperations.getMemberCount(beginDate, endDate).intValue());
        return modelOperations.getMembers(first, pageSize, sortField,
            sortOrder.name(), filters, beginDate, endDate);
    }

    @Override
    public String getRowKey(Member member) {
        return member.getId() + "";
    }

    @Override
    public Member getRowData(String rowKey) {

        List<Member> members = (List<Member>) getWrappedData();

        for (Member member : members) {
            if ((member.getId() + "").equals(rowKey)) {
                return member;
            }
        }

        return null;
    }
}  

当我单击包含成员数据表的页面时,我得到以下异常(就好像它第一次获取hibernate.cfg.xml一样???):

INFO  Configuration                   - configuring from resource: /hibernate.cfg.xml
INFO  Configuration                   - Configuration resource: /hibernate.cfg.xml
INFO  Configuration                   - Configured SessionFactory: null  

一些表绑定日志然后是下面的日志和异常:

INFO  TransactionFactoryFactory       - Using default transaction strategy (direct JDBC transactions)
INFO  ransactionManagerLookupFactory  - instantiating TransactionManagerLookup: org.hibernate.transaction.WeblogicTransactionManagerLookup
INFO  ransactionManagerLookupFactory  - instantiated TransactionManagerLookup
INFO  SettingsFactory                 - Automatic flush during beforeCompletion(): disabled
INFO  SettingsFactory                 - Automatic session close at end of transaction: disabled
INFO  SettingsFactory                 - JDBC batch size: 15
INFO  SettingsFactory                 - JDBC batch updates for versioned data: disabled
INFO  SettingsFactory                 - Scrollable result sets: enabled
INFO  SettingsFactory                 - JDBC3 getGeneratedKeys(): enabled
INFO  SettingsFactory                 - Connection release mode: auto
INFO  SettingsFactory                 - Default batch fetch size: 1
INFO  SettingsFactory                 - Generate SQL with comments: disabled
INFO  SettingsFactory                 - Order SQL updates by primary key: disabled
INFO  SettingsFactory                 - Order SQL inserts for batching: disabled
INFO  SettingsFactory                 - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
INFO  ASTQueryTranslatorFactory       - Using ASTQueryTranslatorFactory
INFO  SettingsFactory                 - Query language substitutions: {}
INFO  SettingsFactory                 - JPA-QL strict compliance: disabled
INFO  SettingsFactory                 - Second-level cache: enabled
INFO  SettingsFactory                 - Query cache: disabled
INFO  SettingsFactory                 - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
INFO  SettingsFactory                 - Optimize cache for minimal puts: disabled
INFO  SettingsFactory                 - Structured second-level cache entries: disabled
INFO  SettingsFactory                 - Statistics: disabled
INFO  SettingsFactory                 - Deleted entity synthetic identifier rollback: disabled
INFO  SettingsFactory                 - Default entity-mode: pojo
INFO  SettingsFactory                 - Named query checking : enabled
INFO  SettingsFactory                 - Check Nullability in Core (should be disabled when Bean Validation is on): disabled
INFO  SessionFactoryImpl              - building session factory
INFO  BasicTypeRegistry               - Type registration [materialized_blob] overrides previous : org.hibernate.type.MaterializedBlobType@1a11d34
INFO  SessionFactoryObjectFactory     - Not binding factory to JNDI, no JNDI name configured
INFO  SchemaUpdate                    - Running hbm2ddl schema update
INFO  SchemaUpdate                    - fetching database metadata
ERROR SchemaUpdate                    - could not get database metadata
java.sql.SQLException: Cannot set auto commit to "true" when in distributed transaction.
        at weblogic.jdbc.wrapper.JTSConnection.setAutoCommit(JTSConnection.java:625)
        at org.hibernate.tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.prepare(SuppliedConnectionProviderConnectionHelper.java:60)
        at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:168)
        at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:375)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1872)  

您对此例外的看法是什么? 感谢。

1 个答案:

答案 0 :(得分:0)

我认为线索在

INFO  SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured

来自休眠docs

  

3.8.2。 JNDI绑定的SessionFactory

     

JNDI绑定的Hibernate SessionFactory可以简化查找功能   工厂和创建新的会话。然而,这不是相关的   到JNDI绑定的Datasource;两者都只使用相同的注册表。

     

如果您希望将SessionFactory绑定到JNDI名称空间,   使用属性指定名称(例如java:hibernate / SessionFactory)   hibernate.session_factory_name。如果省略此属性,则   SessionFactory不会绑定到JNDI。这在特别有用   具有只读JNDI默认实现的环境(在Tomcat中,   例如)。

因此,您需要在hibernate配置中提供hibernate.session_factory_name