在我的ControllerServlet类中,对于doPost方法,我有一个从db表中删除人员的操作:
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = request.getServletPath();
...
else if (path.equals("/remove_person")) {
String id = request.getParameter("id");
Person person = em.find(Person.class, Integer.parseInt(id));
try {
utx.begin();
em.remove(person);
utx.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
String url = path + ".jsp";
request.getRequestDispatcher(url).forward(request, response);
}
但是,当我刷新表格时,我试图删除的记录仍然存在于人员表中。顺便说一句,当我不得不添加新人时,我没有遇到任何问题。
下面是实体Person类的代码:
@Entity
@Table(name = "persons")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Person.findAll", query = "SELECT p FROM Person p"),
@NamedQuery(name = "Person.findById", query = "SELECT p FROM Person p WHERE v.id = :id"),
@NamedQuery(name = "Person.findByName", query = "SELECT p FROM Person p WHERE v.name = :name"),
@NamedQuery(name = "Person.findByYearBirth", query = "SELECT p FROM Person p WHERE v.yearBirth= :yearBirth"),
@NamedQuery(name = "Person.findByNameYearBirth",
query = "SELECT p FROM Person p WHERE p.name = :name or p.yearBirth = :yearBirth"),
@NamedQuery(name = "Person.deleteById", query = "DELETE FROM Person p WHERE p.id = :id")})
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Size(max = 45)
@Column(name = "name")
private String name;
@Column(name = "yearBirth")
private Short yearBirth;
// constructors, setters, getters...
}
那么,这个问题的原因是什么?
更新
1)我可以成功(手动)从表中删除记录或从mysql workbranch输入sql语句。
2)对于以下代码,如果我删除try / catch,我会得到异常java.lang.RuntimeException: Uncompilable source code - unreported exception javax.transaction.NotSupportedException; must be caught or declared to be thrown
Person person = em.find(Person.class, Integer.parseInt(id));
try {
utx.begin();
em.remove(person);
utx.commit();
} catch (Exception e) {
e.printStackTrace();
}
3)我尝试使用下面的代码从表中删除记录但在这种情况下我得到了异常:
javax.persistence.TransactionRequiredException:
Exception Description: No externally managed transaction is currently active for this thread
Query query = em.createNamedQuery("Person.deleteById");
query.setParameter("id", Integer.parseInt(id));
query.executeUpdate();
ControllerServlet类
@WebServlet(
name = "ControllerServlet",
loadOnStartup = 1,
urlPatterns = {
"/index",
"/search_person",
"/add_person",
"/remove_person"})
public class ControllerServlet extends HttpServlet {
@PersistenceUnit
private EntityManagerFactory emf;
@Resource
private UserTransaction utx;
private EntityManager em;
@Override
public void init() throws ServletException {
assert emf != null;
em = emf.createEntityManager();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = request.getServletPath();
if (path.equals("/index")) {
}
else if (path.equals("/search_person")) {
List persons = em.createNamedQuery("Person.findAll").getResultList();
request.setAttribute("findByNameAndYearBirth", persons);
}
else if (path.equals("/add_person")) {
}
else if (path.equals("/remove_person")) {
List persons = em.createNamedQuery("Person.findAll").getResultList();
request.setAttribute("findAll", persons);
}
String url = path + ".jsp";
request.getRequestDispatcher(url).forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = request.getServletPath();
if (path.equals("/index")) {
}
else if (path.equals("/search_person")) {
String name = request.getParameter("name");
String yearBirth = request.getParameter("yearBirth");
Query query = em.createNamedQuery("Person.findAll");
if (!name.isEmpty() && !yearBirth.isEmpty()) {
query = em.createNamedQuery("Person.findByNameAndYearBirth");
query.setParameter("name", name);
query.setParameter("yearBirth", Short.parseShort(yearBirth));
}
else if (!name.isEmpty()) {
query = em.createNamedQuery("Person.findByModel");
query.setParameter("name", name);
}
else if (!yearBirth.isEmpty()) {
try {
Short sYearBirth = Short.parseShort(yearBirth);
query = em.createNamedQuery("Person.findByYearBirth");
query.setParameter("yearBirth", sYearBirth);
} catch (NumberFormatException nfe) {}
}
List persons = query.getResultList();
request.setAttribute("findByNameAndYearBirth", persons);
}
else if (path.equals("/add_person")) {
String name = request.getParameter("name");
String hobby = request.getParameter("hobby");
String yearBirth = request.getParameter("yearBirth");
int personsLen = em.createNamedQuery("Person.findAll").getResultList().size();
Person newPerson = new Person(
++personsLen, name, hobby, Short.parseShort(yearBirth)
);
try {
utx.begin();
em = emf.createEntityManager();
em.persist(newPerson);
utx.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
else if (path.equals("/remove_person")) {
String id = request.getParameter("id");
Person person = null;
try {
utx.begin();
person = em.find(Person.class, Integer.parseInt(id));
em.remove(person);
utx.commit();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
String url = path + ".jsp";
request.getRequestDispatcher(url).forward(request, response);
}
}
的persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="DB_PERSON_TEST_PU" transaction-type="JTA">
<jta-data-source>jdbc/db_person_test</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
堆栈跟踪:
SEVERE: java.lang.IllegalArgumentException: Object: null is not a known entity type.
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.remove(EntityManagerImpl.java:560)
at server.ControllerServlet.doPost(ControllerServlet.java:122)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:744)
答案 0 :(得分:0)
SQL服务器实例本身可能会阻止从表中删除条目。 您可能需要仔细检查将要删除的条目链接到其他条目的任何键和/或约束。
尝试使用SQL而不是脚本手动删除表中的条目,如果SQL服务器确实拒绝删除条目,因为前面提到的约束它应该显示错误,指示一个或多个约束阻止您执行如此。
解决方法是暂时删除所有约束,删除条目然后重新应用它们。
我希望这足以提供足够的帮助。