This article introduces spring development_JDBC operation of MySQL database, as follows:
Project structure:
Database table:
/spring_1100_spring+jdbc/src/com/b510/bean/Person.java
package com.b510.bean;/** * Normal javaBean class Person * * @author Hongten * */public class Person { /** * id number */ private int id; /** * Name */ private String name; /** * Age */ private int age; /** * 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 { /** * Save Person * * @param person*/ public abstract void save(Person person); /** * Update Person * * @param person*/ public abstract void update(Person person); /** * Get Person * * @param id * @return*/ public abstract Person getPerson(Integer id); /** * Get all Person * * @return*/ public abstract List<Person> getPerson(); /** * Delete the Person with the specified id * * @param id*/ public abstract void delete(Integer 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; /** * jdbc operation auxiliary class provided by spring*/ private JdbcTemplate jdbcTemplate; // Set the data source public void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } public void save(Person person) { jdbcTemplate.update("insert into person(name,age,sex)values(?,?,?)", new 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.VARCHAR, java.sql.Types.INTEGER, java.sql.Types.VARCHAR, java.sql.Types.INTEGER }); } public Person getPerson(Integer id) { Person person = (Person) jdbcTemplate.queryForObject( "select * from 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.query("select * from person", new PersonRowMapper()); return list; } 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) throws SQLException { Person person = 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 ClassPathXmlApplicationContext("bean.xml"); PersonService personService = (PersonService) act .getBean("personService"); Person person = 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 Persons"); for (Person person2 : person1) { System.out.println(person2.getId() + " " + person2.getName() + " " + person2.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.getSex()); // Delete a record personService.delete(1); }} /spring_1100_spring+jdbc/src/bean.xml
<?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/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/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!--Configuration Data Source--> <bean id="dataSource" destroy-method="close"> <property name="driverClassName" value="org.gjt.mm.mysql.Driver" /> <property name="url" value="jdbc:mysql://localhost:3307/spring?useUnicode=true&characterEncoding=UTF-8" /> <property name="username" value="root" /> <property name="password" value="root" /> <!-- Initial value when the connection pool starts --> <property name="initialSize" value="1" /> <!-- Maximum value of the connection pool --> <property name="maxActive" value="300" /> <!-- Maximum idle value. After a peak time, the connection pool can slowly release some of the unused connections and reduce them until maxIdle --> <property name="maxIdle" value="2" /> <!-- 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 time to apply when the flood peak comes --> <property name="minIdle" value="1" /> </bean> <!-- Use annotation to configure transactions. For the transaction manager of the data source, inject the data source we defined into the property dataSource of the DataSourceTransactionManager class --> <bean id="txManager" > <property name="dataSource" ref="dataSource" /> </bean> <!-- Introduce namespace: 1.xmlns:tx="http://www.springframework.org/schema/tx 2.http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd Use the @Transaction annotation to use the transaction manager --> <tx:annotation-driven transaction-manager="txManager" /> <!-- Configure service bean: PersonServiceBean --> <bean id="personService"> <!-- Inject data source into property dataSource--> <property name="dataSource" ref="dataSource"></property> </bean></beans>
Running 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 09 23:30:57 CST 2012]; root of context hierarchy2012-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.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory information: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@1a05308]: org.springframework.beans.factory.support.DefaultListableBeanFactory@2bb5142012-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++++++++++Get all Person2 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 configuration files to store our data source information:
/spring_1100_spring+jdbc/src/jdbc.properties
driverClassName=org.gjt.mm.mysql.Driverurl=jdbc/:mysql/://localhost/:3307/spring?useUnicode/=true&characterEncoding/=UTF-8username=rootpassword=rootinitialSize=1maxActive=300maxIdle=2minIdle=1
Correspondingly:
/spring_1100_spring+jdbc/src/bean.xml
<?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/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/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" destroy-method="close"> <property name="driverClassName" value="${driverClassName}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- Initial value when the connection pool starts --> <property name="initialSize" value="${initialSize}" /> <!-- Maximum value of the connection pool --> <property name="maxActive" value="${maxActive}" /> <!-- Maximum idle value. After a peak time, the connection pool can slowly release part of the unused connections, reducing until maxIdle --> <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 time to apply when the flood peak comes--> <property name="minIdle" value="${minIdle}" /> </bean> <!-- Use annotation to configure transactions. For the transaction manager of the data source, inject the data source we defined into the property dataSource of the DataSourceTransactionManager class --> <bean id="txManager" > <property name="dataSource" ref="dataSource" /> </bean> <!-- Introduce namespace: 1.xmlns:tx="http://www.springframework.org/schema/tx 2.http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd Use the @Transaction annotation to use the transaction manager --> <tx:annotation-driven transaction-manager="txManager" /> <!-- Configure service bean: PersonServiceBean --> <bean id="personService"> <!-- Inject data source into property dataSource--> <property name="dataSource" ref="dataSource"></property> </bean></beans> 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 10 00:23:59 CST 2012]; root of context hierarchy2012-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.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory information: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@c1b531]: org.springframework.beans.factory.support.DefaultListableBeanFactory@1aa57fb2012-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++++++++++++ Get all Person2 TomCat 12 Female 3 hongten 21 Male 4 liufang 21 Female 5 Divide 20 Male 6 Jone 20 Female 7 Su Dongpo 21 Male 8 Su Dongpo 21 Male***************************2 TomCat 12 Female
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.