如何将mysql数据源添加到applicationContext.xml

时间:2014-10-24 15:50:00

标签: java mysql spring hibernate maven

我正在制作动态网络应用程序。 在我的应用程序中,我使用Spring和Hibernate。

这是我的pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>rasika.gayan.nought</groupId>
<artifactId>mit-site-temp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<!-- spring framework spring framework spring framework -->

<!-- Shared version number properties -->
<properties>
    <org.springframework.version>4.1.1.RELEASE</org.springframework.version>
</properties>

<dependencies>
    <!-- Core utilities used by other modules. Define this if you use Spring 
        Utility APIs (org.springframework.core.*/org.springframework.util.*) -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <!-- Expression Language (depends on spring-core) Define this if you use 
        Spring Expression APIs (org.springframework.expression.*) -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <!-- Bean Factory and JavaBeans utilities (depends on spring-core) Define 
        this if you use Spring Bean APIs (org.springframework.beans.*) -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <!-- Aspect Oriented Programming (AOP) Framework (depends on spring-core, 
        spring-beans) Define this if you use Spring AOP APIs (org.springframework.aop.*) -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <!-- Application Context (depends on spring-core, spring-expression, spring-aop, 
        spring-beans) This is the central artifact for Spring's Dependency Injection 
        Container and is generally always defined -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <!-- Various Application Context utilities, including EhCache, JavaMail, 
        Quartz, and Freemarker integration Define this if you need any of these integrations -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <!-- Transaction Management Abstraction (depends on spring-core, spring-beans, 
        spring-aop, spring-context) Define this if you use Spring Transactions or 
        DAO Exception Hierarchy (org.springframework.transaction.*/org.springframework.dao.*) -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <!-- JDBC Data Access Library (depends on spring-core, spring-beans, spring-context, 
        spring-tx) Define this if you use Spring's JdbcTemplate API (org.springframework.jdbc.*) -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <!-- Object-to-Relation-Mapping (ORM) integration with Hibernate, JPA, 
        and iBatis. (depends on spring-core, spring-beans, spring-context, spring-tx) 
        Define this if you need ORM (org.springframework.orm.*) -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <!-- Object-to-XML Mapping (OXM) abstraction and integration with JAXB, 
        JiBX, Castor, XStream, and XML Beans. (depends on spring-core, spring-beans, 
        spring-context) Define this if you need OXM (org.springframework.oxm.*) -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-oxm</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <!-- Web application development utilities applicable to both Servlet and 
        Portlet Environments (depends on spring-core, spring-beans, spring-context) 
        Define this if you use Spring MVC, or wish to use Struts, JSF, or another 
        web framework with Spring (org.springframework.web.*) -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <!-- Spring MVC for Servlet Environments (depends on spring-core, spring-beans, 
        spring-context, spring-web) Define this if you use Spring MVC with a Servlet 
        Container such as Apache Tomcat (org.springframework.web.servlet.*) -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <!-- Spring MVC for Portlet Environments (depends on spring-core, spring-beans, 
        spring-context, spring-web) Define this if you use Spring MVC with a Portlet 
        Container (org.springframework.web.portlet.*) -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc-portlet</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <!-- Support for testing Spring applications with tools such as JUnit and 
        TestNG This artifact is generally always defined with a 'test' scope for 
        the integration testing framework and unit testing stubs -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${org.springframework.version}</version>
        <scope>test</scope>
    </dependency>

    <!-- javax servlet -->

     <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>

    <!-- javax servlet jsp -->

    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.2.1</version>
        <scope>provided</scope>
    </dependency>

    <!-- hibernate -->

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.3.6.Final</version>
    </dependency>

    <!-- spring data jpa -->

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.7.0.RELEASE</version>
    </dependency>

    <!-- jdbc driver -->

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>

    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.4</version>
    </dependency>

    <dependency>
        <groupId>javax.persistence</groupId>
        <artifactId>persistence-api</artifactId>
        <version>1.0</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.0-api</artifactId>
        <version>1.0.1.Final</version>
    </dependency>


    <!-- slf4j -->

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.7</version>
    </dependency>

</dependencies>

<!-- jetty and compiler -->

