java.lang.ClassNotFoundException: com.mysql.jdbc.Driver (maven + jboss)

前端 未结 4 1534
轻奢々
轻奢々 2021-01-21 08:02

maven pom.xml



        
相关标签:
4条回答
  • 2021-01-21 08:20

    This error occurred because your mysql jar is not on your run-time class-path. If you are using maven,

    1. Open your EAR/web project properties
    2. Click on "Deployment Assembly"
    3. Click on "Add..."
    4. Select on "Java Build Path Entries"
    5. Click on "Next"
    6. Select "Maven Dependencies"
    7. Click "Finish"
    0 讨论(0)
  • 2021-01-21 08:30

    As a rule you should not be including your JDBC drivers in your war file.

    I suggest you mark the driver as provided and add it to the lib directory of the server.

    PS. I'm not sure why you would be using

    Class.forName("com.mysql.jdbc.Driver")
    

    in your code. Why not let the contain manage your connections and transactions?

    0 讨论(0)
  • It seems you are using JBoss AS7. Check instructions here: https://community.jboss.org/wiki/DataSourceConfigurationInAS7

    Basically, you should

    1. Install mysql connector
    2. Create a data source using it
    3. Refer to that data source using JNDI configuration

    Class.forName() is an idiom commonly used when data sources are not provided by the container. In modern Java EE servers, they are provided.

    0 讨论(0)
  • 2021-01-21 08:32

    I had a slightly different use case. I was using apache's BasicDataSource in a stand-alone application.

    I got this exception because I was calling setDriverClassName with com.mysql.jdbc.Driver.class.toString() instead of "com.mysql.jdbc.Drive" as a String (so compile time check ensures that there is no typo or Driver's location didn't change in a version upgrade... etc).

    But!

    When you look Driver's implementation it has a static initialization block:

    static {
      try {
        java.sql.DriverManager.registerDriver(new Driver());
      } catch (SQLException E) {
        throw new RuntimeException("Can't register driver!");
      }
    }
    

    When I wrote com.mysql.jdbc.Driver.class.toString() this initialization block executed too early and caused later on misleading ClassNotFoundException to be thrown. Once I switched to "com.mysql.jdbc.Driver" my application started to work.

    This is a case when static becomes evil :)

    0 讨论(0)
提交回复
热议问题