Detailed spring Development _JDBC operation MySQL Database _java

Source: Internet
Author: User
Tags abstract aop tomcat

This article describes the spring development _JDBC operation MySQL database, specifically as follows:

Project structure:

Database tables:

/spring_1100_spring+jdbc/src/com/b510/bean/person.java

Package Com.b510.bean;

/**
 * Ordinary JavaBean type Person * * * @author hongten * * * * * * */public 
 class person
{

  /**
   * ID number
* *
  private int id;
  /**
   * Name
  /private String name;
  /**
   * Age
  /private int;
  /**
   * Gender
  /private String sex;


  public person (int ID, string name, int age, string sex) {
    this.id = ID;
    this.name = name;
    This.age = age;
    This.sex = sex;
  }

  Public person () {
  } public

  int getId () {return
    ID;
  }

  public void setId (int id) {
    this.id = ID;
  }

  Public String GetName () {return
    name;
  }

  public void SetName (String name) {
    this.name = name;
  }

  public int getage () {return age
    ;
  }

  public void Setage (int age) {
    this.age = age;
  }

  Public String Getsex () {return
    sex;
  }

  public void Setsex (String sex) {
    this.sex = sex;
  }

}

/spring_1100_spring+jdbc/src/com/b510/service/personservice.java

Package com.b510.service;

Import java.util.List;

Import Com.b510.bean.Person;

Public interface Personservice {

  /**
   * Saving person
   * 
   * @param person
  /public abstract void Save ( person);

  /**
   * Update Person
   * 
   * @param person/public
  abstract void update (person);

  /**
   * Get person
   * 
   * @param ID
   * @return
  /public abstract person Getperson (Integer ID); c23/>/**
   * Get all person
   * 
   * *
@return
  /public abstract list<person> Getperson ();

  /**
   * Delete person
   * 
   * @param ID/public
  abstract void Delete (Integer id)

of the specified ID;

/spring_1100_spring+jdbc/src/com/b510/service/impl/personservicebean.java

Package Com.b510.service.impl;

Import java.util.List;

Import Javax.sql.DataSource;

Import Org.springframework.jdbc.core.JdbcTemplate;
Import Com.b510.bean.Person;

Import Com.b510.service.PersonService;
  /** * Business Bean * * @author hongten * */public class Personservicebean implements Personservice {/** * data source * *
  Private DataSource DataSource;

  /** * Spring provides JDBC operations assistance class * * Private JdbcTemplate JdbcTemplate;
  Sets the data source public void Setdatasource (DataSource DataSource) {this.jdbctemplate = new JdbcTemplate (DataSource); ' public void save ' {jdbctemplate.update (' INSERT into person (name,age,sex) VALUES (?,?,?) ', NE
            W object[] {person.getname (), Person.getage (), Person.getsex ()}, new int[] {Java.sql.Types.VARCHAR,
  Java.sql.Types.INTEGER, Java.sql.Types.VARCHAR}); } public void update (person person) {jdbctemplate.update (' Update person set name=?,age=?,sex=? Where id=? ", new object[] {PersoN.getname (), Person.getage (), Person.getsex (), Person.getid ()}, new int[] {Java.sql.Types.VARCHA

  R, Java.sql.Types.INTEGER, Java.sql.Types.VARCHAR, Java.sql.Types.INTEGER}); Getperson (Integer id) {Person person = (person) jdbctemplate.queryforobject ("SELECT * Fro
    M person where id=? ", new object[] {ID}, new int[] {Java.sql.Types.INTEGER}, new Personrowmapper ());

  return person; @SuppressWarnings ("unchecked") public list<person> Getperson () {list<person> List = jdbctemplate.q
    Uery ("SELECT * from person", New Personrowmapper ());

  return list;
        The public void Delete (Integer id) {jdbctemplate.update ("Delete from person where id =?", new object[] {ID},

  New int[] {Java.sql.Types.INTEGER});

 }
}

/spring_1100_spring+jdbc/src/com/b510/service/impl/personrowmapper.java

Package Com.b510.service.impl;

Import Java.sql.ResultSet;
Import java.sql.SQLException;

Import Org.springframework.jdbc.core.RowMapper;

Import Com.b510.bean.Person;

public class Personrowmapper implements RowMapper {

  @Override public
  Object Maprow (ResultSet set, int index) thro WS SQLException {person is
    = new Person (set.getint ("id"), set.getstring ("name"), set
        . GetInt ("Age"), Set.getstring ("Sex"));
    return person;
  }



/spring_1100_spring+jdbc/src/com/b510/test/springjdbctest.java

Package com.b510.test;

Import java.util.List;
Import Org.springframework.context.ApplicationContext;

Import Org.springframework.context.support.ClassPathXmlApplicationContext;
Import Com.b510.bean.Person;

Import Com.b510.service.PersonService; public class Springjdbctest {public static void main (string[] args) {ApplicationContext act = new Classpathxmlapp

    Licationcontext ("Bean.xml");

    Personservice Personservice = (personservice) Act. Getbean ("Personservice");
    person who = new person ();
    Person.setname ("Su Dongpo");
    Person.setage (21);

    Person.setsex ("male");

    Save a record personservice.save (person);
    List<person> Person1 = Personservice.getperson ();
    System.out.println ("++++++++ Get all Person"); for (person Person2:person1) {System.out.println (Person2.getid () + "" + person2.getname () + "" + per
    Son2.getage () + "" + person2.getsex ());
    Person Updateperson = new person (); Updateperson.setname ("Divide");
    Updateperson.setage (20);
    Updateperson.setsex ("male");
    Updateperson.setid (5);
    Update a record personservice.update (Updateperson);

    System.out.println ("******************");
    Get a record person Oneperson = Personservice.getperson (2); System.out.println (Oneperson.getid () + "" + oneperson.getname () + "" + oneperson.getage () + "" + oneperson.gets
    EX ());
  Delete a record personservice.delete (1);

 }
}

/spring_1100_spring+jdbc/src/bean.xml

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" 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 /spring-context-2.5.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-2.5.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/
    Spring-tx-2.5.xsd > <!--Configure Data source--> <bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" > <property name= "driverclassname value=" org.gjt.mm.mySql. Driver "/> <property name=" url "value=" Jdbc:mysql://localhost:3307/spring?useunicode=true&characterenc 
    Oding=utf-8 "/> <property name=" username "value=" "root"/> <property name= "password" value= "root"/> <!--The initial value of the connection pool startup--> <property name= "InitialSize" value= "1"/> <!--the maximum connection pool value--> Erty name= "maxactive" value=/> <!--maximum idle value. After a peak time, the connection pool can slowly release a part of the connection that has not been used, and has been reduced to maxidle so far--> ;p roperty name= "Maxidle" value= "2"/> <!--minimum idle value. When the number of idle connections is less than the valve value, the connection pool will advance to some connections to avoid the flood peak when it is too late to apply for--> <property Name= "Minidle" value= "1"/> </bean> <!--use annotations to configure transactions. For the transaction manager of the data source, inject our defined data source into the properties DataSource of the Datasourcetransactionmanager class--> <bean id= "Txmanager" class= "org . Springframework.jdbc.datasource.DataSourceTransactionManager "> <property name=" DataSource "ref=" DataSource "/> </bean> <!--introduce namespaces: 1.xmlns:tx=" Http://www.sprinGframework.org/schema/tx 2.http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/

  Spring-tx-2.5.xsd uses the transaction manager--> <tx:annotation-driven transaction-manager= "TxManager" using the @transaction annotation method/> <!--configuration Business Bean:personservicebean--> <bean id= "Personservice" class= " Com.b510.service.impl.PersonServiceBean > <!--inject the data source to the property DataSource--> <property name= "DataSource" ref=

 "DataSource" ></property> </bean> </beans>

Run results;

2012-3-9 23:30:57 org.springframework.context.support.AbstractApplicationContext preparerefresh information: refreshing Org.springframework.context.support.classpathxmlapplicationcontext@1a05308:display name [ ORG.SPRINGFRAMEWORK.CONTEXT.SUPPORT.CLASSPATHXMLAPPLICATIONCONTEXT@1A05308]; startup Date [Fri Mar 23:30:57 CST 2012]; Root of context hierarchy 2012-3-9 23:30:57 Org.springframework.beans.factory.xml.XmlBeanDefinitionReader Loadbeandefinitions information: Loading XML bean Definitions from class path resource [Bean.xml] 2012-3-9 23:30:58 org.springframe Work.context.support.AbstractApplicationContext obtainfreshbeanfactory Information: Bean factory for application context [ ORG.SPRINGFRAMEWORK.CONTEXT.SUPPORT.CLASSPATHXMLAPPLICATIONCONTEXT@1A05308]: org.springframework.beans.factory.support.defaultlistablebeanfactory@2bb514 2012-3-9 23:30:58 Org.springframework.beans.factory.support.DefaultListableBeanFactory preinstantiatesingletons Information: Pre-instantiating singletons in Org.springframework.beans.factory.Support. defaultlistablebeanfactory@2bb514:defining Beans [Datasource,txmanager, Org.springframework.aop.config.internalAutoProxyCreator, Org.springframework.transaction.annotation.annotationtransactionattributesource#0, Org.springframework.transaction.interceptor.transactioninterceptor#0, Org.springframework.transaction.config.internaltransactionadvisor,personservice]; Root of factory hierarchy ++++++++ gets all person 2 TomCat 12 female 3 Hongten 21 male 4 Liufang 21 female 5 Divide 20 male 6 Jone 20 Female 7
 Su Dongpo 21 male ****************** 2 TomCat 12 female

Of course we can use the configuration file to store our data source information:

/spring_1100_spring+jdbc/src/jdbc.properties

Driverclassname=org.gjt.mm.mysql.driver
url=jdbc\:mysql\://localhost\:3307/spring?useunicode\=true& Characterencoding\=utf-8
username=root
password=root
initialsize=1
maxactive=300
maxIdle=2
minidle=1

To modify the appropriate:

/spring_1100_spring+jdbc/src/bean.xml

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" 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 /spring-context-2.5.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-2.5.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-2.5.xsd "> <!--read jdbc.properties configuration file--> <context:property-placeholder location=" classpath: Jdbc.properties "/> <!--configuration data source--> <bean id=" DataSource "class=" org.apache.comMons.dbcp.BasicDataSource "destroy-method=" Close "> <property name=" driverclassname "value=" ${driverclassname } "/> <property name= url" value= "${url}"/> <property name= "username" value= "${username}"/> & Lt;property name= "Password" value= "${password}"/> <!--the initial value of the connection pool startup--> <property name= "InitialSize" va Lue= "${initialsize}"/> <!--connection pool maximum--> <property name= "maxactive" value= "${maxactive}"/> ;! --Maximum idle value. After a rush hour, the connection pool can slowly release a portion of the connection that has not been used until the maxidle is reduced to--> <property name= "Maxidle" value= "${maxidle}"/&
    Gt <!--minimum idle value. When the number of idle connections is less than the threshold, the connection pool will advance to some connections to avoid the flood peak time to apply for--> <property name= "Minidle" value= "${minidle"/> ;/bean> <!--use annotations to configure transactions. For the transaction manager of the data source, inject our defined data source into the properties DataSource of the Datasourcetransactionmanager class--> <bean id= "Txmanager" class= "org . Springframework.jdbc.datasource.DataSourceTransactionManager "> <property name=" DataSource "ref= "DataSource"/> </bean> <!--Introducing namespaces: 1.xmlns:tx= "Http://www.springframework.org/schema/tx 2.ht
    Tp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd Use the transaction manager--> <tx:annotation-driven transaction-manager= "Txmanager"/> <!--Configure business with @transaction annotations Bean:pe Rsonservicebean--> <bean id= "Personservice" class= "Com.b510.service.impl.PersonServiceBean" > <!--to Property da Tasource injection Data source--> <property name= "DataSource" ref= "DataSource" ></property> </bean> &LT;/BEANS&G

 T

The

Run results are the same:

2012-3-10 0:23:59 org.springframework.context.support.AbstractApplicationContext preparerefresh information: refreshing Org.springframework.context.support.classpathxmlapplicationcontext@c1b531:display name [ ORG.SPRINGFRAMEWORK.CONTEXT.SUPPORT.CLASSPATHXMLAPPLICATIONCONTEXT@C1B531]; startup Date [Sat Mar 00:23:59 CST 2012]; Root of context hierarchy 2012-3-10 0:23:59 Org.springframework.beans.factory.xml.XmlBeanDefinitionReader Loadbeandefinitions information: Loading XML bean Definitions from class path resource [Bean.xml] 2012-3-10 0:23:59 org.springframe Work.context.support.AbstractApplicationContext obtainfreshbeanfactory Information: Bean factory for application context [ ORG.SPRINGFRAMEWORK.CONTEXT.SUPPORT.CLASSPATHXMLAPPLICATIONCONTEXT@C1B531]: ORG.SPRINGFRAMEWORK.BEANS.FACTORY.SUPPORT.DEFAULTLISTABLEBEANFACTORY@1AA57FB 2012-3-10 0:23:59 Org.springframework.core.io.support.PropertiesLoaderSupport loadproperties Information: Loading properties file from class path Resource [jdbc.properties] 2012-3-10 0:23:59 orG.springframework.beans.factory.support.defaultlistablebeanfactory preinstantiatesingletons Information: Pre-instantiating singletons in org.springframework.beans.factory.support.defaultlistablebeanfactory@1aa57fb:defining beans [ Org.springframework.beans.factory.config.propertyplaceholderconfigurer#0,datasource,txmanager, Org.springframework.aop.config.internalAutoProxyCreator, Org.springframework.transaction.annotation.annotationtransactionattributesource#0, Org.springframework.transaction.interceptor.transactioninterceptor#0, Org.springframework.transaction.config.internaltransactionadvisor,personservice]; Root of factory hierarchy ++++++++ gets all person 2 TomCat 12 female 3 Hongten 21 male 4 Liufang 21 female 5 Divide 20 male 6 Jone 20 Female 7
 Su Dongpo 21 men 8 su Dongpo 21 male ****************** 2 TomCat 12 female

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.