<build>
    <plugins>

        <plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>9.2.3.v20140905</version>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.2</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>

    </plugins>
</build>

在我的pom.xml中,我包含 org.hibernate.javax.persistence javax.persistence 。 这是正确的????

然后这是我的applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">


<!-- this will scan other all in directory -->
<context:component-scan base-package="com.rasika.gayan">
    <context:exclude-filter type="annotation"
        expression="org.springframework.stereotype.Controller" />
</context:component-scan>

<!-- ***************jpa configeration ********************** -->

<tx:annotation-driven transaction-manager="transactionManager" />

<bean class="org.springframework.orm.jpa.JpaTransactionManager"
    id="transactionManager">
    <property name="dataSource" ref="dataSource"></property>
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/finalyearproject" />
    <property name="username" value="root" />
    <property name="password" value="r00t" />
</bean>

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />

    <property name="annotatedClasses">
        <list>
            <value>com.xxx.yyy.entity.Complains</value>
            <value>com.xxx.yyy.entity.LogFileContent</value>
            <value>com.xxx.yyy.entity.OrderDetail</value>
            <value>com.xxx.yyy.entity.SendDeliverableDetail</value>
            <value>com.xxx.yyy.entity.SkillDetail</value>
            <value>com.xxx.yyy.entity.TaskDetail</value>
            <value>com.xxx.yyy.entity.TaskRateDetail</value>
            <value>com.xxx.yyy.entity.TempUser</value>
            <value>com.xxx.yyy.entity.UserComments</value>
            <value>com.xxx.yyy.entity.UserDetail</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>




<!-- **org.springframework.jdbc.datasource.DriverManagerDataSource -->
<!-- org.apache.commons.dbcp.BasicDataSource -->

