I am trying to connect to a mysql database on my first Spring Project and I seem to be overlooking something really simple.
I have this bean in my application-context.xml file which is commented out!
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
I know this is going to sound stupid, but in order to create a class that connects to a Mysql database using JDBC and the or the Spring JDBCTemplate, what do I do from here?
I am confused about how to populate properties in the bean above, do I do it in a superclass like this and then extend my subclasses from it.
import org.springframework.jdbc.datasource.DriverManagerDataSource;
public class JdbcDao {
protected DriverManagerDataSource dataSource = new DriverManagerDataSource();
JdbcDao(){
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost/db_name");
dataSource.setUsername("bcash");
dataSource.setPassword("");
}
}
I am confused so any help is truly apprecated,
Many Thanks
See JdbcTemplate Best Practices for further info.
Nutshell: no, your DAO wouldn’t create a new datasource via
new; that defeats the purpose of using Spring. Implementations should be injected, not instantiated directly; roughly:Then in your Spring config (if not using annotations), also roughly:
(This uses a setter; you could also use an annotation and skip the XML config.)
You could also use JdbcTemplate as your base class and save more energy.
I recommend going over the Data access with JDBC reference docs (if you’re using JDBC), or the corresponding section that deals directly with your ORM choice.