У меня есть файлы конфигурации 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>
Я также добавил jar2 classpath jpa2.0 в файл конфигурации weblogic и создал источник данных с именем test-ds и именем jndi с именем test-ds через консоль администратора weblogic. Я собрал все методы операций с моделями в класс 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;
}
}
Я вызываю методы getMember и getMemberCount из базового компонента (объекта данных). Я комментировал класс modeloperations в компоненте поддержки. Чтобы использовать аннотацию @EJB, я развернул jsf2.war как библиотеку в weblogic. Заголовок управляемого компонента и LazyDataModel приведены ниже:
Заголовок бэк-бина:
@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)
Что вы думаете об этом исключении?
Спасибо.