在我构建我的应用程序后,我得到了他的错误...................................... ...

        SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
        SLF4J: Defaulting to no-operation (NOP) logger implementation
        SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
        [INFO] Scanning for projects...
        [INFO]                                                                         
        [INFO] ------------------------------------------------------------------------
        [INFO] Building mit-site-temp 0.0.1-SNAPSHOT
        [INFO] ------------------------------------------------------------------------
        [INFO] 
        [INFO] >>> jetty-maven-plugin:9.2.3.v20140905:run (default-cli) @ mit-site-temp >>>
        [INFO] 
        [INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ mit-site-temp ---
        [debug] execute contextualize
        [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
        [INFO] Copying 0 resource
        [INFO] 
        [INFO] --- maven-compiler-plugin:3.2:compile (default-compile) @ mit-site-temp ---
        [WARNING] The POM for org.apache.maven:maven-plugin-api:jar:2.0.9 is invalid, transitive dependencies (if any) will not be available, enable debug logging for more details
        [WARNING] The POM for org.apache.maven:maven-artifact:jar:2.0.9 is invalid, transitive dependencies (if any) will not be available, enable debug logging for more details
        [WARNING] The POM for org.apache.maven:maven-core:jar:2.0.9 is invalid, transitive dependencies (if any) will not be available, enable debug logging for more details
        [INFO] Nothing to compile - all classes are up to date
        [INFO] 
        [INFO] --- maven-resources-plugin:2.5:testResources (default-testResources) @ mit-site-temp ---
        [debug] execute contextualize
        [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
        [INFO] Copying 0 resource
        [INFO] 
        [INFO] --- maven-compiler-plugin:3.2:testCompile (default-testCompile) @ mit-site-temp ---
        [INFO] Nothing to compile - all classes are up to date
        [INFO] 
        [INFO] <<< jetty-maven-plugin:9.2.3.v20140905:run (default-cli) @ mit-site-temp <<<
        [INFO] 
        [INFO] --- jetty-maven-plugin:9.2.3.v20140905:run (default-cli) @ mit-site-temp ---
        2014-10-24 20:55:54.158:INFO::main: Logging initialized @3946ms
        [INFO] Configuring Jetty for project: mit-site-temp
        [INFO] webAppSourceDirectory not set. Trying src\main\webapp
        [INFO] Reload Mechanic: automatic
        [INFO] Classes = D:\MITSite\target\classes
        [INFO] Context path = /
        [INFO] Tmp directory = D:\MITSite\target\tmp
        [INFO] Web defaults = org/eclipse/jetty/webapp/webdefault.xml
        [INFO] Web overrides =  none
        [INFO] web.xml file = file:/D:/MITSite/src/main/webapp/WEB-INF/web.xml
        [INFO] Webapp directory = D:\MITSite\src\main\webapp
        2014-10-24 20:55:54.230:INFO:oejs.Server:main: jetty-9.2.3.v20140905
        2014-10-24 20:55:58.044:INFO:/:main: No Spring WebApplicationInitializer types detected on classpath
        2014-10-24 20:55:58.096:INFO:/:main: Initializing Spring root WebApplicationContext
        log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
        log4j:WARN Please initialize the log4j system properly.
        log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
        2014-10-24 20:55:58.503:WARN:oejw.WebAppContext:main: Failed startup of context o.e.j.m.p.JettyWebAppContext@4857e34a{/,file:/D:/MITSite/src/main/webapp/,STARTING}{file:/D:/MITSite/src/main/webapp/}
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined

    ////// minimize the error log ................

    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
    Caused by: 
    org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined

    ////// minimize the error log .......

    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
    2014-10-24 20:55:58.508:WARN:oejsh.RequestLogHandler:main: !RequestLog
    2014-10-24 20:55:58.526:WARN:oejuc.AbstractLifeCycle:main: FAILED ServerConnector@45c01e6{HTTP/1.1}{0.0.0.0:8080}: java.net.BindException: Address already in use: bind
    java.net.BindException: Address already in use: bind


////// minimize the error log.......

    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
    2014-10-24 20:55:58.526:WARN:oejuc.AbstractLifeCycle:main: FAILED org.eclipse.jetty.maven.plugin.MavenServerConnector@3480a546: java.net.BindException: Address already in use: bind
    java.net.BindException: Address already in use: bind

///// minimize the error log..........
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
2014-10-24 20:55:58.526:WARN:oejuc.AbstractLifeCycle:main: FAILED org.eclipse.jetty.maven.plugin.JettyServer@26ed15da: java.net.BindException: Address already in use: bind
java.net.BindException: Address already in use: bind

///// at last in error log

[INFO] Jetty server exiting.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 7.172s
[INFO] Finished at: Fri Oct 24 20:55:58 IST 2014
[INFO] Final Memory: 31M/260M

[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.eclipse.jetty:jetty-maven-plugin:9.2.3.v20140905:run (default-cli) on project mit-site-temp: Failure: Address already in use: bind -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

请帮我解决这个问题

3 个答案:

答案 0 :(得分:0)

看起来你正在依赖依赖。如果您是Java新手,请尝试阅读错误消息,这将对您有所帮助。只是谷歌“无法加载类”org.slf4j.impl.StaticLoggerBinder“”,你会发现很多帖子。您需要在pom.xml中添加公共日志记录依赖项。同上,问题的标题不相关。你实际上有构建问题,数据源将是下一步。希望这会有所帮助。

编辑: 样本依赖。我仍然建议您查看评论中的链接以更好地理解它。

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.7</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.16</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.1.1</version>
    </dependency>

Bean“transactionManager”定义:

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  <property name="entityManagerFactory" ref="sessionFactory" />
</bean>

答案 1 :(得分:0)

据我所知,你在这里有两个问题:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined

换句话说,你不能在JPA TransactionManager中使用hibernate会话工厂,你必须在简单的Spring + hibernate方法(spring transaction management + hibernate session factory,see outdated exemple here之间做出选择。 ) 要么 Spring + JPAAdapter + JPA(春季JPA交易管理+ JPA entityManagerFactory

要了解两种方法之间的区别,请参阅HibernateTransactionManager or JpaTransactionManager

第二个问题

java.net.BindException: Address already in use: bind

表示服务器预期侦听的http端口已被其他程序使用(使用TCPView知道哪一个)

答案 2 :(得分:0)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/YOUR_DATABASE_NAME" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
    </bean>
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.Dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.hbm2ddl.autodll">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
        <property name="packagesToScan">
            <list>
                <value>com.deneme</value>
            </list>
        </property>
    </bean>
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
</beans>