I. Spring's support for DAO
Dao:data Access Object
Spring provides a DAO framework that enables developers to develop applications without coupling specific database technologies.
Spring closes the usage of databases such as Operation Oracle,mysql,db2,sql.
They all implement the same interface, and the method is the same.
Advantage:
Depending on the interface, the implementation class of the DAO interface can be replaced at any time by dependency injection, and the application does not have to know the interface and the underlying database operation details at all.
Application----Call-----DAO Interface---Implement the--dao interface implementation class----operations------Database
Second, spring injection data source
2.1. DataSource (data source)
The way data is connected is called a database. such as JDBC, connection pooling, or Jndi
Spring configures a data source by using a dependency injection method
Different systems, the management of data sources is more about the underlying behavior, and these behaviors should not affect the business.
Changing the data requires only modifying the contents of the bean definition without modifying any one line of code.
2.2. Configure the data source
Applicationcontext.xml Configuring a data source
<?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:p= "http://www.springframework.org/schema/p" xmlns:aop= " Http://www.springframework.org/schema/aop "xsi:schemalocation=" Http://www.springframework.org/schema/beans http ://www.springframework.org/schema/beans/spring-beans-3.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/http Www.springframework.org/schema/aop/spring-aop-3.1.xsd "><!--data source--><bean id=" DataSource "class=" Org.springframework.jdbc.datasource.DriverManagerDataSource "><!--drive--><property name=" Driverclassname "value=" oracle.jdbc.driver.OracleDriver "/><!--url--><property name=" url "value=" jdbc : Oracl:thin: @localhost: 1521:orcl "/><!--connected user name--><property name=" username "value=" ACCP "></ property><!--Connection Password--><property name= "password" value= "ACCP" ></property></beaN></beans>
jdbc Action:
Package Com.pb.jdbc.dao.impl;import Java.sql.connection;import Java.sql.preparedstatement;import Java.sql.resultset;import Java.sql.sqlexception;import Javax.sql.datasource;import Com.pb.entity.Person;import Com.pb.jdbc.dao.persondao;public class Persondaoimpl implements Persondao {private DataSource DataSource; @Override Public Person FindByID (Integer id) {Connection con = null; PreparedStatement PS = null; ResultSet rs = null; Person P=null; String sql= "SELECT * from the person where id=?"; Object [] Params={id}; Gets the connection try {con=datasource.getconnection (); Ps=con.preparestatement (SQL); if (Params!=null) {for (int i = 0; i < params.length; i++) {Ps.setobject (i+1, params[i]); }} rs=ps.executequery (); if (rs!=null) {p=new person (); while (Rs.next ()) {P.setid (Rs.getint ("id"))); P.setname (rs.getstring ("name")); P.setage (Rs.getint ("Age")); }} return p; } catch (SQLException e) {e.printstacktrace (); }finally{try {if (rs!=null) rs.close (); if (ps!=null) ps.close (); if (con!=null) con.close (); } catch (SQLException e) {e.printstacktrace (); }} return null; } public void Setdatasource (DataSource DataSource) {this.datasource = DataSource; }}
Update Applicationcontext.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:p= "http://www.springframework.org/schema/p" xmlns:aop= " Http://www.springframework.org/schema/aop "xsi:schemalocation=" Http://www.springframework.org/schema/beans http ://www.springframework.org/schema/beans/spring-beans-3.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/http Www.springframework.org/schema/aop/spring-aop-3.1.xsd "><!--data source--><bean id=" DataSource "class=" Org.springframework.jdbc.datasource.DriverManagerDataSource "><!--drive--><property name=" Driverclassname "value=" oracle.jdbc.driver.OracleDriver "/><!--url--><property name=" url "value=" jdbc : Oracl:thin: @localhost: 1521:orcl "/><!--connected user name--><property name=" username "value=" ACCP "></ property><!--Connection Password--><property name= "password" value= "ACCP" ></property></bean><!--Persondao Interface implementation class--><bean id= "Persondaoimpl" class= "Com.pb.jdbc.dao.impl.PersonDaoImpl" ><!- -Attribute Association--><property name= "DataSource" ref= "DataSource"/></bean></beans>
Third, JDBC Template
Why do I need jdbctemplate (jdbc template)?
When using JDBC, it is always necessary to perform fixed steps, such as Connection,statement, closing, exception handling, and so on.
JdbcTemplate Effect:
Spring encapsulates common JDBC operations into jdbctemplate, simplifying the development process using JDBC, where developers don't need to care, get connections, and close connections
Change the code above
Package Com.pb.jdbc.dao.impl;import Java.math.bigdecimal;import Java.util.list;import java.util.Map;import Javax.sql.datasource;import Org.springframework.jdbc.core.jdbctemplate;import Com.pb.entity.Person;import Com.pb.jdbc.dao.persondao;public class Jdbctemplatepersondaoimpl implements Persondao {private JdbcTemplate JdbcTempl Ate Look up @Override public person FindByID (Integer ID) by ID {person p=null; The return is a collection, but each element of the collection is a map String sql= "SELECT * from the person where id=?"; Placeholder Object [] params={id}; Call SQL and Placeholder List results=jdbctemplate.queryforlist (sql,params); For (object object:results) {map personmap= (map) Object; Gets the value of each map Long p_id= ((BigDecimal) personmap.get ("id")). Longvalue (); String P_name= (String) personmap.get ("name"); The Integer p_age= ((BigDecimal) personmap.get ("Age")). Intvalue (); Statement p=new person (); P.sEtAge (P_age); P.setid (P_ID); P.setname (P_name); } return p; }//By setting data to get JdbcTemplate instance public void Setdatasource (DataSource DataSource) {jdbctemplate=new JdbcTemplate ( DataSource); }}
Iv. JDBC Template
To use the JdbcTemplate object to complete the JDBC operation. Typically, there are three ways to get JdbcTemplate objects.
- The first way: We can inject a datasource reference in our own defined DAO implementation class to complete the instantiation of the JdbcTemplate. That is, it "injects" DataSource from the outside into the DAO, then instantiates the jdbctemplate itself, and then sets DataSource to the JdbcTemplate object.
- The second way: Configure a jdbctemplate bean in the Spring IoC container, inject the DataSource into it, and then inject jdbctemplate into the custom DAO.
- The Third Way: Spring provides the Org.springframework.jdbc.core.support.JdbcDaoSupport class, which defines the JdbcTemplate property, and also defines the DataSource property , when the DataSource property is set, an instance of JdbcTemplate is created, so our own DAO only needs to inherit the Jdbcdaosupport class and then inject DataSource to
First Kind
public class Userserviceimpl implements UserService { private jdbctemplate jdbctemplate; Public JdbcTemplate getjdbctemplate () { return jdbctemplate; } Injection Method 1 public void Setjdbctemplate (JdbcTemplate jdbctemplate) { this.jdbctemplate = jdbctemplate; } Other methods omitted here ... }
Application.xml prerequisite is that the DataSource 2.2 configuration data source has been configured
<bean id= "JdbcTemplate" class= "org.springframework.jdbc.core.JdbcTemplate" > <property name = " DataSource "ref=" DataSource "> </bean> <bean id=" UserService "class=" Com.hxzy.account.jdbcTemplate.UserServiceImpl "> <property name=" JdbcTemplate "ref=" JdbcTemplate "/> </bean>
The second is instantiating jdbctemplate through a database
public class Userserviceimpl implements UserService { private jdbctemplate jdbctemplate; Injection Method 2 public void Setdatasource (DataSource DataSource) { this.jdbctemplate = new JdbcTemplate (DataSource); } //Other methods omitted ... }
Applicationcontext.xml
Provided that the DataSource 2.2 configuration data source has been configured
The spring configuration file is:
<bean id= "UserService" class= "Com.hxzy.account.jdbcTemplate.UserServiceImpl" > <property name= " DataSource "ref=" DataSource "/> </bean>
The third type:
Inheriting Jdbcdaosupport, which has a jdbctemplate inside it, needs to be injected DataSource attribute to instantiate.
public class Userdaoimpl extends Jdbcdaosupport implements Userdao { @Override public void Save (user user) { String sql = null; This.getjdbctemplate (). update (SQL); Other methods omitted ...
Xml
<bean id= "Userdao" class= "Com.hxzy.account.jdbcTemplate.UserDaoImpl" > <property name= "DataSource" ref = "DataSource"/>
V. JDBC Template Operations Database
Executing DDL and Updates
- DDL statements can be executed using the Execute () method of JdbcTemplate
- To perform update or inert, you can use the update () method;
Package Com.pb.demo;import Java.util.list;import Java.util.map;import javax.sql.datasource;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import org.springframework.jdbc.core.jdbctemplate;/** * 1.JdbcTemplate queryforxxx method executes SQL statement * 2. Both query and update can use the placeholder * 3. The elements in the returned list are map * 4. Update operation with UPDATE * 5. Use the Execute method to perform DDL operations */public class Jdbctemplatedemo {public static void main (St Ring[] args) {ApplicationContext context=new classpathxmlapplicationcontext ("Applicationcontext.xml"); Get Data source DataSource Datasource=context.getbean ("DataSource", Datasource.class); Through the data source instance JdbcTemplate jdbctemplate jt=new jdbctemplate (DataSource); Execute a placeholder for the query statement String sql_v= "SELECT * from the person where name=? and age=? "; Object [] params={"John Doe", 24}; Incoming parameters List result=jt.queryforlist (sql_v,params); For (object Object:result) {//Direct Output Object System.out.println (object); or the output value map map= (map) object; SYSTEM.OUT.PRINTLN ("ID:" +map.get ("id") + "Name:" +map.get ("name") +map.get ("Age"); }//Update String sql_update= "Update person set name=?" where age=? "; The age of 23 is updated to Zhangxiao Object [] pupdate={"Zhangxiao", 23}; The number of rows affected by the database int count=jt.update (sql_update, pupdate); System.out.println ("updated" +count+ "line"); Query total number of records String sql_count= "SELECT COUNT (*) from person"; int Totalcount=jt.queryforint (sql_count); SYSTEM.OUT.PRINTLN ("Total number of records of the person table:" +totalcount); Execute DDL Statement//Create a table String ddl= "CREATE TABLE test (ID number (4) Primary key,name VARCHAR2 (50))"; Jt.execute (DDL); SYSTEM.OUT.PRINTLN ("CREATE table succeeded"); Delete Table String del_table= "drop table test"; Jt.execute (del_table); System.out.println ("Delete table succeeded"); }}
Configuration data such as: 2.2
Package Com.pb.demo;import Java.sql.preparedstatement;import Java.sql.sqlexception;import java.util.ArrayList; Import Java.util.list;import Javax.sql.datasource;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Org.springframework.jdbc.core.batchpreparedstatementsetter;import org.springframework.jdbc.core.jdbctemplate;/* * * Using bulk processing data */public class JdbcTemplateDemo2 {public static void main (string[] args) {ApplicationContext cont Ext=new classpathxmlapplicationcontext ("Applicationcontext.xml"); Get Data source DataSource Datasource=context.getbean ("DataSource", Datasource.class); Through the data source instance JdbcTemplate jdbctemplate jt=new jdbctemplate (DataSource); BULK INSERT Data final int count=200; Final List id=new ArrayList (); Final List name=new ArrayList (); Final List password=new ArrayList (); Set the value for the collection for (int i = 0; i < count; i++) { Id.add (i); Name.add ("name_" +i); Password.add ("Password_" +i); }//refers to processing data String sql= "insert into users values (?,?,?)"; BatchPreparedStatementSetter bps=new BatchPreparedStatementSetter () {@Override public V OID Setvalues (preparedstatement ps, int index) throws SQLException {Ps.setobject (1, id.get (index)); Ps.setobject (2, Name.get (index)); Ps.setobject (3, Password.get (index)); } @Override public int getbatchsize () {return count; } }; Perform insert jt.batchupdate (SQL, BPS); System.out.println ("Insert done!"); }}
The JDBC template operates the database in the form of an object
class inheritance for executing functions:
SqlFunction
Package Com.pb.object;import javax.sql.datasource;import org.springframework.jdbc.object.sqlfunction;/** * Execute function * */ public class Personfunction extends sqlfunction{public personfunction (DataSource ds) { //Initialize super (ds, " Select COUNT (*) from person "); Compile compile ();} }
Perform an added or updated class inheritance Sqlupdate
Package Com.pb.object;import Java.sql.types;import Javax.sql.datasource;import org.springframework.jdbc.object.sqlupdate;/** * Perform add or update * */public class Personupdate extends Sqlupdate {public Personupdate (DataSource ds) { super (ds, "INSERT into person values (?,?,?)"); Set the parameter to data int [] Types={types.bigint,types.varchar,types.integer} in Oracle; Set parameter settypes (types); Compile (); }}
The class that executes the query inherits Mappingsqlquery
Package Com.pb.object;import Java.sql.resultset;import Java.sql.sqlexception;import javax.sql.datasource;import Org.springframework.jdbc.object.mappingsqlquery;import com.pb.entity.person;/** * Object Query * @author Administrator * * * * public class Personquery extends Mappingsqlquery {public personquery (DataSource ds) { super (ds, "select * from Person "); Compile (); } @Override protected Object Maprow (ResultSet rs, int rownum) throws SQLException {person p=new person (); P.setage (Rs.getint ("Age")); P.setid (Rs.getlong ("id")); P.setname (rs.getstring ("name")); return p; }}
Implementing Classes and Interfaces
Package Com.pb.dao;import Java.util.list;import Com.pb.entity.person;public interface Persondao { //query all Public list<person> find (); Increase public void update (person P); Query total number of records public int GetCount (); }
Implementation class
package com.pb.dao.impl;import java.util.list;import Javax.sql.DataSource; Import Com.pb.dao.persondao;import Com.pb.entity.person;import Com.pb.object.personfunction;import Com.pb.object.personquery;import Com.pb.object.personupdate;public class Objectpersondaoimpl implements PersonDao {/ /3 Implementation class private Personfunction pf=null; Execute function private personquery pq=null; Execute query private personupdate pu=null; Execute Update/* * Instantiate object by injecting data source * */public void Setdatasource (DataSource ds) {pf=new personfunction (DS); Pq=new Personquery (DS); Pu=new Personupdate (DS); } @Override Public list<person> find () {return pq.execute (); } @Override public void Update (person p) {//Incoming parameter Pu.update (P.getid (), P.getname (), P.getage ()); } @Override public int getcount () {//Function call return Pf.run () using Run }}
Applicationcontext.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:p= "http://www.springframework.org/schema/ P " xsi:schemalocation=" Http://www.springframework.org/schema/beans http://www.springframework.org/schema/ Beans/spring-beans-3.1.xsd "><bean id=" DataSource "class=" Org.springframework.jdbc.datasource.DriverManagerDataSource "><property name=" Driverclassname "value=" Oracle.jdbc.driver.OracleDriver "/><property name=" url "value=" Jdbc:oracle:thin: @localhost: 1521:orcl "/> <property name= "username" value= "ACCP"/><property name= "password" value= "ACCP"/></bean><bean Id= "Objectpersondao" class= "Com.pb.dao.impl.ObjectPersonDaoImpl" ><property name= "DataSource" ref= " DataSource "></property></bean></beans>
Test class
Package Com.pb.demo;import Java.util.list;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Com.pb.dao.persondao;import Com.pb.entity.person;public class Testobjectjdbc {public static void Main (string[] args) { ApplicationContext Context=new classpathxmlapplicationcontext ("Applicationcontext.xml"); Persondao Opd=context.getbean ("Objectpersondao", persondao.class); Person P=new person (); P.setage (in); P.setid (7); P.setname ("extermination division Too"); Opd.update (p); List<person> Persons=opd.find (); Method System.out.println ("Total Records:" +opd.getcount ()) that invokes the total number of records in the query. for (person per:persons) { System.out.println ("ID:" +per.getid () + "Name:" +per.getname () + "Age:" +per.getage ()); } }}
Spring (vii) Persistence layer