23spring_jdbctemplate to realize the change of single table and delete

Source: Internet
Author: User

The first step is to build the table:

Step two: Write the entity class for the product table

 Public classProduce {Private intID; PrivateString name; PrivateString Price;/** * @returnThe ID*/ Public intgetId () {returnID;}/** * @paramID The ID to set*/ Public voidSetId (intID) { This. ID =ID;}/** * @returnThe name*/ PublicString GetName () {returnname;}/** * @paramname the name to set*/ Public voidsetName (String name) { This. Name =name;}/** * @return The price*/ PublicString GetPrice () {returnPrice ;}/** * @paramPrice the price to set*/ Public voidSetprice (String price) { This. Price =Price ;} }

The third step: Write Productdao, complete the basic common operation.

This immediately has a problem, we want to use the spring JdbcTemplate to operate the database, then we should inject jdebctemplate in the Productdao class, we think of the way is to define a member variable, and then

Injected, but spring has considered this for us, so we have provided a Jdbcdaosupport class to help us. This class provides a way to Setjdbctempalte.

/** We're going to use the Spring JDBC Template (jdbctemplate) The first idea is to define a member variable in this class, and then use the set method to inject it with spring. But spring has considered the situation for us. We do not need to write what setjdbctemplate this method, just go * inherit jdbcdaosupport this class can be. In this class there is already setjdbctemplate this method. *  */ Public classProductdaoextendsJdbcdaosupport {
Increase
public void Save (produce Produce1)
{
String sql= "INSERT into product values (null,?,?)";
This.getjdbctemplate (). Update (SQL, Produce1.getname (), Produce1.getprice ());


}
Change
public void update (produce Produce1)
{
String sql= "Update product set name=?,price=?" where id=? ";
This.getjdbctemplate (). Update (SQL, Produce1.getname (), Produce1.getprice (), Produce1.getid ());


}
By deleting
public void Delete (produce Produce1)
{String sql= "delete from product where id=?";
This.getjdbctemplate (). Update (SQL, Produce1.getid ());

}


}

Fourth step: Configure the Spring Applicationcontext.xml file.

<!--Introducing peoperties Files -<!--<context:property-placeholder location= "classpath:db.properties"/> -<Beanclass= "Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">< Propertyname= "Locations"value= "Classpath:db.properties"/></Bean> <BeanID= "DataSource"class= "Com.mchange.v2.c3p0.ComboPooledDataSource">  < Propertyname= "Driverclass"value= "${driver}"/>  < Propertyname= "Jdbcurl"value= "${url}"></ Property> < Propertyname= "User"value= "${username}"></ Property>< Propertyname= "Password"value= "${password}"></ Property></Bean>     <BeanID= "JdbcTemplate"class= "Org.springframework.jdbc.core.JdbcTemplate">< Propertyname= "DataSource"ref= "DataSource"/></Bean><!-- inject values into the jdbctemplate of  Productdao's parent class -- <BeanID= "Productdao"class= "Cn.itcast.spring.c_jdbc." Productdao ">< Propertyname= "JdbcTemplate"ref= "JdbcTemplate"/></Bean>

Fifth step: Writing JUnit test code

@RunWith (Springjunit4classrunner.class) @ContextConfiguration (Locations= "Classpath:applicationContext.xml") Public classproducttest {@AutowiredPrivateProductdao Productdao; //@Test     Public voidTestsave () {Produce Produce1=NewProduce (); Produce1.setname (Love); Produce1.setprice ("100");  This. Productdao.save (Produce1); }    //@Test     Public voidtestupdate () {Produce Produce2=NewProduce (); Produce2.setid (1); Produce2.setname ("Love 2"); Produce2.setprice ("200");  This. Productdao.update (PRODUCE2); } @Test Public voidTestdelete () {Produce produce1produce=NewProduce (); Produce1produce.setid (2);  This. Productdao.delete (Produce1produce); }}

The above on the additions and deletions are explained, the following to find out alone to explain. Find two pieces to explain, simple to find and complex to find.

Simple to find:

If the return result is a simple value, use JdbcTemplate to provide the Queryforxxx method

For example: queryForInt return result is int

queryForLong Returns the result is a long

queryForObject returns a result of object (return string)

For the above three methods, write two methods respectively.

Find the number of items and find the name of the item

//find the number of items Public LongFindtotlecount () {String SQL= "SELECT count (*) from produce"; return  This. Getjdbctemplate (). queryForLong (SQL);}//find the name of the product PublicString Findnamebyid (intID) {String SQL= "SELECT name from product where id=?";return  This. Getjdbctemplate (). queryForObject (SQL, String.class, id);}

Write the appropriate test code in JUnit:

 //test Find the name of the product       
//@Test Public voidTestfindnamebyid () {String name= This. Productdao.findnamebyid (1); System.out.print (name); }
//test to find the total number of items @Test Public voidTesttotlecount () {LongCount= This. Productdao.findtotlecount (); System.out.print ("AAAAAAA" +count); }

The result: The output is all right.

Off Topic:

A common multi-table query actually has a fatal disadvantage. Take Macheng Teacher's DatabaseClass class as an example. This class has a fatal disadvantage, that is, in multi-table queries, such as

SELECT * from Custom,order where custom.orderid=orider.id and custom.id=? Here are two tables, and the query gets the fields that have all the fields of the two tables. Then there is a problem.

I don't have an entity class for a field of two tables Ah, for this I would like to re-create the corresponding entity class, in case I later field in the less one, it is not to change often ah. This is his fatal flaw.

But hibernate is a good solution to this problem. Because each entity class in Hibernate has a corresponding. Hbm.xml so the results are stored in the respective entity classes.

The complex query is put in the final words:

Complex query Return object:

JdbcTemplate does not provide a handler like the Apache Dbutils framework, but instead requires the manual encapsulation of the result set (that is, we have to take a data out of the database ourselves,

Wrap it up as an object yourself. )

------------Common Enterprise Development, developers will write separate result set wrappers for each table (RowMapper)

So we're going to manually encapsulate the result set (RowMapper) ourselves. Note that with RowMapper, we just care about the encapsulation of each value of a row of data, and don't care how to break it.

Rs.next () or whatever, we don't care.

First step: Write an inner class to inherit rowmapper<>

The second step: write the corresponding method of finding the result.

//The first step:Private classProductrowmapperImplementsRowmapper<produce>{     PublicProduce Maprow (ResultSet RS,intRowNum)throwsSQLException {produce Produce1=NewProduce (); Produce1.setid (Rs.getint ("id")); Produce1.setname (Rs.getstring ("Name")); Produce1.setprice (Rs.getstring ("Price")); returnProduce1; }}//The second step is to persist one of the product objects in the database based on the ID.  PublicProduce Findproducebyid (intID) {String SQL= "SELECT * from product where id=?"; return  This. Getjdbctemplate (). queryForObject (SQL,NewProductrowmapper (), id);}

Step three: Write JUnit test code:

    @Test    publicvoid  testfindproduct ()    {        produce Produce1= this. Productdao.findproducebyid (1);         // The results from the test are not right.        System.out.print (Produce1.getid () +produce1.getname () +produce1.getprice ());            

The result: Yes.

The core of this is RowMapper.

23spring_jdbctemplate to realize the change of single table and delete

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.