mysql jdbc example_Spring + JDBC example

In this tutorial, we will extend last Maven + Spring hello world example by adding JDBC support, to use Spring + JDBC to insert a record into a customer table.

1. Customer table

In this example, we are using MySQL database.

CREATE TABLE`customer` (

`CUST_ID`int(10) unsigned NOT NULLAUTO_INCREMENT,

`NAME`varchar(100) NOT NULL,

`AGE`int(10) unsigned NOT NULL,PRIMARY KEY(`CUST_ID`)

) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

2. Project Dependency

Add Spring and MySQL dependencies in Maven pom.xml file.

File : pom.xml

http://maven.apache.org/maven-v4_0_0.xsd">

4.0.0

com.mkyong.common

SpringExample

jar

1.0-SNAPSHOT

SpringExample

http://maven.apache.org

org.springframework

spring

2.5.6

mysql

mysql-connector-java

5.1.9

3. Customer model

Add a customer model to store customer’s data.

packagecom.mkyong.customer.model;importjava.sql.Timestamp;public classCustomer

{intcustId;

String name;intage;//getter and setter methods

}

4. Data Access Object (DAO) pattern

Customer Dao interface.

packagecom.mkyong.customer.dao;importcom.mkyong.customer.model.Customer;public interfaceCustomerDAO

{public voidinsert(Customer customer);public Customer findByCustomerId(intcustId);

}

Customer Dao implementation, use JDBC to issue a simple insert and select statement.

packagecom.mkyong.customer.dao.impl;importjava.sql.Connection;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importjavax.sql.DataSource;importcom.mkyong.customer.dao.CustomerDAO;importcom.mkyong.customer.model.Customer;public class JdbcCustomerDAO implementsCustomerDAO

{privateDataSource dataSource;public voidsetDataSource(DataSource dataSource) {this.dataSource =dataSource;

}public voidinsert(Customer customer){

String sql= "INSERT INTO CUSTOMER " +

"(CUST_ID, NAME, AGE) VALUES (?, ?, ?)";

Connection conn= null;try{

conn=dataSource.getConnection();

PreparedStatement ps=conn.prepareStatement(sql);

ps.setInt(1, customer.getCustId());

ps.setString(2, customer.getName());

ps.setInt(3, customer.getAge());

ps.executeUpdate();

ps.close();

}catch(SQLException e) {throw newRuntimeException(e);

}finally{if (conn != null) {try{

conn.close();

}catch(SQLException e) {}

}

}

}public Customer findByCustomerId(intcustId){

String sql= "SELECT * FROM CUSTOMER WHERE CUST_ID = ?";

Connection conn= null;try{

conn=dataSource.getConnection();

PreparedStatement ps=conn.prepareStatement(sql);

ps.setInt(1, custId);

Customer customer= null;

ResultSet rs=ps.executeQuery();if(rs.next()) {

customer= newCustomer(

rs.getInt("CUST_ID"),

rs.getString("NAME"),

rs.getInt("Age")

);

}

rs.close();

ps.close();returncustomer;

}catch(SQLException e) {throw newRuntimeException(e);

}finally{if (conn != null) {try{

conn.close();

}catch(SQLException e) {}

}

}

}

}

5. Spring bean configuration

Create the Spring bean configuration file for customerDAO and datasource.

File : Spring-Customer.xml

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

File : Spring-Datasource.xml

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

File : Spring-Module.xml

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

6. Review project structure

Full directory structure of this example.

d21350ed2e95bcb2fd6ae76ab49a0ac6.png

7. Run it

package com.mkyong.common;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mkyong.customer.dao.CustomerDAO;

import com.mkyong.customer.model.Customer;

public class App

{

public static void main( String[] args )

{

ApplicationContext context =

new ClassPathXmlApplicationContext("Spring-Module.xml");

CustomerDAO customerDAO = (CustomerDAO) context.getBean("customerDAO");

Customer customer = new Customer(1, "mkyong",28);

customerDAO.insert(customer);

Customer customer1 = customerDAO.findByCustomerId(1);

System.out.println(customer1);

}

}

output

Customer [age=28, custId=1, name=mkyong]

转 : https://mkyong.com/spring/maven-spring-jdbc-example/

实现定时任务可以使用Quartz框架,结合Spring MVC进行整合。下面是具体步骤: 1. 引入依赖 在pom.xml中添加依赖: ``` <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency> ``` 2. 配置Quartz 在Spring的配置文件中添加Quartz的配置,如下: ``` <!--配置Quartz--> <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="quartzProperties"> <props> <prop key="org.quartz.scheduler.instanceName">QuartzScheduler</prop> <prop key="org.quartz.scheduler.instanceId">AUTO</prop> <prop key="org.quartz.scheduler.skipUpdateCheck">true</prop> <prop key="org.quartz.scheduler.jmx.export">true</prop> <prop key="org.quartz.jobStore.class">org.quartz.impl.jdbcjobstore.JobStoreTX</prop> <prop key="org.quartz.jobStore.driverDelegateClass">org.quartz.impl.jdbcjobstore.StdJDBCDelegate</prop> <prop key="org.quartz.jobStore.dataSource">myDS</prop> <prop key="org.quartz.jobStore.tablePrefix">QRTZ_</prop> <prop key="org.quartz.jobStore.isClustered">false</prop> <prop key="org.quartz.threadPool.class">org.quartz.simpl.SimpleThreadPool</prop> <prop key="org.quartz.threadPool.threadCount">10</prop> <prop key="org.quartz.dataSource.myDS.driver">com.mysql.jdbc.Driver</prop> <prop key="org.quartz.dataSource.myDS.URL">jdbc:mysql://localhost:3306/quartz?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true</prop> <prop key="org.quartz.dataSource.myDS.user">root</prop> <prop key="org.quartz.dataSource.myDS.password">123456</prop> <prop key="org.quartz.dataSource.myDS.maxConnections">30</prop> </props> </property> <property name="autoStartup" value="true"/> <property name="startupDelay" value="5"/> </bean> ``` 这里配置了Quartz的数据源,使用的是MySQL数据库。 3. 编写定时任务 创建一个类,实现Quartz的Job接口,如下: ``` public class MyJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("定时任务执行了"); } } ``` 4. 配置定时任务 在Spring的配置文件中添加对定时任务的配置,如下: ``` <!-- 配置定时任务 --> <bean id="myJobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean"> <property name="jobClass" value="com.example.MyJob"/> </bean> <bean id="myJobTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail" ref="myJobDetail"/> <property name="cronExpression" value="0/5 * * * * ?"/> </bean> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="myJobTrigger"/> </list> </property> <property name="schedulerContextAsMap"> <map> <entry key="key1" value="value1"/> <entry key="key2" value="value2"/> </map> </property> <property name="schedulerListeners"> <list> <bean class="org.springframework.scheduling.quartz.JobListenerFactoryBean"> <property name="name" value="jobListener"/> </bean> </list> </property> </bean> ``` 这里配置了一个每5秒执行一次的定时任务。 5. 启动定时任务 在启动Spring的时候,定时任务会自动启动。也可以在代码中手动启动定时任务,如下: ``` @Autowired private Scheduler scheduler; /** * 启动定时任务 */ public void startJob() throws SchedulerException { scheduler.start(); } ``` 至此,一个使用Spring MVC和Quartz实现的定时任务就完成了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值