基于MVC的休眠JPA项目中的“ java.lang.ClassNotFoundException:javax.persistence.Persistence”错误

时间:2018-12-10 08:43:37

标签: hibernate jpa servlets model-view-controller

我尝试基于MVC结构和Hibernate JPA创建一个Web应用程序。

我想将数据表单保存在数据库中。为此,我在servlet中获取数据并在personManager包中的business logic "bl"类中调用一个方法。

此方法最多会获取并保存数据,但会出现此错误:

10-Dec-2018 11:15:07.463 SEVERE [http-nio-8080-exec-5] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [manager] in context with path [] threw exception [Servlet execution threw an exception] with root cause
java.lang.ClassNotFoundException: javax.persistence.Persistence
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1309)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1137)
at util.JPAProvider.<clinit>(JPAProvider.java:13)
at model.bl.PersonManager.<init>(PersonManager.java:24)
at controller.Manager.service(Manager.java:81)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
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)

servlet类:

  public void service (HttpServletRequest request , HttpServletResponse response)throws IOException, ServletException
{
    String username= request.getParameter("choose-username");
    String password= request.getParameter("choose-password");
    String repeatPass= request.getParameter("repeat-password");
    String email = request.getParameter("email");
    HttpSession session = request.getSession();

     try {
            PersonManager personManager = new PersonManager();
            personManager.addUser(username , password , email , "female");
            response.sendRedirect("/views/welcome.jsp");
        } catch (Exception e)
        {
            request.getRequestDispatcher("/views/register.jsp").forward(request, response);
        }
    }

JPAProvider类:

public class JPAProvider {

private static final EntityManagerFactory entityManagerFactory;//instate of session for connect to database
static{
    entityManagerFactory  = Persistence.createEntityManagerFactory("MyConnection");
}

public static EntityManagerFactory getEntityManagerFactory() {
    return entityManagerFactory;
}

}

公共类PersonManager {

EntityManager entityManager=null;
EntityTransaction entityTransaction=null;

public PersonManager() {
     entityManager = JPAProvider.getEntityManagerFactory().createEntityManager();//session factory
     entityTransaction = entityManager.getTransaction();
}

public Boolean addUser(String username , String password , String email , String sex)
{
    try{
        entityTransaction.begin();
        Person person = new Person();
        person.setUsername(username);
        person.setPassword(password);
        person.setEmail(email);
        person.setSex(sex);
        entityManager.persist(person);
        entityTransaction.commit();
        entityManager.close();

    }catch (Exception e){
        System.out.println(e.getStackTrace());
        System.out.println("addUser failed");
    }
    return true;
}

}

人员班级:

package model.entity;
import model.bl.PersonManager;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;

//mapping class to table
@Entity (name = "person")
@Table(name = "USERS")
@EntityListeners(value = PersonManager.class)

public class Person implements Serializable
{

@Id // create id and fill auto by sequence in database
@Column(name="UID" ,columnDefinition = "NUMBER" )
@SequenceGenerator(name = "mySeq" , sequenceName = "DB_MYSEQ")
@GeneratedValue(strategy=GenerationType.AUTO ,generator="mySeq")
private long uId;


@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "FK_PERSON",referencedColumnName = "UID")
private List<Pictures> picturesList;


@Basic
@Column (name = "USERNAME" , columnDefinition = "NVARCHAR2(30)" , nullable = false , unique = true)
private String username ;

@Basic
@Column (name = "USER_PASSWORD" , columnDefinition = "NVARCHAR2(32)" , nullable = false , unique = true)
private String  password ;

@Basic
@Column (name = "EMAIL" , columnDefinition = "NVARCHAR2(40)" , nullable = false)
private String email;


@Basic
@Column (name = "SEX" , columnDefinition = "NVARCHAR2(20)")
private String sex ;

//--------------------------------------------------------

public Person() { }

public Person(String username, String password, String email, String sex, String userPic) {
    this.username = username;
    this.password = password;
    this.email = email;
    this.sex = sex;
    this.userPic = userPic;
}
public Person(String username, String password, String email ,String sex, String userPic,List<Pictures> picturesList ) {
    this.picturesList = picturesList;
    this.sex = sex;
    this.userPic = userPic;
    this.email = email;
    this.password = password;
    this.username = username;
}

//--------------------------------------------------------

public void setUsername(String username) {
    this.username = username;
}

public void setPassword(String password) {
    this.password = password;
}

public void setEmail(String email) {
    this.email = email;
}

public void setUserPic(String userPic) {
    this.userPic = userPic;
}

public void setSex(String sex) {
    this.sex = sex;
}

public void setuId(long uId) {this.uId = uId;}

//--------------------------------------------------------

public String getUsername() {
    return username;
}

public String getPassword() {
    return password;
}

public String getUserPic() {
    return userPic;
}

public String getEmail() {
    return email;
}

public String getSex() {
    return sex;
}

public long getuId() {return uId;}

}
}

persistence.xml:

<persistence-unit name="MyConnection" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>

        <!--<property name="hibernate.transaction.flush_before_completion" value="true"/>-->
        <!--<property name="hibernate.format_sql" value="true"/>-->

        <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
        <property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="hibernate.connection.username" value="midas"/>
        <property name="hibernate.connection.password" value="midas123"/>
        <property name="hibernate.connection.url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
        <!--<property name="hibernate.hbm2ddl.auto" value="create-drop"/>-->
        <property name="show_sql" value="true"></property>
       <!-- <property name="hibernate.globally_quoted_identifiers" value="true"/>-->
    </properties>
</persistence-unit>

在某些情况下,据说问题出在javax.persistence.jar上。 我将新的javax.persistence.jar添加到我的库中,但问题没有解决。

我使用:

tomcat 8 JDK 1.8.0-172  oracle 11g IntellyJ Idea

我使用了以下库:

1)hibernate-enverc-4.2.0.final

2)hibernate-jpa-2.0-api-1.0.1-final.jar

3)tomcat库

项目结构:

src->控制器-> Manager.java

src->模型-> bl-> personManager.java

src->实体-> person.java

src-> util-> JPAProvider.java

src-> META-INF-> persistence.xml

网络->视图-> ...

web-> WEB-INF-> lib

web-> WEB-INF-> web.xml

如何解决此错误?

2 个答案:

答案 0 :(得分:1)

对于仍然遇到此问题的任何人,我都会得到一个对我有效的解决方案!

打开项目属性(右键单击>属性),然后选择“ Deployment Assembly”。在此处单击“添加”,选择“构建路径条目”,然后选择“行依赖”。这将指示WTP将Maven依赖项发送到服务器目录。

答案 1 :(得分:0)

它不应该在项目根目录下,而应直接在源文件夹下。

在运行时,在META-INF下的类路径中搜索persistence.xml文件。因此,如果要将META-INF文件夹放在已编译的软件包树的顶部,则需要将其放在源树的顶部。 Eclipse遵循包/文件夹层次结构将每个非Java文件复制到其输出目录(默认情况下为bin)。