在本文中,我们将给您介绍关于无法删除或更新父行ConstraintViolationException的详细内容,并且为您解答无法删除或更新父行怎么解决的相关问题,此外,我们还将为您提供关于###Er
在本文中,我们将给您介绍关于无法删除或更新父行ConstraintViolationException的详细内容,并且为您解答无法删除或更新父行怎么解决的相关问题,此外,我们还将为您提供关于### Error updating database. Cause: java.sql.SQLIntegrityConstraintViolationException: ORA-02291...、c# – 无法删除集合:[NHibernate.Exceptions.GenericADOException]、Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate ...、com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException的实例源码的知识。
本文目录一览:- 无法删除或更新父行ConstraintViolationException(无法删除或更新父行怎么解决)
- ### Error updating database. Cause: java.sql.SQLIntegrityConstraintViolationException: ORA-02291...
- c# – 无法删除集合:[NHibernate.Exceptions.GenericADOException]
- Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate ...
- com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException的实例源码
无法删除或更新父行ConstraintViolationException(无法删除或更新父行怎么解决)
我有2个对象实体(用户和电话),它们应该具有多对多关系。
User.java
//all columns@ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.EAGER) @JoinTable(name = "USER_PHONE", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "phone_id", referencedColumnName = "id")) private List<Phone> phones;
电话.java
//all columns@ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.EAGER) @JoinTable(name = "USER_PHONE", joinColumns = @JoinColumn(name = "phone_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id")) private List<User> userList;
现在,我在USER表中添加了ID为1和2的2个用户。然后,我添加一个ID为1的电话,并将它们映射到两个用户ID(1&2)。
我的USER_PHONE表如下所示:
Select * from USER_PHONE;+----------+---------+| phone_id | user_id |+----------+---------+| 1 | 1 || 1 | 2 |+----------+---------+
现在,我希望删除ID为2的用户。尝试执行此操作时,出现错误
javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`dbname`.`USER_PHONE`, CONSTRAINT `FKC6A847DAFA96A429` FOREIGN KEY (`user_id`) REFERENCES `USER` (`ID`))
我的删除脚本:
String query = "DELETE User where id=?1"; try{ Query q = entityManager.createQuery(query); q.setParameter(1,id); q.executeUpdate(); System.out.println(System.currentTimeMillis() + " DELETE: userId " + id + " ==> deleted"); } catch(Exception e){ e.printStackTrace(); return false; }
知道我哪里出错了吗?非常感谢 :)
答案1
小编典典尝试使用entityManager.createNativeQuery()
。您不能使用,createQuery()
因为该表应该作为实体存在于Java代码中。另外,您需要使用确切的SQL格式。
String query = "DELETE FROM USER_PHONE WHERE user_id=?1";
try{ Query q = entityManager.createNativeQuery(query); q.setParameter(1,id); q.executeUpdate(); System.out.println(System.currentTimeMillis() + " DELETE User_Phone: userId " + id + " ==> deleted"); } catch(Exception e){ e.printStackTrace(); return false; }`
首先从USER_PHONE
(使用createNativeQuery()
)删除行,然后从User
(使用createQuery()
)删除行
### Error updating database. Cause: java.sql.SQLIntegrityConstraintViolationException: ORA-02291...
在向Oracle数据库里面插入数据时发生了以下错误
; ]; ORA-02291: 违反完整约束条件 (SSM.SYS_C0011830) - 未找到父项关键字
; nested exception is java.sql.SQLIntegrityConstraintViolationException: ORA-02291: 违反完整约束条件 (SSM.SYS_C0011830) - 未找到父项关键字
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:986)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
A表和B表通过主键与中间表C表关联,在向C表中插入数据时,如果插入C表时中数据没有与A表或者B表中主键对应,就会出现该错误。
简而言之就是在插入数据时,中间表的数据必须在它所关联的表中存在。
c# – 无法删除集合:[NHibernate.Exceptions.GenericADOException]
tableA有列:tabAId,col2,col3(tabAId primaryKey和Identity列.)
tableB有列:tabAId,name(tabAId不为null)
我在tableA的hbm文件中创建了Bag,以维护关系.
<bag name="tableB" lazy="true" inverse="false" batch-size="25" cascade="all-delete-orphan"> <key column="tabAId" /> <one-to-many/> </bag>
当我尝试更新tableA中的记录时,它抛出异常,因为我在tableA实例中有子列表.
[NHibernate.Exceptions.GenericADOException] = {“Could not delete collection: [MIHR.Entities.tableA.tableB#21][sql: UPDATE dbo.tableB SET tabAId = null WHERE tabAId = @p0]”}
InnerException = {“Cannot insert the value NULL into column ‘tabAId’,table ‘SA_MIHR_DEV.dbo.tableB’;
column does not allow nulls. UPDATE fails.\r\nThe statement has been terminated.”}
解决方法
1)不要使用inverse =“false”
<bag name="tableB" lazy="true" inverse="true" // instead of false batch-size="25" cascade="all-delete-orphan"> <key column="tabAId" /> <one-to-many/> </bag>
此设置(inverse =“true”)将指示NHibernate直接从DB中删除项目.
虽然使用inverse =“false”一般会导致:
> UPDATE(with null)==从集合中删除的行为
> DELETE item ==级联行为
2)使引用列可以为空
这意味着,我们可以让NHibernate进行UPDATE和DELETE.因为列现在可以为空.
这些只是两种解决方法.
我的偏好是:inverse =“true”
要使用inverse =“true”正常工作,我们总是必须在C#中指定关系的两面.这是Add(),INSERT操作必须的:
Parent parent = new Parent(); Child child = new Child { ... Parent = parent,}; // unless initialized in the Parent type,we can do it here parent.Children = parent.Children ?? new List<Child>(); parent.Children.Add(child); // Now just parent Could be saved // and NHibernate will do all the cascade as expected // and because of inverse mapping - the most effective way session.Save(parent);
正如我们所看到的,我们已明确指定了关系的两个方面.这必须从NHibernate逆映射中获益.这也是一种很好的做法,因为稍后,当我们从数据库加载数据时,我们期望NHibernate会为我们设置
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate ...
### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry ''qingmu'' for key ''PRIMARY''
### The error may involve com.qingmu2.core.dao.seller.SellerDao.insertSelective-Inline
### The error occurred while setting parameters
### SQL: insert into tb_seller ( seller_id, name, nick_name, password, telephone, status, address_detail, linkman_name, linkman_qq, linkman_mobile, linkman_email, create_time ) values ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry ''qingmu'' for key ''PRIMARY''
; SQL []; Duplicate entry ''qingmu'' for key ''PRIMARY''; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry ''qingmu'' for key ''PRIMARY'', dubbo version: 2.8.4, current host: 127.0.0.1
org.springframework.dao.DuplicateKeyException:
### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry ''qingmu'' for key ''PRIMARY''
### The error may involve com.qingmu2.core.dao.seller.SellerDao.insertSelective-Inline
### The error occurred while setting parameters
### SQL: insert into tb_seller ( seller_id, name, nick_name, password, telephone, status, address_detail, linkman_name, linkman_qq, linkman_mobile, linkman_email, create_time ) values ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry ''qingmu'' for key ''PRIMARY''
; SQL []; Duplicate entry ''qingmu'' for key ''PRIMARY''; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry ''qingmu'' for key ''PRIMARY''
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:239)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:73)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:371)
at com.sun.proxy.$Proxy11.insert(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.insert(SqlSessionTemplate.java:240)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:51)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:52)
at com.sun.proxy.$Proxy24.insertSelective(Unknown Source)
at com.qingmu2.core.service.SellerServiceImpl.add(SellerServiceImpl.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
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:208)
at com.sun.proxy.$Proxy25.add(Unknown Source)
at com.alibaba.dubbo.common.bytecode.Wrapper2.invokeMethod(Wrapper2.java)
at com.alibaba.dubbo.rpc.proxy.javassist.JavassistProxyFactory$1.doInvoke(JavassistProxyFactory.java:46)
at com.alibaba.dubbo.rpc.proxy.AbstractProxyInvoker.invoke(AbstractProxyInvoker.java:72)
at com.alibaba.dubbo.rpc.protocol.InvokerWrapper.invoke(InvokerWrapper.java:53)
at com.alibaba.dubbo.rpc.filter.ExceptionFilter.invoke(ExceptionFilter.java:64)
at com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:91)
at com.alibaba.dubbo.monitor.support.MonitorFilter.invoke(MonitorFilter.java:75)
at com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:91)
at com.alibaba.dubbo.rpc.filter.TimeoutFilter.invoke(TimeoutFilter.java:42)
at com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:91)
at com.alibaba.dubbo.rpc.protocol.dubbo.filter.TraceFilter.invoke(TraceFilter.java:78)
at com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:91)
at com.alibaba.dubbo.rpc.filter.ContextFilter.invoke(ContextFilter.java:70)
at com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:91)
at com.alibaba.dubbo.rpc.filter.GenericFilter.invoke(GenericFilter.java:132)
at com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:91)
at com.alibaba.dubbo.rpc.filter.ClassLoaderFilter.invoke(ClassLoaderFilter.java:38)
at com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:91)
at com.alibaba.dubbo.rpc.filter.EchoFilter.invoke(EchoFilter.java:38)
at com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper$1.invoke(ProtocolFilterWrapper.java:91)
at com.alibaba.dubbo.rpc.protocol.dubbo.DubboProtocol$1.reply(DubboProtocol.java:113)
at com.alibaba.dubbo.remoting.exchange.support.header.HeaderExchangeHandler.handleRequest(HeaderExchangeHandler.java:84)
at com.alibaba.dubbo.remoting.exchange.support.header.HeaderExchangeHandler.received(HeaderExchangeHandler.java:170)
at com.alibaba.dubbo.remoting.transport.DecodeHandler.received(DecodeHandler.java:52)
at com.alibaba.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.run(ChannelEventRunnable.java:82)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry ''qingmu'' for key ''PRIMARY''
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:408)
at com.mysql.jdbc.Util.getInstance(Util.java:383)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1049)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4208)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4140)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2597)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2758)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2826)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2082)
at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1302)
at com.alibaba.druid.pool.DruidPooledPreparedStatement.execute(DruidPooledPreparedStatement.java:493)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.ibatis.logging.jdbc.PreparedStatementLogger.invoke(PreparedStatementLogger.java:62)
at com.sun.proxy.$Proxy33.execute(Unknown Source)
at org.apache.ibatis.executor.statement.PreparedStatementHandler.update(PreparedStatementHandler.java:44)
at org.apache.ibatis.executor.statement.RoutingStatementHandler.update(RoutingStatementHandler.java:69)
at org.apache.ibatis.executor.SimpleExecutor.doUpdate(SimpleExecutor.java:48)
at org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:105)
at org.apache.ibatis.executor.CachingExecutor.update(CachingExecutor.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:62)
at com.sun.proxy.$Proxy31.update(Unknown Source)
at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:152)
at org.apache.ibatis.session.defaults.DefaultSqlSession.insert(DefaultSqlSession.java:141)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:358)
... 47 more
因为我对同一条数据进行插入,所以才会报这个异常,因为id相同
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException的实例源码
public void delete(int row) throws Exception { ExecuteUpdateCommand command = new ExecuteUpdateCommand(); command.setsqlString(getDelete(row)); command = (ExecuteUpdateCommand)BisisApp.getJdbcService().executeCommand(command); if (command != null){ if (command.getRowCount() == 1){ data.remove(row); fireTableDataChanged(); } else if (command.getException() instanceof MysqLIntegrityConstraintViolationException){ throw new HoldingsIntegrityViolationException ("\u0160ifra ne mo\u017ee biti obrisana!\nPostoje primerci/godine/sveske za koje je uneta selektovana \u0161ifra."); } else { throw command.getException(); } } else { throw new Exception ("Gre\u0161ka u konekciji s bazom podataka!"); } }
@Override public int persist(SearchQueryVO obj) throws sqlException { int r =0; Connection con=DBConnection.getSingleConnection(); try{ //con = DBConnection.getConnection(); String query = "insert into "+tableName+" (query,jsonpath,result,timestamp)values(?,?,?)"; PreparedStatement preparedStatement = con.prepareStatement(query); //preparedStatement.setLong(1,obj.getSongId()); preparedStatement.setString(1,obj.getQuery()); preparedStatement.setString(2,obj.getJsonPath()); preparedStatement.setString(3,obj.getResult()); preparedStatement.setTimestamp(4,new Timestamp(System.currentTimeMillis())); r=preparedStatement.executeUpdate(); } catch(MysqLIntegrityConstraintViolationException ex){ System.out.println( "QUERY IS ALREADY THERE: "+obj.getQuery()); } finally{ con.close(); } return r; }
private VmNicVO persistAndRetryIfMacCollision(VmNicVO vo) { int tries = 5; while (tries-- > 0) { try { vo = dbf.persistAndRefresh(vo); return vo; } catch (JpaSystemException e) { if (e.getRootCause() instanceof MysqLIntegrityConstraintViolationException && e.getRootCause().getMessage().contains("Duplicate entry")) { logger.debug(String.format("Concurrent mac allocation. Mac[%s] has been allocated,try allocating another one. " + "The error[Duplicate entry] printed by jdbc.spi.sqlExceptionHelper is no harm," + "we will try finding another mac",vo.getMac())); logger.trace("",e); vo.setMac(NetworkUtils.generateMacWithdeviceid((short) vo.getdeviceid())); } else { throw e; } } } return null; }
public ResultSet executeQuery( PreparedStatement pstmt,Void result ) throws sqlException,SiteException { try { pstmt.executeUpdate(); }catch( MysqLIntegrityConstraintViolationException e ){ //This exception is thrown in case there is already one avatar image for //the user. Note that,it should be caught before being passed to the client!!! throw new InternalSiteException("The user Avatar image already exists!"); } return null; }
@Override public int persist(AsyncSearchVO obj) throws sqlException { int r =0; Connection con=DBConnection.getSingleConnection(); try{ //con = DBConnection.getConnection(); String query = "insert into "+table+" (uuid,query,result_uri,search_type,tables,timeinMS,?)"; PreparedStatement preparedStatement = con.prepareStatement(query); preparedStatement.setString(1,obj.getUuid()); preparedStatement.setString(2,obj.getQuery()); preparedStatement.setString(3,obj.getResultUri()); preparedStatement.setString(4,obj.getSearchType()); preparedStatement.setString(5,obj.getTables()); preparedStatement.setLong(6,obj.getTimeinMS()); preparedStatement.setTimestamp(7,new Timestamp(System.currentTimeMillis())); r=preparedStatement.executeUpdate(); } catch(MysqLIntegrityConstraintViolationException ex){ System.out.println( "QUERY IS ALREADY THERE: "+obj.getQuery()); } finally{ con.close(); } return r; }
public int persist(SearchQueryVO obj,Connection con ) throws sqlException { int r =0; try{ //con = DBConnection.getConnection(); String query = "insert into "+tableName+" (query,new Timestamp(System.currentTimeMillis())); r=preparedStatement.executeUpdate(); } catch(MysqLIntegrityConstraintViolationException ex){ System.out.println( "QUERY IS ALREADY THERE: "+obj.getQuery()); } finally{ } return r; }
public int persist(ConfigVO obj) throws sqlException { int r =0; Connection con=DBConnection.getSingleConnection(); try{ //con = DBConnection.getConnection(); String query = "insert into music.config (category,instance,component,name,value,description)values(?,obj.getCategory()); preparedStatement.setString(2,obj.getInstance()); preparedStatement.setString(3,obj.getComponent()); preparedStatement.setString(4,obj.getName()); preparedStatement.setString(5,obj.getValue()); preparedStatement.setString(6,obj.getDescription()); r=preparedStatement.executeUpdate(); } catch(MysqLIntegrityConstraintViolationException ex){ System.out.println( "Config IS ALREADY THERE: "+obj.getName()); } finally{ con.close(); } return r; }
@Override public boolean create(Document_Organisation obj) throws sqlException { boolean result = false; if (obj.getDoc() == null || obj.getorgs() == null) { throw new IllegalArgumentException("No Document nor organisation is already created,the Affiliation ID is not null."); } PreparedStatement statement = null; try { statement = connect.prepareStatement(sql_INSERT,Statement.RETURN_GENERATED_KEYS); for (Organisation org : obj.getorgs()) { try { statement.setString(1,obj.getDoc().getDocID()); statement.setLong(2,org.getorganisationId()); statement.executeUpdate(); result = true; } catch (MysqLIntegrityConstraintViolationException e) { } } } finally { closeQuietly(statement); } return result; }
private void handle(APICreateLdapBindingMsg msg) { APICreateLdapBindingEvent evt = new APICreateLdapBindingEvent(msg.getId()); // account check SimpleQuery<AccountVO> sq = dbf.createquery(AccountVO.class); sq.add(AccountVO_.uuid,SimpleQuery.Op.EQ,msg.getAccountUuid()); AccountVO avo = sq.find(); if (avo == null) { evt.setError(errf.instantiateErrorCode(LdapErrors.CANNOT_FIND_ACCOUNT,String.format("cannot find the specified account[uuid:%s]",msg.getAccountUuid()))); bus.publish(evt); return; } String ldapUseAsLoginName = LdapUtil.getLdapUseAsLoginName(); // bind op LdapTemplateContextSource ldapTemplateContextSource = readLdapServerConfiguration(); String fullDn = msg.getLdapUid(); if (!validatednExist(ldapTemplateContextSource,fullDn)) { throw new OperationFailureException(errf.instantiateErrorCode(LdapErrors.UNABLE_TO_GET_SPECIFIED_LDAP_UID,String.format("cannot find dn[%s] on ldap server[Address:%s,Basedn:%s].",fullDn,String.join(",",ldapTemplateContextSource.getLdapContextSource().getUrls()),ldapTemplateContextSource.getLdapContextSource().getBaseLdapPathAsstring()))); } try { evt.setInventory(bindLdapAccount(msg.getAccountUuid(),fullDn)); logger.info(String.format("create ldap binding[ldapUid=%s,ldapUseAsLoginName=%s] success",ldapUseAsLoginName)); } catch (JpaSystemException e) { if (e.getRootCause() instanceof MysqLIntegrityConstraintViolationException) { evt.setError(errf.instantiateErrorCode(LdapErrors.BIND_SAME_LDAP_UID_TO_MULTI_ACCOUNT,"The ldap uid has been bound to an account. ")); } else { throw e; } } bus.publish(evt); }
@Override public UsedIpInventory reserveIp(IpRangeInventory ipRange,String ip) { try { UsedIpVO vo = new UsedIpVO(ipRange.getUuid(),ip); vo.setIpInLong(NetworkUtils.ipv4StringToLong(ip)); String uuid = ipRange.getUuid() + ip; uuid = UUID.nameUUIDFromBytes(uuid.getBytes()).toString().replaceAll("-",""); vo.setUuid(uuid); vo.setL3NetworkUuid(ipRange.getL3NetworkUuid()); vo.setNetmask(ipRange.getNetmask()); vo.setGateway(ipRange.getGateway()); vo = dbf.persistAndRefresh(vo); return UsedIpInventory.valueOf(vo); } catch (JpaSystemException e) { if (e.getRootCause() instanceof MysqLIntegrityConstraintViolationException) { logger.debug(String.format("Concurrent ip allocation. " + "Ip[%s] in ip range[uuid:%s] has been allocated,try allocating another one. " + "The error[Duplicate entry] printed by jdbc.spi.sqlExceptionHelper is no harm," + "we will try finding another ip",ip,ipRange.getUuid())); logger.trace("",e); } else { throw e; } } return null; }
private void updateEO(Object entity,DataIntegrityViolationException de) { if (!MysqLIntegrityConstraintViolationException.class.isAssignableFrom(de.getRootCause().getClass())) { throw de; } MysqLIntegrityConstraintViolationException me = (MysqLIntegrityConstraintViolationException) de.getRootCause(); if (!(me.getErrorCode() == 1062 && "23000".equals(me.getsqlState()) && me.getMessage().contains("PRIMARY"))) { throw de; } if (!haSEO()) { throw de; } // at this point,the error is caused by a update tried on VO entity which has been soft deleted. This is mostly // caused by a deletion cascade(e.g deleting host will cause vm running on it to be deleted,and deleting vm is trying to return capacity // to host which has been soft deleted,because vm deletion is executed in async manner). In this case,we make the update to EO table Object idval = getEOPrimarykeyvalue(entity); Object eo = getEntityManager().find(eoClass,idval); final Object deo = ObjectUtils.copy(eo,entity); new Runnable() { @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public void run() { getEntityManager().merge(deo); } }.run(); logger.debug(String.format("A EO[%s] update has been made",eoClass.getName())); }
/** * does what it says * * @param user * @throws DBOperationException */ public void removeUserFromrole(User user) throws DBOperationException { if (user.getId() == -1 || this.getId() == -1) { throw new DBOperationException( "User or Role is not correctly configured and has no id"); } if (users == null) users = new ArrayList(); else if (!users.contains(user)) return; // return the favor user.getRoles().remove(this); UserRoleIdxExample userRole = new UserRoleIdxExample(); Criteria crit = userRole.createCriteria(); crit.andRoleIdEqualTo(this.id); crit.andUserIdEqualTo(user.getId()); sqlSession session = null; try { session = MyBatisConnectionFactory.getsqlSessionFactory() .openSession(true); // get it UserRoleIdx ur = session.selectOne( "io.starter.dao.UserRoleIdxMapper.selectByExample",userRole); session.delete("io.starter.dao.UserRoleIdxMapper.deleteByPrimaryKey",ur.getId()); } catch (Exception e) { if (session != null) session.close(); if (!(e.getCause() instanceof MysqLIntegrityConstraintViolationException)) { throw new DBOperationException(e.toString()); } // otherwise record already exists,just move on } finally { if (session != null) session.close(); } if (users != null) users.remove(user); if (session != null) session.close(); }
今天关于无法删除或更新父行ConstraintViolationException和无法删除或更新父行怎么解决的介绍到此结束,谢谢您的阅读,有关### Error updating database. Cause: java.sql.SQLIntegrityConstraintViolationException: ORA-02291...、c# – 无法删除集合:[NHibernate.Exceptions.GenericADOException]、Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate ...、com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException的实例源码等更多相关知识的信息可以在本站进行查询。
本文标签: