做一个简单的有数据库的maven项目,目前还是没有前端,而且没有使用mybatis。之后会向项目中添加。
图片
对于上图的说明,第一个大的表格是未运行测试程序数据表的内容,第二个大的表格是运行测试程序后数据表的内容。
此例子在http://www.cnblogs.com/hongten/archive/2012/03/09/java_spring_jdbc.html的基础上进行修改,链接中的网页的缺憾在于没有给出如何建立数据库和表的语句。
由于使用了maven工程,所以更容易添加jar包。
接下来对此例子进行详细的说明。
从最开始的pom文件开始进行说明
<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.spring</groupId> <artifactId>mavenSpringJdbc</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>mavenSpringJdbc Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.19</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>3.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.0.5.RELEASE</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>3.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>3.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.apache.geronimo.specs</groupId> <artifactId>geronimo-servlet_2.5_spec</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.0.5.RELEASE</version> </dependency> </dependencies> <build> <finalName>mavenSpringJdbc</finalName> </build> <properties> <springVersion>3.2.5.RELEASE</springVersion> </properties> </project>
在pom文件中之前忘了添加commons-dbcp这个文件。
在原来的例子中没有建表语句。将这个缺陷不上。
观察bean.xml文件中关于数据库连接的部分,
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.gjt.mm.mysql.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=UTF-8" /> <property name="username" value="root" /> <property name="password" value="root" /> <!-- 连接池启动时的初始值 --> <property name="initialSize" value="1" /> <!-- 连接池的最大值 --> <property name="maxActive" value="300" /> <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 --> <property name="maxIdle" value="2" /> <!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 --> <property name="minIdle" value="1" /> </bean>
其中
<property name="url" value="jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=UTF-8" />
这个说明在mysql中建立了一个spring的数据库
CREATE DATABASE spring DEFAULT CHARACTER SET utf8;
USE spring;
建立了表后,建数据库。javabean是这个样子的
package com.b510.bean; /** * 普通的javaBean类Person * * @author Hongten * */ public class Person { /** * id号 */ private int id; /** * 姓名 */ private String name; /** * 年龄 */ private int age; /** * 性别 */ private String sex; public Person(int id, String name, int age, String sex) { this.id = id; this.name = name; this.age = age; this.sex = sex; } public Person() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
表的信息如下:
建表语句:
CREATE TABLE person(
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30),
age INT,
sex VARCHAR(30)
)ENGINE=InnoDB;
之后需要给表中插入数据,本例子需要插入最少七个数据,插入数据语句如下:
INSERT INTO person(id,name,age,sex)VALUES(1,'乔峰',36,'男');
之后就是spring的内容了。先将文件列举如下:
package com.b510.service; import java.util.List; import com.b510.bean.Person; public interface PersonService { /** * 保存Person * * @param person */ public abstract void save(Person person); /** * 更新Person * * @param person */ public abstract void update(Person person); /** * 获取Person * * @param id * @return */ public abstract Person getPerson(Integer id); /** * 获取所有Person * * @return */ public abstract List<Person> getPerson(); /** * 删除指定id的Person * * @param id */ public abstract void delete(Integer id); }
package com.b510.service.impl; import java.util.List; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import com.b510.bean.Person; import com.b510.service.PersonService; /** * 业务bean * * @author Hongten * */ public class PersonServiceBean implements PersonService { /** * 数据源 */ private DataSource dataSource; /** * spring提供的jdbc操作辅助类 */ private JdbcTemplate jdbcTemplate; // 设置数据源 public void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } public void save(Person person) { jdbcTemplate.update("insert into person(name,age,sex)values(?,?,?)", new Object[] { person.getName(), person.getAge(), person.getSex() }, new int[] { java.sql.Types.VARCHAR, java.sql.Types.INTEGER, java.sql.Types.VARCHAR }); } public void update(Person person) { jdbcTemplate.update("update person set name=?,age=?,sex=? where id=?", new Object[] { person.getName(), person.getAge(), person.getSex(), person.getId() }, new int[] { java.sql.Types.VARCHAR, java.sql.Types.INTEGER, java.sql.Types.VARCHAR, java.sql.Types.INTEGER }); } public Person getPerson(Integer id) { Person person = (Person) jdbcTemplate.queryForObject( "select * from person where id=?", new Object[] { id }, new int[] { java.sql.Types.INTEGER }, new PersonRowMapper()); return person; } @SuppressWarnings("unchecked") public List<Person> getPerson() { List<Person> list = jdbcTemplate.query("select * from person", new PersonRowMapper()); return list; } public void delete(Integer id) { jdbcTemplate.update("delete from person where id = ?", new Object[] { id }, new int[] { java.sql.Types.INTEGER }); } }
package com.b510.service.impl; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import com.b510.bean.Person; public class PersonRowMapper implements RowMapper { public Object mapRow(ResultSet set, int index) throws SQLException { Person person = new Person(set.getInt("id"), set.getString("name"), set .getInt("age"), set.getString("sex")); return person; } }
package com.b510.test; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.b510.bean.Person; import com.b510.service.PersonService; public class SpringJDBCTest { public static void main(String[] args) { ApplicationContext act = new ClassPathXmlApplicationContext("bean.xml"); PersonService personService = (PersonService) act .getBean("personService"); Person person = new Person(); person.setName("苏东坡"); person.setAge(21); person.setSex("男"); // 保存一条记录 personService.save(person); List<Person> person1 = personService.getPerson(); System.out.println("++++++++得到所有Person"); for (Person person2 : person1) { System.out.println(person2.getId() + " " + person2.getName() + " " + person2.getAge() + " " + person2.getSex()); } Person updatePerson = new Person(); updatePerson.setName("Divide"); updatePerson.setAge(20); updatePerson.setSex("男"); updatePerson.setId(5); // 更新一条记录 personService.update(updatePerson); System.out.println("******************"); // 获取一条记录 Person onePerson = personService.getPerson(2); System.out.println(onePerson.getId() + " " + onePerson.getName() + " " + onePerson.getAge() + " " + onePerson.getSex()); // 删除一条记录 personService.delete(1); } }
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!--配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.gjt.mm.mysql.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=UTF-8" /> <property name="username" value="root" /> <property name="password" value="root" /> <!-- 连接池启动时的初始值 --> <property name="initialSize" value="1" /> <!-- 连接池的最大值 --> <property name="maxActive" value="300" /> <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 --> <property name="maxIdle" value="2" /> <!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 --> <property name="minIdle" value="1" /> </bean> <!-- 采用注解方式来配置事务。针对数据源的事务管理器 ,把我们定义的数据源注入到DataSourceTransactionManager类的属性dataSource中 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 引入命名空间: 1.xmlns:tx="http://www.springframework.org/schema/tx 2.http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 采用@Transaction注解方式使用事务管理器 --> <tx:annotation-driven transaction-manager="txManager" /> <!-- 配置业务bean:PersonServiceBean --> <bean id="personService" class="com.b510.service.impl.PersonServiceBean"> <!-- 向属性dataSource注入数据源 --> <property name="dataSource" ref="dataSource"></property> </bean> </beans>
然后运行测试类就可以得到结果了。
搭建此例子就可以之后具体分析如何写这样的例子了。