2014-09-28 2 views
0

Я использую Hibernate 4 с базой данных Postgresql. Выбор запросов выполняется хорошо, но когда дело доходит до обновления запросов (Вставка), не работает вообще.Hibernate совершает, но не сохраняет

В журналах ничего не говорится об ошибках, все кажется одобренным и совершенным. Пытаюсь сохранить объект, используя Dao слой:

public void add(Role role) { 
    sessionFactory.openSession().save(role); 
} 

Сервис слой:

@Transactional 
public void addNewRole(Role role) { 
    roleDao.add(role);  

} 

объект Роль отображается, SessionFactory вводится без каких-либо проблем. А вот что говорит журналы:

2014-09-28 10:44:52 DEBUG HibernateTransactionManager:367 - Creating new transaction with name [com.x.y.base.services.imp.RoleServiceImp.addNewRole]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; '' 
2014-09-28 10:44:52 DEBUG HibernateTransactionManager:420 - Opened new Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[[email protected] [email protected] [email protected] [email protected] [email protected]580 [email protected]b34 [email protected]0e [email protected]efd8 unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] for Hibernate transaction 
2014-09-28 10:44:52 DEBUG HibernateTransactionManager:430 - Preparing JDBC Connection of Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[[email protected] [email protected] [email protected] [email protected] [email protected]580 [email protected]b34 [email protected]0e [email protected]efd8 unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] 
2014-09-28 10:44:52 DEBUG DriverManagerDataSource:142 - Creating new JDBC DriverManager Connection to [jdbc:postgresql://localhost:5432/moe] 
2014-09-28 10:44:52 DEBUG HibernateTransactionManager:491 - Exposing Hibernate transaction as JDBC transaction [[email protected]] 
2014-09-28 10:44:52 DEBUG HibernateTransactionManager:755 - Initiating transaction commit 
2014-09-28 10:44:52 DEBUG HibernateTransactionManager:554 - Committing Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[[email protected] [email protected] [email protected] [email protected] [email protected]580 [email protected]b34 [email protected]0e [email protected]efd8 unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] 
2014-09-28 10:44:52 DEBUG HibernateTransactionManager:636 - Closing Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[[email protected] [email protected] [email protected] [email protected] [email protected]580 [email protected]b34 [email protected]0e [email protected]efd8 unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] after transaction 

весна-db.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:aop="http://www.springframework.org/schema/aop" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:tx="http://www.springframework.org/schema/tx" 
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 


<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="location"> 
     <value>classpath:properties/db.properties</value> 
    </property> 
</bean> 

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
    <property name="driverClassName" value="${db.driverClassName}" /> 
    <property name="url" value="${db.url}" /> 
    <property name="username" value="${db.username}" /> 
    <property name="password" value="${db.password}" /> 
</bean> 

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
    <property name="dataSource" ref="dataSource" /> 
    <property name="mappingResources"> 
     <list> 
      <value>mapping/User.hbm.xml</value> 
      <value>mapping/Role.hbm.xml</value> 
      <value>mapping/Permission.hbm.xml</value> 
      <value>mapping/Representation.hbm.xml</value> 
      <value>mapping/Right.hbm.xml</value> 
     </list> 
    </property> 
    <property name="hibernateProperties"> 
     <props> 
      <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop> 
      <prop key="hibernate.show_sql">true</prop> 
      <prop key="hibernate.connection.autocommit">true</prop> 
      <prop key="hibernate.format_sql">true</prop> 
      <prop key="hibernate.use_sql_comments">true</prop> 
      <prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop> 
     </props> 
    </property> 
</bean> 

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
    <property name="sessionFactory" ref="sessionFactory" /> 
</bean> 

Тест приложение:

public static void main(String[] args) { 

    ApplicationContext cx = new ClassPathXmlApplicationContext("spring/spring-all.xml"); 
    RoleService roleService = (RoleService) cx.getBean("roleService"); 

    Role role = new Role(); 
    role.setCode("TEST"); 
    role.setName("Test"); 
    role.setDescription("Test Role"); 

    roleService.addNewRole(role); 

} 

объект не сохраняется в физическом база данных вообще? Я проверил привилегии пользователя базы данных, но, похоже, имеет полный супер-доступ ко всем операциям!

В чем может быть причина?

+0

Если вы попытаетесь запустить подобную вставку без спящего режима, это сработает? Вы уважаете все не нулевые, внешние ключи и т. Д. Ограничения? –

+0

Обычная вставка работает, все поля отправляются, обычная таблица без ограничений, кроме первичного ключа! – Hatem

+0

Можете ли вы проверить свою команду hibernate с добавлением значения к первичному ключу? Я не впадаю в спячку, я просто даю некоторые общие идеи. –

ответ

3

Вы открываете новый сеанс, не связанный с текущей транзакцией Spring, в вашем DAO. Не делай этого. Вместо этого получите текущую сессию, связанную с текущей транзакцией:

Session session = sessionfactory.getCurrentSession(); 
+0

Большое спасибо, это правильный ответ, вы спасаете мой день! – Hatem

Смежные вопросы