Spring integrates JDBC for simple addition, deletion, and modification, and spring integrates jdbc for addition and deletion.

Source: Internet
Author: User

Spring integrates JDBC for simple addition, deletion, and modification, and spring integrates jdbc for addition and deletion.

Spring integrates JDBC to implement simple addition, deletion, and modification:

1. Import the Spring package and the driver package of the database;
2. Select a data source (dbcp and C3P0)
3. Import the data source package (dbcp is used here)

<span style="font-family:FangSong_GB2312;font-size:14px;">commons-pool-1.5.6.jar 、commons-dbcp-1.4.jar(jdk6+)</span>

4. Create a dataSource data source in beans. xml
5. Create a jdbc. properties file to store database connection information
6. Import the corresponding jdbc. properties file in beans. xml.
<span style="font-family:FangSong_GB2312;font-size:14px;"><context:property-placeholder location="jdbc.properties" /></span>


7. Write the corresponding DAO and create a JdbcTemplate object for the DAO. The JdbcTemplate object can be used to conveniently perform database operations.
8. Inject corresponding DateSource into DAO and create JdbcTemplate

/** * Set the JDBC DataSource to obtain connections from. */@Resourcepublic void setDataSource(DataSource dataSource) {JdbcTemplate=new JdbcTemplate(dataSource);}

9. Add Data Objects

Specific implementation process:

XML configuration:

<? 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" xsi: schemaLocation = "http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsdhttp://www.springframework.org/schema/beans http: // ww Export springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd "> <! -- Enable Spring's Annotation support --> <context: annotation-config/> <! -- Set which packages Spring uses to find Annotation --> <context: component-scan base-package = "org. oms. spring"/> <! -- Create a data source --> <bean id = "dataSource" class = "org. apache. commons. dbcp. basicDataSource "destroy-method =" close "> <property name =" driverClassName "value =" $ {jdbc. driverClassName} "/> <property name =" url "value =" $ {jdbc. url} "/> <property name =" username "value =" $ {jdbc. username} "/> <property name =" password "value =" $ {jdbc. password} "/> </bean> <! -- Import jdbc. properties under src --> <context: property-placeholder location = "jdbc. properties"/> </beans>



Jdbc. properties

jdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/dbnamejdbc.username=rootjdbc.password=root


Mode class, User

