Spring connection configuration to the database
Here we begin to use Spring management to configure the operation of the data
1, first configure the data in the XML file connection MySQL
<bean id= "myDataSource" class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" ><!-- Results in a setdriverclassname (String) call--><property name= "Driverclassname" value= "Com.mysql.jdbc.Driver"/ ><property name= "url" value= "Jdbc:mysql://localhost:3306/mydb"/><property name= "username" value= "root" /><property name= "Password" value= "Masterkaoli"/></bean>
Oracle
<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" ><property Name= "Driverclassname" value= "Oracle.jdbc.driver.OracleDriver"/><property name= "url" value= "jdbc:oracle: Thin: @rj-t42:1521:elvis "/><property name=" username "value=" Scott "/><property name=" password "value=" Tiger "/></bean>
2, we first set up a table in the database
Create Database cutter_point;create table ' cutter_point '. ' Person ' ( ' ID ' int. NOT NULL auto_increment, ' name ' varchar () Not NULL, primary key (' ID ')) engine=innodb auto_increment=2 DEFAULT Charset=utf8
3, the corresponding Bean class
/** * Function: Implement spring and JDBC Connection * Time: March 26, 2015 21:09:20 * author:cutter_point */package Cn.cutter_point.bean;public class person {private Integer id;private string name;public person () {}//default constructor public person (String name) {this.name = name;} Public Integer GetId () {return ID;} public void SetId (Integer id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;}}
4. Then our business bean1 relative database operation) interface class
/** * Function: Implement spring and JDBC Connection * Time: March 26, 2015 21:09:20 * author:cutter_point */package Cn.cutter_point.service;import Java.util.list;import Cn.cutter_point.bean.person;public interface Personservice {/** * Save person * @param person * * public void Save (person person),/** * Update person * @param person */public void Update,/** * Get person by ID * @p Aram PersonID * @return */public person Getperson (Integer personid);/** * get all the person * @return */public List<person> ; Getpersons ();/** * Delete the specified person according to the ID number * @param personid */public void Delete (Integer personid);}
2) Service Bean Implementation Interface Personservice
/** * Function: Implement spring and JDBC Connection * Time: March 26, 2015 21:09:20 * author:cutter_point */package Cn.cutter_point.service.impl;import Java.util.list;import Javax.sql.datasource;import Org.springframework.jdbc.core.jdbctemplate;import Cn.cutter_ Point.bean.person;import Cn.cutter_point.service.personservice;public class Personservicebean implements Personservice {//private DataSource datasource;//Here we use a class container in spring JdbcTemplate jdbctemplate;public Personservicebean () {}/** * Set data source * @param dataSource */public void Setdatasource (DataSource dataSource) { This.jdbctemplate = new JdbcTemplate (DataSource);} @Overridepublic void Save (person person) {//TODO auto-generated method Stubjdbctemplate.update (' INSERT into person ' (name ) VALUES (?) ", New Object[]{person.getname ()}, new Int[]{java.sql.types.varchar}); } @Overridepublic void update (person person) {//TODO auto-generated method Stubjdbctemplate.update ("Update person set Nam E=? WHERE id =? ", new Object[]{person.getname (), Person.getid ()}, new Int[]{java.sql.Types.varchar, Java.sql.Types.INTEGER});} @Overridepublic person Getperson (Integer PersonID) {//TODO auto-generated method Stubreturn (person) Jdbctemplate.queryforobject ("select * from person where id =?", New Object[]{personid}, new Int[]{java.sql.types.integer }, New Personrowmapper ());} @Overridepublic list<person> getpersons () {return (list<person>) jdbctemplate.query ("SELECT * FROM Person" , new Personrowmapper ());} @Overridepublic void Delete (Integer PersonID) {jdbctemplate.update ("Delete from person where id =?", New Object[]{personi D}, new Int[]{java.sql.types.integer});}}
3) When the query data is implemented, a callback function is used to remove the data one by one.
/** * Function: Implement spring and JDBC Connection * Time: March 26, 2015 21:09:20 * author:cutter_point */package Cn.cutter_point.service.impl;import Java.sql.resultset;import Java.sql.sqlexception;import Org.springframework.jdbc.core.rowmapper;import Cn.cutter_ Point.bean.person;public class Personrowmapper implements RowMapper {@Override//This class has been done at the time of invocation//similar to if (Rs.next) operation, So you don't have to do this here. Public Object Maprow (ResultSet rs, int index) throws SQLException {//This inside we return the result of the query to person person = new Person (r S.getstring ("name"));p Erson.setid (rs.getint ("id")); return person;}}
5. Configure xmljdbc.properties with the mapping file
driverclassname=org.gjt.mm.mysql.driverurl=jdbc\:mysql\://localhost\:3306/cutter_point?useunicode\=true& Characterencoding\=utf-8username=rootpassword=xiaofeng2015initialsize=1maxactive=500maxidle=2minidle=1
Final XML file 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" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi : schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring -beans-2.5.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context/sprin G-context-2.5.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP Http://www.springframework.org/schema/aop/spring-ao P-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd "&G T <context:property-placeholder location= "classpath:jdbc.properties"/> <bean id= "DataSource" class= " Org.apache.commons.dbcp.BasicDataSource " destroy-method= "Close" > <property name= "driverclassname" value= "${driverclassname}"/> <property name= " URL "value=" ${url} "/><!--? Useunicode=true&characterencoding=utf-8---<property name=" username " Value= "${username}"/> <property name= "password" value= "${password}"/> <!--initial value when connection pooling starts--<proper Ty name= "initialsize" value= "${initialsize}"/><!--connection Pool max--<property name= "maxactive" value= "${ Maxactive} "/> <!--maximum idle value. After a peak time, the connection pool can slowly release a portion of the connection that has not been used, and has been reduced to maxidle so far-<property name=" Maxidle " Value= "${maxidle}"/><!--minimum idle value. When the number of idle connections is less than the threshold, the connection pool will pre-apply for some connections to avoid the flood peak time to apply---<property name= "Minidle" Value= "${minidle}"/> </bean><bean id= "Personservice" class= "Cn.cutter_ Point.service.impl.PersonServiceBean "><property name=" DataSource "ref=" DataSource "/></bean></ Beans>
6. Set up Unit test
Package Junit.test;import static Org.junit.assert.*;import Org.junit.beforeclass;import Org.junit.test;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Cn.cutter_point.bean.person;import Cn.cutter_point.service.personservice;public class Personservicetest {private static Personservice personservice;@ Beforeclasspublic static void Setupbeforeclass () throws Exception {try {applicationcontext cxt = new Classpathxmlapplicat Ioncontext ("Beans.xml");p Ersonservice = (personservice) cxt.getbean ("Personservice");} catch (Exception e) {e.printstacktrace ();}} @Testpublic void Save () {for (int i = 0, i < 5; ++i) {Personservice.save (New person ("Xiaofeng" +i));}} @Testpublic void Get () {Person person = Personservice.getperson (1); System.out.println (Person.getname ());} @Testpublic void Update () {Person person = Personservice.getperson (1);p erson.setname ("Shaw X");p ersonservice.update ( person);} @Testpublic void Delete () {PersonservicE.delete (1);} @Testpublic void Getpersons () {for (Person person:personService.getPersons ()) {System.out.println (Person.getname ());}} @Testpublic void Test () {//fail ("not yet implemented");}
Results
A bit of a twist in the middle, note that the value of the ref attribute inside the XML file must be copied, really TMD don't believe yourself, I was this thing for a day, please forgive me this English slag slag!!!
"Java EE Spring" 6, Spring and database connection configuration