首页 > 代码库 > Spring-JDBC实践

Spring-JDBC实践

Spring-JDBC完成Contact的CRUD。

两点注意:

  1.log4j.properties文件不能少

  2.注意导入的包之间的依赖关系以及版本要求。

 

项目结构:

 

主要文件:

建表脚本:

CREATE TABLE contact (  id int(10) unsigned NOT NULL auto_increment,  name varchar(45) NOT NULL,  address varchar(45) default NULL,  gender char(1) default M,  dob datetime default NULL,  email varchar(45) default NULL,  mobile varchar(15) default NULL,  phone varchar(15) default NULL,  PRIMARY KEY  (id)) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8

 

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/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>MarkDemo</groupId>    <artifactId>SpringDAO</artifactId>    <version>0.0.1-SNAPSHOT</version>    <build />    <dependencies>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-core</artifactId>            <version>4.1.1.RELEASE</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-beans</artifactId>            <version>4.1.1.RELEASE</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-dao</artifactId>            <version>2.0.8</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-jdbc</artifactId>            <version>4.1.1.RELEASE</version>        </dependency>        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <version>5.1.33</version>        </dependency>        <dependency>            <groupId>org.apache.logging.log4j</groupId>            <artifactId>log4j-core</artifactId>            <version>2.0.2</version>        </dependency>        <dependency>            <groupId>commons-logging</groupId>            <artifactId>commons-logging</artifactId>            <version>1.2</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-context</artifactId>            <version>4.1.1.RELEASE</version>        </dependency>        <dependency>            <groupId>com.mchange</groupId>            <artifactId>c3p0</artifactId>            <version>0.9.5-pre9</version>        </dependency>    </dependencies></project>
View Code

properties文件

jdbc.properties------------------------------------mysql.driverClassName=com.mysql.jdbc.Drivermysql.url=jdbc:mysql://localhost:3306/testmysql.username=rootmysql.password=111222log4j.properties# Configure logging for testing: optionally with log filelog4j.rootLogger=WARN, stdout# log4j.rootLogger=WARN, stdout, logfilelog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%nlog4j.appender.logfile=org.apache.log4j.FileAppenderlog4j.appender.logfile.File=target/spring.loglog4j.appender.logfile.layout=org.apache.log4j.PatternLayoutlog4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n 

 

spring-dao.xml

<?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:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:mvc="http://www.springframework.org/schema/mvc"    xsi:schemaLocation="http://www.springframework.org/schema/beans                http://www.springframework.org/schema/beans/spring-beans-4.1.xsd               http://www.springframework.org/schema/context               http://www.springframework.org/schema/context/spring-context-4.1.xsd               http://www.springframework.org/schema/tx             http://www.springframework.org/schema/tx/spring-tx-4.1.xsd            http://www.springframework.org/schema/mvc             http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">    <!-- not  property-placeholder -->    <!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"         p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/test"         p:username="root" p:password="111222" /> -->            <context:property-placeholder location="classpath:jdbc.properties" />    <!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"         p:driverClassName="${mysql.driverClassName}" p:url="${mysql.url}" p:username="${mysql.username}"         p:password="${mysql.password}" />. -->    <!-- c3p0 -->    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">        <property name="user" value="${mysql.username}" />        <property name="password" value="${mysql.password}" />        <property name="driverClass" value="${mysql.driverClassName}" />        <property name="jdbcUrl" value="${mysql.url}" />        <property name="maxPoolSize" value="20" />        <property name="minPoolSize" value="2" />        <property name="initialPoolSize" value="2"/>        <property name="maxIdleTime" value="60"/>    </bean></beans>
View Code

 

Contact.java
import java.sql.Date;public class Contact {    private Integer id;    private String name;    private String address;    private String gender;    private Date dob;    private String email;    private String mobile;    private String phone;    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getAddress() {        return address;    }    public void setAddress(String address) {        this.address = address;    }    public String getGender() {        return gender;    }    public void setGender(String gender) {        this.gender = gender;    }    public Date getDob() {        return dob;    }    public void setDob(Date dob) {        this.dob = dob;    }    public String getEmail() {        return email;    }    public void setEmail(String email) {        this.email = email;    }    public String getMobile() {        return mobile;    }    public void setMobile(String mobile) {        this.mobile = mobile;    }    public String getPhone() {        return phone;    }    public void setPhone(String phone) {        this.phone = phone;    }}

 

ContactRowMapper.java
--ContactRowMapper.javaimport java.sql.ResultSet;import java.sql.SQLException;import org.springframework.jdbc.core.RowMapper;public class ContactRowMapper implements RowMapper<Contact> {    public Contact mapRow(ResultSet arg0, int arg1) throws SQLException {                Contact contact = new Contact();        contact.setId(arg0.getInt("id"));        contact.setName(arg0.getString("name"));        contact.setAddress(arg0.getString("address"));        contact.setGender(arg0.getString("gender"));        contact.setDob(arg0.getDate("dob"));        contact.setEmail(arg0.getString("email"));        contact.setMobile(arg0.getString("mobile"));        contact.setPhone(arg0.getString("phone"));        return contact;    }}

 

