hibernate SaveOrUpdate:如何使用

时间:2015-11-28 12:47:07

标签: java hibernate

想知道如何使用SaveOrUpdate,希望在特定列信息相同时插入数据并再次更新数据。

我创建了Abrstract类,抽象(AbstractDao)类在Dao中扩展并在服务类中使用。

  

当我使用beginTransactioncommitSaveOrUpdate我收到错误   “不支持嵌套交易”

Exception in thread "Thread-2" org.hibernate.TransactionException: nested transactions not supported
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:154)
    at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1435)
    at com.my.myProj.mdao.AbstractDao.SaveOrUpdate(AbstractDao.java:26)
    at com.my.myProj.mdao.UniqueDataDaoImpl.saveOrUpdateUniqueData(UniqueDataDaoImpl.java:25)
    at com.my.myProj.service.UniqueDataServiceImpl.saveOrUpdateUniqueData(UniqueDataServiceImpl.java:55)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy33.saveOrUpdateUniqueData(Unknown Source)
    at com.my.myProj.mainapp.savedb.StoreIdentityDataPacketDB.saveIdentityData(StoreDataDB.java:126)

    at com.my.myProj.mainapp.MainApp.run(MainApp.java:359)

我从网上复制了AppConfigHibernateConfiguration。我不确定是否在配置中启用了事务。我想知道以下

  • 如何使用SaveOrUpdate:在新的时候插入,在表格中已经更新
  • 倾斜/理解用于hibernate配置和app类配置的java配置的提示

谢谢!

public abstract class AbstractDao {

    @Autowired
    private SessionFactory sessionFactory;

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    public void persist(Object entity) {
        getSession().persist(entity);
    }

    public void delete(Object entity) {
        getSession().delete(entity);
    }

    public void SaveOrUpdate(Object entity) {
        Transaction tx3 = getSession().beginTransaction();
        getSession().saveOrUpdate(entity);
        tx3.commit();
    }
}

hibernate配置文件

@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.my.testProj.configuration" })
@PropertySource(value = { "classpath:hibernate.properties" })
public class HibernateConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.my.testProj.model" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
     }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        return properties;        
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
       HibernateTransactionManager txManager = new HibernateTransactionManager();
       txManager.setSessionFactory(s);
       return txManager;
    }
}

Dao实施

@Repository("UniqueDataDao")
public class UniqueDataDaoImpl extends AbstractDao implements UniqueDataDao {    

    @Override
    public void saveUniqueData(UniqueData UniqData) {           
        persist(UniqData);    
    }

    @Override
    public void saveOrUpdateUniqueData(UniqueData UniqData) {           
        SaveOrUpdate(UniqData);    
    }    

    @SuppressWarnings("unchecked")
    @Override
    public  List<UniqueData> SelectUniqueTable(String sNum,String sSerNum) {
        // TODO Auto-generated method stub
        Query query = getSession().createQuery("from UniqueData where S_NUMBER = :sModNum and S_SERIAL_NO = :sSerialNum");
        query.setParameter("sModNum", sNum);
        query.setParameter("sSerialNum", sSerNum);
        return query.list();
    }   

}

服务实施

@Service("UniqueService")
@Transactional
public class UniqueDataServiceImpl  implements UniqueDataService {

    @Autowired
    private UniqueDataDao UniqueDao;

    @Override
    public void saveUniqueData(UniqueData UniqData) {       
        UniqueDao.saveUniqueData(UniqData);    
    }

    @Override
    public List<UniqueData> SelectUniqueTable(String sNum, String sSerNum) {        
        return UniqueDao.SelectUniqueTable(sNum, sSerNum);
    }

    @Override
    public List<UniqueData> SelectUniqueTable(String sImeiNum) {        
        return UniqueDao.SelectUniqueTable(sImeiNum);
    }    

    @Override
    public void saveOrUpdateUniqueData(UniqueData UniqData) {           
        UniqueDao.saveOrUpdateUniqueData(UniqData);
    }
  }

主类代码片段:它是一个命令行应用程序。

AbstractApplicationContext appContext = new   
                        AnnotationConfigApplicationContext(AppConfig.class);    
UniqueDataService serviceUniq = 
                        (UniqueDataService) appContext.getBean("UniqueService");

          UniqueDataTable UniqDataTable = oPacket.getUniqDataTable();
          String sNumer = UniqDataTable.getsNumber();                

          UniqueData UniqData = new UniqueData();
          UniqData.setsNumber(sNumer);
          UniqData.setsSerialNum(sSerialNum);

          // save or update : insert or update
          serviceUniq.saveOrUpdateUniqueData(UniqData);    

AppConfig.class

@Configuration
@ComponentScan(basePackages = "com.my.testProj")
public class AppConfig {

}

1 个答案:

答案 0 :(得分:0)

如果数据库中不存在给定对象的id,则

UIKeyboardWillHideNotification方法插入对象,如果存在,则数据库中的记录将从对象的属性中获取相同的值。

为了让您更轻松,您可以想象它在这里有相同的说明:

saveOrUpdate