使用Java连接MySQL

时间:2010-12-21 16:05:27

标签: java mysql spring

我目前已将Spring配置为使用HSQL,但我想使用MySQL。需要改变什么?

<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />

    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
        <property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/>
        <property name="username" value="monty"/>
        <property name="password" value="indian"/>
    </bean>

    <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="annotatedClasses">
            <list>
                <value>uk.co.vinoth.spring.domain.User</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
            </props>
        </property>
    </bean>

    <bean id="myUserDAO" class="uk.co.vinoth.spring.dao.UserDAOImpl">
        <property name="sessionFactory" ref="mySessionFactory"/>
    </bean>

    <bean name="/user/*.htm" class="uk.co.vinoth.spring.web.UserController" >
        <property name="userDAO" ref="myUserDAO" />
    </bean>

</beans>

3 个答案:

答案 0 :(得分:7)

更改以下属性:

    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://127.0.0.1:3306/schema"/>

    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>

(其中'schema'是你的mysql数据库名称,假设你的mysql主机是127.0.0.1)

将mysql-connector jar添加到类路径中。

答案 1 :(得分:1)

您必须更改driverClass的{​​{1}}和url属性。

DataSource应为driverClass
com.mysql.jdbc.Driver应为url

答案 2 :(得分:1)

mysql website

中详细介绍了在Spring中使用mysql和java的一个很好的例子

冬眠应该在常春藤的答案中注明。