ContactsDAO.java
--ContactsDAO.javaimport java.util.List;public interface ContactsDAO {    Contact getContact(Integer id);    Integer Create(Contact contact);    Boolean Update(Contact contact);    Boolean Delete(Integer id);    List<Contact> Search(String name);    List<Contact> getAllContacts();}

 

ContactsDAOImpl.java
--ContactsDAOImpl.javaimport java.sql.Connection;import java.sql.Date;import java.sql.PreparedStatement;import java.sql.SQLException;import java.sql.Statement;import java.util.List;import org.springframework.jdbc.core.PreparedStatementCreator;import org.springframework.jdbc.core.support.JdbcDaoSupport;import org.springframework.jdbc.support.GeneratedKeyHolder;import org.springframework.jdbc.support.KeyHolder;public class ContactsDAOImpl extends JdbcDaoSupport implements ContactsDAO {    public Contact getContact(Integer id) {        Contact contact = this.getJdbcTemplate().queryForObject("select * from contact where id=?", new Object[] { id }, new ContactRowMapper());        return contact;    }    /**     * Add a new contact to database, and return the id.     *      * @author Mark     * @param Object     *            of Contact     * @return [Integer] Auto Increment Key     * @see http://blog.chinaunix.net/uid-1848701-id-2825787.html     * */    public Integer Create(Contact contact) {        final Contact contact2;        contact2 = contact;        if (contact.getId() != null)            throw new RuntimeException("contact with id " + contact.getId() + " is already existed.");//        Object[] params = new Object[] { contact.getName(), contact.getAddress(), contact.getGender(), contact.getDob(), contact.getEmail(),//                contact.getMobile(), contact.getPhone() };//        int id = this.getJdbcTemplate().update("insert into contact(name, address, gender, dob, email, mobile, phone) values(?,?,?,?,?,?,?);", params);                final String strSql = "insert into contact(name, address, gender, dob, email, mobile, phone) values(?,?,?,?,?,?,?);";        KeyHolder keyHolder = new GeneratedKeyHolder();        int id1 = this.getJdbcTemplate().update(new PreparedStatementCreator() {            public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {                int i = 0;                java.sql.PreparedStatement ps = conn.prepareStatement(strSql, new String[] { "object_id" });                ps = conn.prepareStatement(strSql, Statement.RETURN_GENERATED_KEYS);                ps.setString(++i, contact2.getName());                ps.setString(++i, contact2.getAddress());                ps.setString(++i, contact2.getGender());                ps.setDate(++i, (Date) contact2.getDob());                ps.setString(++i, contact2.getEmail());                ps.setString(++i, contact2.getMobile());                ps.setString(++i, contact2.getPhone());                return ps;            }        }, keyHolder);        return keyHolder.getKey().intValue();    }    public Boolean Update(Contact contact) {        Object[] param = new Object[] { contact.getName(), contact.getAddress(), contact.getGender(), contact.getDob(), contact.getEmail(),                contact.getMobile(), contact.getPhone(), contact.getId() };        int count = this.getJdbcTemplate().update("update contact set name=?, address=?, gender=?, dob=?, email=?, mobile=?, phone=? where id=?", param);        return count > 0 ? Boolean.TRUE : Boolean.FALSE;    }    public Boolean Delete(Integer id) {        int count = this.getJdbcTemplate().update("delete from contact where id=?;", new Object[] { id });        return count > 0 ? Boolean.TRUE : Boolean.FALSE;    }    public List<Contact> Search(String name) {        List<Contact> contactList = this.getJdbcTemplate().query("select * from contact where name like %?%;", new Object[] { name }, new ContactRowMapper());        return contactList;    }    public List<Contact> getAllContacts() {        List<Contact> contactList = this.getJdbcTemplate().query("select * from contact;", new ContactRowMapper());        return contactList;    }}

 

ContactsDAOTestClient.java
--ContactsDAOTestClient.javaimport org.springframework.context.ApplicationContext;import java.sql.Date;import javax.sql.DataSource;import org.springframework.context.support.ClassPathXmlApplicationContext;public class ContactsDAOTestClient {    @SuppressWarnings("deprecation")    public static void main(String[] args) {        System.out.println("hello jdbc, see you tomorrow.");        ApplicationContext applicationContext = null;                try {            applicationContext = new ClassPathXmlApplicationContext("classpath:spring-dao.xml");        } catch (Exception e) {            e.printStackTrace();        }        DataSource dataSource = (DataSource) applicationContext.getBean("dataSource");        ContactsDAOImpl contactDao = new ContactsDAOImpl();        contactDao.setDataSource(dataSource);            Contact contact = new Contact();        contact.setName("MARK");        contact.setAddress("WITH HOUSE");        contact.setGender("M");        contact.setDob(new Date(1986,11,07));        contact.setEmail("wancy86@sina.com");        contact.setMobile("13028865078");        contact.setPhone("0755-06326545");         //add a new contact        int id=contactDao.Create(contact);                //get the inserted contact        contactDao.getContact(id);                System.out.println(id);    }}

 

Spring-JDBC实践