Spring and DBCP

Source: Internet
Author: User
Tags aop

Based on JDBC, the operation of the database faster, better than hibernate but the function does not hibernate powerful, adding and removing changes can be used, query with more trouble

Use, first jar package support
Commons-pool.jar
Commons-dbcp.jar
Mysql-connector-java-5.1.12-bin.jar
Add Spring-tx-4.2.0.release to this package on a previous basis.
Base JAR Package


To use DBCP here, the first thing we need to do is to configure spring DataSource the same as this is what we will later use the database main core
<bean id= "DataSource" destroy-method= " Close "class=" Org.apache.commons.dbcp.BasicDataSource "
<property name=" Driverclassname "value=" Com.mysql.jdbc.Driver "/>
<property name=" url "value=" jdbc:mysql://localhost:3306/emp "/>
< Property name= "username" value= "root"/>
<property name= "password" value= "admin"/>
<property name= "Maxactive" value= "ten" ></PROPERTY>
<property name= "InitialSize" value= "2" ></PROPERTY>
<property name= "Minidle" value= "2" ></PROPERTY>
<property name= "Maxidle" value= "3" ></ Property>
</bean>
Explanation:
<property name= "maxactive" value= "ten" ></property> connection pool up to 10 links
<property name= "InitialSize" value= "2" ></property> Pool created 2 links from the beginning
<property name= "Minidle" Value= "2" ></property> min. idle number
<property name= "Maxidle" value= "3" ></property> maximum idle number

After we have configured it, we can use it normally, and in the class we have to first see the dbcp injected into the class.
To complete the injection:
<bean name= "Userdaoimpl" class= "Com.spring.dbcp.UserDaoImpl" >
<property name= "DataSource" ref= "DataSource" ></property>
</bean>

Then you need to get your class to inherit the class Jdbcdaosupport (the simplest way)
public class Userdaoimpl extends Jdbcdaosupport

Last This.getjdbctemplate ()--Get the JDBC template.

But there's a lot of trouble here, because to inherit classes, we have a way of writing that doesn't need to be inherited.
<bean id= "JdbcTemplate" class= "Org.springframework.jdbc.core.JdbcTemplate" >
<property name= "DataSource" ref= "DataSource"/>
</bean>

And then, in our class,
@Resource
private JdbcTemplate template;
So you can get the
Case:
Demonstrate the operation of adding and deleting changes

Note that we have two common parameters for this function function update (sql,new object[]{})----Note that the first argument is an SQL statement, and if there are parameters with placeholders, the second parameter is the position where the placeholder parameter is set


What about our enquiry?
Besides this method, we have
queryForObject (Sql,new usermapper ());---investigate and punish an object in a
queryForList (SQL)---Returns a list array object

Query (SQL,ROWMAPPWE)--search result set

queryForInt (SQL);--Query aggregation function


The trouble here is to query this thing, because the first thing it needs is a mapping table
public class Usermapper implements RowMapper

Public Object Maprow (ResultSet rs, int index) throws SQLException {
User User=new user ();
User.setid (Rs.getint ("id"));
User.setemail (rs.getstring ("email"));
User.setnickname (rs.getstring ("nickname"));
if (rs.getstring ("is_email_verify"). Equals ("Y")) {
User.setemailverify (TRUE);
}else{
User.setemailverify (FALSE);
}
User.setemailverifycode (rs.getstring ("Email_verify_code"));
User.setlastloginip (rs.getstring ("Last_login_time"));
return user;
}


Note here that Spring2.5 begins a new class Beanpropertyrowmapper

We can play like this.
Public list<user> FindAll () {
String sql= "SELECT * from D_user";
Return (list<user>) this.getjdbctemplate (). Query (Sql,new beanpropertyrowmapper (user.class));---here.
}

We don't have to do a couple of mapper in that mess.

Think about the pros and cons.

Configuration applicationcontext.xml:

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "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/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-3.0.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-4.2.xsd ">    <Context:component-scanBase-package= "Com.wode">    </Context:component-scan>     <BeanID= "DataSource"Destroy-method= "Close"class= "Org.apache.commons.dbcp.BasicDataSource">        < Propertyname= "Driverclassname"value= "Com.mysql.jdbc.Driver" />        < Propertyname= "url"value= "Jdbc:mysql://localhost:3306/test" />        < Propertyname= "username"value= "root" />        < Propertyname= "Password"value= "Lovo" />        < Propertyname= "Maxactive"value= "Ten"></ Property>        < Propertyname= "InitialSize"value= "2"></ Property>        < Propertyname= "Minidle"value= "2"></ Property>        < Propertyname= "Maxidle"value= "3"></ Property>    </Bean>    <BeanID= "JdbcTemplate"class= "Org.springframework.jdbc.core.JdbcTemplate">        < Propertyname= "DataSource"ref= "DataSource" />    </Bean>    </Beans>

On the DAO Layer:

@Repository Public classUserdaoimplImplementsuserdao{@ResourcePrivateJdbcTemplate JdbcTemplate;  Public voidsetjdbctemplate (JdbcTemplate jdbctemplate) { This. JdbcTemplate =JdbcTemplate; }        /*** Add Users*/@Override Public intaddUser (user user) {String SQL= "INSERT into users VALUES (null,?,?)"; intResult=jdbctemplate.update (SQL,Newobject[]{user.getusername (), User.getuserpwd ()}); returnresult; }        /*** Delete User*/@Override Public intDeluserbyid (intID) {String SQL= "DELETE from users WHERE user_id=?"; intResult=jdbctemplate.update (SQL,NewObject[]{id}); returnresult; }    /*** Modify User*/@Override Public intUpdateuserbyid (intId,user User) {String SQL= "UPDATE users SET user_name=?,user_pwd=?" WHERE user_id=? "; intResult=jdbctemplate.update (SQL,Newobject[]{user.getusername (), user.getuserpwd (), id}); returnresult; }    /*** View Users*/@Override PublicUser Selectuserbyid (intID) {String SQL= "SELECT * from Users where user_id=?"; User User=jdbctemplate.queryforobject (SQL,NewObject[]{id},NewBeanpropertyrowmapper<> (User.class)); returnuser; }}

And then:

Abstractapplicationcontext  atx=new classpathxmlapplicationcontext ("Applicationcontext.xml");        UserService  userservice= (userservice) Atx.getbean ("Userserviceimpl");

Using a similar Userservice.updateuserbyid (user) method to implement additions and deletions

Spring and DBCP

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.