博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring-JDBC实现Contact的CRUD
阅读量:5101 次
发布时间:2019-06-13

本文共 10957 字,大约阅读时间需要 36 分钟。

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

4.0.0
MarkDemo
SpringDAO
0.0.1-SNAPSHOT
org.springframework
spring-core
4.1.1.RELEASE
org.springframework
spring-beans
4.1.1.RELEASE
org.springframework
spring-dao
2.0.8
org.springframework
spring-jdbc
4.1.1.RELEASE
mysql
mysql-connector-java
5.1.33
org.apache.logging.log4j
log4j-core
2.0.2
commons-logging
commons-logging
1.2
org.springframework
spring-context
4.1.1.RELEASE
com.mchange
c3p0
0.9.5-pre9
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

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
{ 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
Search(String name); List
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
Search(String name) { List
contactList = this.getJdbcTemplate().query("select * from contact where name like %?%;", new Object[] { name }, new ContactRowMapper()); return contactList; } public List
getAllContacts() { List
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);    }}

 

转载于:https://www.cnblogs.com/wancy86/p/spring-jdbc.html

你可能感兴趣的文章
骨骼动画编辑器Spine的纹理打包器(texture packer)
查看>>
HashMap 的深入学习
查看>>
FPGA远程更新之限制条件
查看>>
EMI (电磁干扰)
查看>>
composer
查看>>
HashMap,,ConcurrentHashMap------------------浅谈!!
查看>>
mysql8采用caching-sha2-password加密
查看>>
docker images存放路径指定
查看>>
记一次坑爹的广工校赛
查看>>
UVA232
查看>>
文件读写操作
查看>>
[HNOI2015] 亚瑟王
查看>>
php安装oci8和pdo_oci扩展实现连接oracle数据库
查看>>
request.get_full_path() 和request.path区别
查看>>
SQL数据库的多表查询
查看>>
SQL动态配置,动态解析SQL
查看>>
接口安全性思考
查看>>
C/C++/JAVA内存布局
查看>>
WinPhone 开发(2)-----应用程序栏ApplicationBar
查看>>
六、数组类的创建
查看>>