package org.oms.spring.model;import java.util.Date;public class User {private int id;private String username;private String password;private Group group;private int age;private Date birthDay;private Date createDate;public int getId() {return id;}public void setId(int id) {this.id = id;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Date getBirthDay() {return birthDay;}public void setBirthDay(Date birthDay) {this.birthDay = birthDay;}public Date getCreateDate() {return createDate;}public void setCreateDate(Date createDate) {this.createDate = createDate;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public Group getGroup() {return group;}public void setGroup(Group group) {this.group = group;}public User() {super();}public User(String username, String password, int age,Date birthDay, Date createDate) {super();this.username = username;this.password = password;this.age = age;this.birthDay = birthDay;this.createDate = createDate;}@Overridepublic String toString() {return "User [id=" + id + ", username=" + username + ", password="+ password + ", group=" + group + ", age=" + age+ ", birthDay=" + birthDay + ", createDate=" + createDate + "]";}}

Group Class

package org.oms.spring.model;public class Group {private int id;private String name;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 Group(String name) {super();this.name = name;}public Group() {super();}@Overridepublic String toString() {return "Group [id=" + id + ", name=" + name + "]";}}

The dao class includes interfaces:

package org.oms.spring.dao;import java.util.List;import org.oms.spring.model.User;public interface IUserDao {public void add(User user,int gid);public void update(User user,int gid);public void delete(int id);public User load(int id);public List<User> list(String sql);}package org.oms.spring.dao;import java.util.List;import javax.annotation.Resource;import javax.sql.DataSource;import org.oms.spring.model.User;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Repository;@Repository("userJdbcDao")public class UserDao implements IUserDao {private JdbcTemplate JdbcTemplate;/** * Set the JDBC DataSource to obtain connections from. */@Resourcepublic void setDataSource(DataSource dataSource) {JdbcTemplate=new JdbcTemplate(dataSource);}@Overridepublic void add(User user,int gid) {JdbcTemplate.update("insert into user(username,password,gid,age,birthday,createdate) value (?,?,?,?,?,?)",user.getUsername(),user.getPassword(),gid,user.getAge(),user.getBirthDay(),user.getCreateDate());}@Overridepublic void update(User user,int gid) {JdbcTemplate.update("update user set username=?,password=?,gid=?,age=?,birthday=?,createdate=? where id=?",user.getUsername(),user.getPassword(),gid,user.getAge(),user.getBirthDay(),user.getCreateDate(),user.getId());}@Overridepublic void delete(int id) {JdbcTemplate.update("delete from user where id =?",id);}@Overridepublic User load(int id) {return null;}@Overridepublic List<User> list(String sql) {return null;}}


GroupDao class

Package org. oms. spring. dao; import org. oms. spring. model. group; public interface IGroupDao {public void add (Group group Group);} package org. oms. spring. dao; import java. SQL. preparedStatement; import java. SQL. SQLException; import javax. annotation. resource; import javax. SQL. dataSource; import org. oms. spring. model. group; import org. springframework. jdbc. core. jdbcTemplate; import org. springframework. jdbc. core. preparedSt AtementCreator; import org. springframework. jdbc. support. generatedKeyHolder; import org. springframework. jdbc. support. keyHolder; import org. springframework. stereotype. repository; import com. mysql. jdbc. connection; @ Repository ("groupJdbcDao") public class GroupDao implements IGroupDao {private JdbcTemplate;/*** Set the JDBC DataSource to obtain connections from. * // @ Resourcepublic void setDataS Ource (DataSource dataSource) {JdbcTemplate = new JdbcTemplate (dataSource) ;}@ Overridepublic void add (final Group group) {/*** you can add an object using the following methods, and get the automatically incrementing ID */KeyHolder keyHolder = new GeneratedKeyHolder (); JdbcTemplate in this object. update (new PreparedStatementCreator () {@ Overridepublic PreparedStatement createPreparedStatement (java. SQL. connection con) throws SQLException {String INSERT_ SQL = "insert into 'gro Up '(name) value (?) "; PreparedStatement ps = con. prepareStatement (INSERT_ SQL, new String [] {"id"}); ps. setString (1, group. getName (); return ps ;}}, keyHolder); group. setId (keyHolder. getKey (). intValue ());}}


Test method:

Package org. oms. spring. test; import static org. junit. assert. *; import java. util. date; import javax. annotation. resource; import org. junit. test; import org. junit. runner. runWith; import org. oms. spring. dao. IGroupDao; import org. oms. spring. dao. IUserDao; import org. oms. spring. model. group; import org. oms. spring. model. user; import org. springframework. test. context. contextConfiguration; import org. springframework. test. context. junit4.SpringJUnit4ClassRunner;/*** after the following annotations are used, you can directly inject the dependency into the Test ** @ author sunlight ** // run Junit in the Spring testing environment @ RunWith (SpringJUnit4ClassRunner. class) // load beans. xml file @ ContextConfiguration ("/beans. xml ") public class TestJdbc {@ Resource (name =" userJdbcDao ") private IUserDao userJdbcDao; @ Resource (name =" groupJdbcDao ") private IGroupDao groupJdbcDao; @ Testpublic void testAdd () {Group group = new Group ("test1"); groupJdbcDao. add (group); System. out. println (group. getId (); User user = new User ("I am Spring", "123", 20, new Date (), new Date (); userJdbcDao. add (user, group. getId () ;}@ Testpublic void testUpdate () {User user = new User ("Spring", "123", 20, new Date (), new Date ()); user. setId (2); userJdbcDao. update (user, 1) ;}@ Testpublic void testDel () {userJdbcDao. delete (2 );}}

Test result diagram:


Database Table:

Create table 'user' ('id' int (11) unsigned not null AUTO_INCREMENT COMMENT 'id primary key', 'username' varchar (100) not null default ''comment 'name ', 'Password' varchar (100) default null comment 'Password', 'gid' int (11) default null comment 'group id', 'age' int (11) DEFAULT '18 'comment' ages, 'birthday' date default null comment' birthdate, 'createdate' datetime default null comment' creation time', primary key ('id ')) ENGINE = InnoDB AUTO_INCREMENT = 4 default charset = utf8;

Create table 'group' ('id' int (11) unsigned not null AUTO_INCREMENT, 'name' varchar (100) not null default ''comment' Group name ', primary key ('id') ENGINE = InnoDB AUTO_INCREMENT = 5 default charset = utf8;

Chinese characters in the data table are garbled and sleep for the next explanation at 00:36:54, January 1, September 18, 2014!



Kneeling, JDBC (MySQL) works with Spring's add, delete, modify, and query examples to directly import the project to Myeclipse for running.

Please refer to this article for details.
Reference: www.cnblogs.com/..c.html

Spring, Hibernate, and Jquery are used. The question is how to use the pop-up window to add, delete, modify, and query changes.

What you said has nothing to do with spring and hibernate, that is, the design of the front-end page. You must have a list of products listed on the page. What you want to do is: (1) When a user clicks a product in the product list, the pop-up dialog box lists the information of the product to be clicked in the dialog box; (2) modify the values in the dialog box and click OK in the dialog box. Change the value in the background and respond to the foreground accordingly.

STEP (1): Do not assign values in the click event. Remember to take the id with you. The pure jQuery/javascript code is complete.
In step (2), check whether ajax is required or not. If not, there will be more background forwarding or redirection, that is, click "OK" in the dialog box to submit the form, and a servlet responds to change the Database Value and jump to the same page. If ajax is used, convert the modified value to json or a value that you think is convenient, and put it in response. getOutputstream () (the mvc framework must respond to the page according to the framework), and some value assignment operations are performed in the callback function on the page, update the new value in reponse to the product you just clicked.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.