Using JdbcTemplate in Spring

Source: Internet
Author: User

Software 152 class Yang Jinhong

Spring uses JdbcTemplate, Jdbcdaosupport, and namedparameterjdbctemplate to manipulate databases, but JdbcTemplate is most commonly used and easiest to use.

Jdbc.properties:




user=rootpassword=123driverclass=com.mysql.jdbc.driverjdbcurl=jdbc\:mysql\:///spring? Encoding\=uft-8initpoolsize=5maxpoolsize=20

Applicationcontext.xml Import configuration files and configuration datasouce:

    <!--Import resource File-<Context:property-placeholderLocation= "Classpath:jdbc.properties"/><!--Configuring C3P0 Data sources-<BeanId= "DataSource"Class= "Com.mchange.v2.c3p0.ComboPooledDataSource"><PropertyName= "User"Value= "${user}"></Property><PropertyName= "Password"Value= "${password}"></Property><PropertyName= "Driverclass"Value= "${driverclass}"></Property><PropertyName= "Jdbcurl"Value= "${jdbcurl}"></Property> <property name= "initialpoolsize"  value< Span style= "COLOR: #0000ff" >= "${initpoolsize}" ></ property> <property name= "Maxpoolsize" Span style= "COLOR: #ff0000" > Value= "${maxpoolsize}" > </property> </< Span style= "COLOR: #800000" >bean>       

Test0410.java (Attributes and fields in the database):

PackageSPRING.JDBC;PublicClasstest0410 {PrivateInteger uuid;PrivateString name;PrivateInteger age;PublicInteger Getuuid () {ReturnUuid }PublicvoidSetuuid (Integer uuid) {This.uuid =Uuid }PublicString GetName () {return name; public void SetName ( String name {this.name = name;} public Integer getage () {return age; } public void Setage ( Integer age) {this.age = age;} @Override public String toString () {return" test0410 [ Uuid= "+ uuid +", name= "+ name +", age= "+ Age +" ";}}     

Test0410dao.java:

PackageSPRING.JDBC;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.jdbc.core.BeanPropertyRowMapper;ImportOrg.springframework.jdbc.core.JdbcTemplate;ImportOrg.springframework.jdbc.core.RowMapper;import org.springframework.stereotype.repository;@ Repositorypublic class Test0410dao {@Autowired private JdbcTemplate JdbcTemplate; public test0410 get (Integer id) {String sql= ' select ID UUID , name,age from test0410 where id=? " ; rowmapper<test0410> rowmapper=new beanpropertyrowmapper<test0410> ( test0410. classreturn test10410;}}       

Configure automatic scanning and jdbctemplate in Applicationcontext.xml:

<!--Configure automatic scanning of packages-<Context:component-scanBase-package= "Spring.jdbc"></Context:component-scan><!-- Configure spring JdbcTemplate --> <bean id= "JdbcTemplate"  Class= "org.springframework.jdbc.core.JdbcTemplate" > <property name=" DataSource " Ref=" DataSource "></property> </bean>     

Test class:

PackageSpring.jdbc.test;ImportJava.sql.SQLException;ImportJava.util.ArrayList;ImportJava.util.List;ImportJavax.sql.DataSource;ImportOrg.junit.Test;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;ImportOrg.springframework.jdbc.core.BeanPropertyRowMapper;ImportOrg.springframework.jdbc.core.JdbcTemplate;ImportOrg.springframework.jdbc.core.RowMapper;Importspring.jdbc.test0410;ImportSpring.jdbc.test0410Dao;PublicClassjdbctest {Private ApplicationContext ctx=Null;PrivateJdbcTemplate JdbcTemplate; {ctx=New Classpathxmlapplicationcontext ("Applicationcontext.xml"); Jdbctemplate= (JdbcTemplate) Ctx.getbean ("JdbcTemplate"); } @TestPublicvoidTestdao () {Test0410dao test04101= (Test0410dao) Ctx.getbean ("Test0410dao"); System.out.println (Test04101.get (1)); }/*** Get the value of a single column or make a statistical query * using queryForObject (String sql, class<long> requiredtype)*/@TestPublicvoidTestQueryForObject2 () {String sql= "SELECT count (ID) from test0410";Long Count=jdbctemplate.queryforobject (SQL, long.)Class); System.out.println (count); }/*** Check the collection of entity classes * Note that the queryForList method is not called*/@TestPublicvoidTestqueryforlist () {String sql= "SELECT id uuid,name,age from test0410 where Id>?"; Rowmapper<test0410> temapper=New Beanpropertyrowmapper<test0410> (test0410.Class); List<test0410> test0410s=jdbctemplate.query (SQL, temapper,2); System.out.println (test0410s); }/*** Get a record from the database, actually get an object * Note: not calling queryForObject (String sql, class<test0410> requiredtype, Object ... args) method * Instead, you need to call queryForObject (String sql, rowmapper<test0410> rowmapper, Object ... args) * Where the RowMapper specifies how to map the rows of the result set, The common implementation class for Beanpropertyrowmapper * * uses the alias of the column in SQL and the class's property name mapping, for example: ID UUID * * does not support cascading properties*/@TestPublicvoidTestqueryforobject () {String sql= "SELECT id uuid,name,age from test0410 where id=?"; Rowmapper<test0410> rowmapper=New Beanpropertyrowmapper<test0410> (test0410.Class); test0410 Test10410=jdbctemplate.queryforobject (sql,rowmapper,1); System.out.println (test10410); }/*** Perform batch update: UPDATE, INSERT, delete * The last parameter is a object[] list collection.*/@TestPublicvoidTestbatchupdate () {String sql= "insert into test0410 (id,name,age) VALUES (?,?,?)"; List<object[]> batchargs=New arraylist<object[]>(); Batchargs.add (New object[]{2, "AAA", 23}); Batchargs.add (New Object[]{3, "BBB", 24}); Batchargs.add (new object[]{4, "CCC", 25}); Jdbctemplate.batchupdate ( SQL, Batchargs); } /** * perform update, INSERT, delete */ @Test public void Testuptate () {String sql= "update test0410 set name=?" where id=? "; Jdbctemplate.update (SQL, "Lyj", 1public void testdatesource () throws sqlexception{DataSource datasource= (DataSource) Ctx.getbean ("DataSource" 

Using JdbcTemplate in spring

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.