简体   繁体   中英

Connecting to MySQL using Java

I currently have Spring configured to use HSQL, but I would like to use MySQL. What needs to change?

<?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>

Change the following properties:

    <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>

(where 'schema' is your mysql database name, assuming your mysql host is 127.0.0.1)

And add the mysql-connector jar to your classpath.

You'd have to change the driverClass and url properties of the DataSource .

driverClass should be com.mysql.jdbc.Driver
url should be jdbc:mysql://localhost:3306/dbname

A good example of using mysql with java in spring is detailed on the mysql website

The hibernate should be as noted in the answer by ivy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM