gpt4 book ai didi

java - 从数据库中删除对象,JPA

转载 作者:行者123 更新时间:2023-11-30 10:46:03 25 4
gpt4 key购买 nike

这是我的 DAO 方法:

public void deleteById(int id){
TypedQuery<Animal> query = entityManager.createQuery("Select e from Animal e where e.id="+id, Animal.class);
Animal entity = query.getSingleResult();
System.out.println(entityManager.contains(entity));
System.out.println(entity.hashCode());
entity = entityManager.merge(entity);
System.out.println("after merge");
System.out.println(entity.hashCode());
System.out.println(entityManager.contains(entity));
entityManager.remove(entity);
}

这是我的 Controller :

@RequestMapping("{animal}/{name}/{id}/delete")
public String dropAnimal(@PathVariable("id") int id){

animalDAO.deleteById(id);
return "glowny";
}

当我尝试移除对象时,我在移除分离实例时出错。

我在merge前后做了sysout,都是false,不知道为什么。为什么我的对象仍然分离?

java.lang.IllegalArgumentException: Removing a detached instance kaczynski.impl.Cat#1 at org.hibernate.jpa.event.internal.core.JpaDeleteEventListener.performDetachedEntityDeletionCheck(JpaDeleteEventListener.java:69) at org.hibernate.event.internal.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:106) at org.hibernate.event.internal.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:73) at org.hibernate.internal.SessionImpl.fireDelete(SessionImpl.java:920) at org.hibernate.internal.SessionImpl.delete(SessionImpl.java:896) at org.hibernate.jpa.spi.AbstractEntityManagerImpl.remove(AbstractEntityManagerImpl.java:1214) 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.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:365) at com.sun.proxy.$Proxy22.remove(Unknown Source) 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.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240) at com.sun.proxy.$Proxy22.remove(Unknown Source) at kaczynski.DBaccess.AnimalDAO.deleteById(AnimalDAO.java:88) at kaczynski.DBaccess.AnimalDAO$$FastClassBySpringCGLIB$$5f2786e9.invoke() at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655) at kaczynski.DBaccess.AnimalDAO$$EnhancerBySpringCGLIB$$53a0549d.deleteById() at kaczynski.web.AnimalsController.dropAnimal(AnimalsController.java:48) 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.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:859) at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source)

在 stackTrace 之前我有这个消息:

kwi 21, 2016 10:47:45 AM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet [mvc-dispatcher] in context with path [/zapisywacz.baza] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Removing a detached instance kaczynski.impl.Cat#1; nested exception is java.lang.IllegalArgumentException: Removing a detached instance kaczynski.impl.Cat#1] with root cause

这是 hascodes 的输出:

false
1870474474
after merge
445252736
false

持久性.xml

<persistence 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"
version="2.0">
<persistence-unit name="myDatabase" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>

<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.user" value="tutorial" />
<property name="javax.persistence.jdbc.password" value="password" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mojaBaza" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect " />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>

动物实体

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Animal {

@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private int id;

private String name;

private int age;
@Column(name="date_of_birth")
private String dateOfBirth;

private double weight;

public Animal(String name, int age, String dateOfBirth, double weight) {
this.name = name;
this.age = age;
this.dateOfBirth = dateOfBirth;
this.weight = weight;
}

public Animal() {}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getDateOfBirth() {
return dateOfBirth;
}

public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}

public double getWeight() {
return weight;
}

public void setWeight(double weight) {
this.weight = weight;
}

@Override
public String toString() {
return " id= " + id + " name=" + name + ", age=" + age
+ ", dateOfBirth=" + dateOfBirth + ", weight=" + weight;
}

public String tease() {
return "";
}

public String giveVoice() {
return "";
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}
}

最佳答案

我找到了解决方案,

在 spring 中配置丢失,并且由于注释 @Transactional,spring 不可见。

关于java - 从数据库中删除对象,JPA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36763490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com