User Instances JdbcTemplate in spring

Source: Internet
Author: User

1, first configure the JdbcTemplate

Configure a JdbcTemplate bean in the Spring IOC container, inject DataSource (using a third-party data source c3p0), and inject jdbctemplate into the custom DAO.

<bean id="DS"class="Com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="User"Value="Root"/> <property name="Password"Value="Root"/> <property name="Jdbcurl"Value="jdbc:mysql:///db_test"/> <property name="Driverclass"Value="Com.mysql.jdbc.Driver"/></bean><bean id="JdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate"> <property name="DataSource"ref="DS"/></bean>

2, in the custom DAO class is configured as follows, for private jdbctemplate temp; Add annotations to allow the framework to inject the object automatically. DAO layer classes using @Repository annotations

@Repositorypublic class Userdaoimpl implements Userdao {@Autowired private jdbctemplate temp; @Override public boolean Add (user user) {String SQL="INSERT into user values (?,?,?,?)"; int update=temp.update (SQL, User.getid (), User.getname (), User.getage (), user.getaddress ()); returnUpdate >0?true:false; } @Override public boolean update (user user) {String SQL="Update user set name=?, age=?, address=? where id=?"; int update=temp.update (SQL, User.getname (), User.getage (), user.getaddress (), User.getid ()); returnUpdate >0?true:false; }
}

3. Testing

Public class Jdbctest {private UserService service; @Before public void before () {Classpathxmlapplicationcontext CTX= New Classpathxmlapplicationcontext ("Beans.xml"); Service=Ctx.getbean (Userserviceimpl.class); } @Test public void Add () {User User=new User (); User.setname ("Guo Jing"); User.setage ( at); User.setaddress ("Beijing");    Service.add (user); } @Test public void Update () {User User=new User (); User.setid (1); User.setname ("Huang Rong"); User.setage ( -); User.setaddress ("Nanchang");    Service.update (user); }
}

User Instances 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.