Spring Object/XML mapping 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 NULL AUTO_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
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.common</groupId>
<artifactId>SpringExample</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>SpringExample</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
<!-- MySQL database driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
</dependencies>
</project>
3. Customer model
Add a customer model to store customer’s data.
package com.mkyong.customer.model;
import java.sql.Timestamp;
public class Customer
{
int custId;
String name;
int age;
//getter and setter methods
}
4. Data Access Object (DAO) pattern
Customer Dao interface.
package com.mkyong.customer.dao;
import com.mkyong.customer.model.Customer;
public interface CustomerDAO
{
public void insert(Customer customer);
public Customer findByCustomerId(int custId);
}
Customer Dao implementation, use JDBC to issue a simple insert and select statement.
package com.mkyong.customer.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mkyong.customer.dao.CustomerDAO;
import com.mkyong.customer.model.Customer;
public class JdbcCustomerDAO implements CustomerDAO
{
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void insert(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 new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
public Customer findByCustomerId(int custId){
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 = new Customer(
rs.getInt("CUST_ID"),
rs.getString("NAME"),
rs.getInt("Age")
);
}
rs.close();
ps.close();
return customer;
} catch (SQLException e) {
throw new RuntimeException(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
<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-2.5.xsd">
<bean id="customerDAO" class="com.mkyong.customer.dao.impl.JdbcCustomerDAO">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
File : Spring-Datasource.xml
<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-2.5.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:3306/mkyongjava" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
</beans>
File : Spring-Module.xml
<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-2.5.xsd">
<import resource="database/Spring-Datasource.xml" />
<import resource="customer/Spring-Customer.xml" />
</beans>
6. Review project structure
Full directory structure of this example.
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]
Spring Object/XML mapping example的更多相关文章
- [Java] 解决spring的xml标签内不能自由增加说明的难题,方便调试、部署时进行批量屏蔽
作者:zyl910 以往我们想在spring的xml配置文件中增加说明文本时,只能使用xml注释(<!-- 注释 -->).这对于"调试.部署时想批量屏蔽部分bean" ...
- Spring 通过XML配置文件以及通过注解形式来AOP 来实现前置,环绕,异常通知,返回后通知,后通知
本节主要内容: 一.Spring 通过XML配置文件形式来AOP 来实现前置,环绕,异常通知 1. Spring AOP 前置通知 XML配置使用案例 2. Spring AOP ...
- Spring AOP:面向切面编程,AspectJ,是基于spring 的xml文件的方法
导包等不在赘述: 建立一个接口:ArithmeticCalculator,没有实例化的方法: package com.atguigu.spring.aop.impl.panpan; public in ...
- Spring读取xml配置文件的原理与实现
本篇博文的目录: 一:前言 二:spring的配置文件 三:依赖的第三方库.使用技术.代码布局 四:Document实现 五:获取Element的实现 六:解析Element元素 七:Bean创造器 ...
- Spring的xml解析原理分析【转载】
一:前言 二:spring的配置文件 三:依赖的第三方库.使用技术.代码布局 四:Document实现 五:获取Element的实现 六:解析Element元素 七:Bean创造器 八:Ioc容器的创 ...
- spring+mybaits xml配置解析----转
一.项目中spring+mybaits xml配置解析 一般我们会在datasource.xml中进行如下配置,但是其中每个配置项原理和用途是什么,并不是那么清楚,如果不清楚的话,在使用时候就很有可能 ...
- Object Relational Mapping框架之Hibernate
hibernate框架简介: hibernate框架就是开发中在持久层中应用居多的ORM框架,它对JDBC做了轻量级的封装. (百度介绍,感觉不错) 什么是ORM:Object Relational ...
- spring mvc: xml生成
spring mvc: xml生成 准备: javax.xml.bind.annotation.XmlElement; javax.xml.bind.annotation.XmlRootElement ...
- ORM(Object Relational Mapping)框架
ORM(Object Relational Mapping)框架 ORM(Object Relational Mapping)框架采用元数据来描述对象一关系映射细节,元数据一般采用XML格式,并且存放 ...
随机推荐
- MacOS安装phpMyAdmin几点问题
1. 登录时出现“#2002 无法登录 MySQL 服务器”. 原因: phpMyAdmin为PHP编写,MacOS默认安装的php配置,设置mysql监听socket默认为/var/mysql/my ...
- URAL 1992
CVS Description Yoda: Visit I will the cloners on Kamino... And see this army they have created for ...
- EF DataBase First生成model的验证
如何避免在EF自动生成的model中的DataAnnotation被覆盖掉 相信很多人刚接触EF+MVC的时候,DataBase First模式生成model类中加验证信息的时候,会在重新生成mode ...
- Java [Leetcode 171]Excel Sheet Column Number
题目描述: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 解题思路: 循环读取数字,从左向右读取,每次该位字 ...
- 【转】Android Studio -修改LogCat的颜色*美爆了*
原文网址:http://www.2cto.com/kf/201505/400357.html 一. 先看效果 二.设置 File->Settings 或Ctrl + Alt +S 找到 Edit ...
- JS调试必备的5个debug技巧
我一直使用printf调试程序,一般来说都是比较顺利,但有时候,你会发现需要更好的方法.下面几个JavaScript技巧相信你一定会觉得十分有用 1. debugger; 我以前也说过,你可以在J ...
- javascript的setTimeout()用法总结,js的setTimeout()方法
引子 js的setTimeout方法用处比较多,通常用在页面刷新了.延迟执行了等等.但是很多javascript新手对setTimeout的用法还是不是很了解.虽然我学习和应用javascript已经 ...
- IT版孔乙己(转)
[不要做学究]回忆孔先生IT版 我关于本文评价:看到这篇文章很多人会生出这样的疑问“这明明是在诋毁钻研技术的人嘛?是不是在宣扬技术无用论?”. 初看这篇文章的时候我也是这样的想法,但是逐步才明白这篇文 ...
- codedorces 260 div2 A题
水题,扫描一遍看是否出现价格低质量高的情况. #include<cstdio> #include<string> #include<vector> #include ...
- OnItemClickListener 的参数详解(转)
转载地址:http://blog.iamzsx.me/show.html?id=147001 我们在使用ListView的时候,一般都会为ListView添加一个响应事件android.widget. ...