Spring DAO's jdbc
Spring-provided DAO (data Access object) support the main purpose is to make it easier to use different data access technologies, such as JDBC, in a standard way, Hibernate, or JDO. Not only does it allow you to easily switch between these persistent technologies, but it allows you to encode without having to deal with specific exceptions in various technologies.
to facilitate the use of various data access technologies in a consistent manner, such as JDBC, JDO, and Hibernate, Spring provides a set of abstract DAO classes for you to extend. These abstract classes provide methods through which you can obtain data sources and other configuration information related to the data access technology you are currently using.
DAO support class:
Jdbcdaosupport-jdbc the base class for data access objects. Requires a DataSource, while providing jdbctemplate for subclasses. The
Hibernatedaosupport-hibernate the base class of the data Access object. Requires a sessionfactory, while providing hibernatetemplate for subclasses. You can also choose to initialize directly by providing a hibernatetemplate, which allows you to reuse the latter's settings, such as sessionfactory, flush mode, exception Translator (Exception translator), and so on. The
Jdodaosupport-jdo the base class of the data Access object. You need to set up a persistencemanagerfactory and provide jdotemplate for subclasses. &NBSP
JPADAOSUPPORT-JPA The base class of the data Access object. Requires a entitymanagerfactory, while providing jpatemplate for subclasses. &NBSP
This section mainly discusses sping support for Jdbcdaosupport.
Here's an example:
drop table if exists user;
/*==============================================================*//
* Table:user * *
/*============= =================================================*/
CREATE TABLE User
(
ID bigint auto_increment Not NULL,
name varchar (in),
age int,
primary key (ID)
);
public class User {
private Integer ID;
private String name;
Private Integer age;
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;
}
Public Integer Getage () {return age
;
}
public void Setage (Integer age) {
this.age = age;
}
}
/** * Created by IntelliJ idea.<br> * <B>USER</B>: leizhimin<br> * <B>DATE</B>: 20 08-4-22 15:34:36<br> * <b>note</b>: DAO interface */public interface Iuserdao {public void insert (User u
SER);
Public User find (Integer ID);
} Import Javax.sql.DataSource;
Import java.sql.Connection;
Import java.sql.SQLException; /** * Created by IntelliJ idea.<br> * <B>NOTE</B>: base class DAO, providing data source injection/public class Basedao {Priva
Te DataSource DataSource;
Public DataSource Getdatasource () {return DataSource;
public void Setdatasource (DataSource DataSource) {this.datasource = DataSource;
Public Connection getconnection () {Connection conn = null;
try {conn = datasource.getconnection ();
catch (SQLException e) {e.printstacktrace ();
Return conn; }/** * Created by IntelliJ idea.<br> * <B>USER</B>: leizhimin<br&Gt * <b>date</b>: 2008-4-22 15:36:04<br> * <B>NOTE</B>: DAO Implementation */public class Userdao Extend
S Basedao implements Iuserdao {public JdbcTemplate getjdbctemplate () {return new JdbcTemplate (Getdatasource ());
public void Insert (user user) {String name = User.getname ();
int age = User.getage (). Intvalue ();
Jdbctemplate.update ("INSERT into User (name,age)"//+ "VALUES (' + name +" ', "+ Age +") ");
String sql = "INSERT into user (Name,age) VALUES (?,?)";
Getjdbctemplate (). Update (Sql,new object[]{name,age}); Public User find (Integer ID) {List rows = getjdbctemplate (). queryForList ("select * from User WHERE i
D= "+ id.intvalue ());
Iterator it = Rows.iterator ();
if (It.hasnext ()) {Map UserMap = (map) it.next ();
Integer i = new Integer (Usermap.get ("id"). toString ());
String name = Usermap.get ("name"). ToString (); Integer age = new Integer (USERMAP.GET ("age"). ToString ());
User user = new user ();
User.setid (i);
User.setname (name);
User.setage (age);
return user;
return null;
}
}
<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE beans Public "-//spring/dtd bean/en" "Http://www.springframework.org/dtd/spring-beans.dtd" > <beans>
; <bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" singleton= "true" > <property name = "Driverclassname" > <value>com.mysql.jdbc.Driver</value> </property> <property na Me= "url" > <value>jdbc:mysql://localhost:3306/springdb</value> </property> <proper
Ty name= "username" > <value>root</value> </property> <property name= "Password" > <value>leizhimin</value> </property> </bean> <bean id= "Basedao" class= "com. Lavasoft.springnote.ch05_jdbc03_temp. Basedao "abstract=" true "> <property name=" DataSource "> <ref bean=" DataSource "/> </proper
ty> </bean> <bean id= "Userdao" Class= "Com.lavasoft.springnote.ch05_jdbc03_temp.
Userdao "parent=" Basedao "> </bean> </beans>
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.FileSystemXmlApplicationContext;
/**
* Created by IntelliJ idea.<br>
* <B>USER</B>: leizhimin<br>
* <b>date </b>: 2008-4-22 15:59:18<br>
* <B>NOTE</B>: Test class, Client */public
class Springdaodemo {public
static void Main (string[] args) {
ApplicationContext context = new Filesystemxmlapplicationcontext ("d:\\_spring\\src\\com\\lavasoft\\springnote\\ch05_jdbc03_temp\\ Bean-jdbc-temp.xml ");
User user = new user ();
User.setname ("Hahhahah");
User.setage (new Integer);
Iuserdao Userdao = (Iuserdao) context.getbean ("Userdao");
Userdao.insert (user);
user = Userdao.find (new Integer (1));
System.out.println ("Name:" + user.getname ());
}
}
Run Result:
Log4j:warn No Appenders could is found for logger (org.springframework.core.CollectionFactory).
Log4j:warn Please initialize the log4j system properly.
Name:jdbctemplate
Process finished with exit code 0
Spring DAO's Hibernate
Hibernatedaosupport-hibernate the base class of the data Access object. Requires a sessionfactory, while providing hibernatetemplate for subclasses. You can also choose to initialize directly by providing a hibernatetemplate, which allows you to reuse the latter's settings, such as sessionfactory, flush mode, exception Translator (Exception translator), and so on.
This section mainly discusses the support of Sping to Hibernatetemplate.
Here's an example:
drop table if exists user;
/*==============================================================*//
* Table:user * *
/*============= =================================================*/
CREATE TABLE User
(
ID bigint auto_increment Not NULL,
name varchar (in),
age int,
primary key (ID)
);
/**
* Created by IntelliJ idea.<br>
* <B>NOTE</B>: Hiberante entity class */public
class User {
private Integer ID;
private String name;
Private Integer age;
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;
}
Public Integer Getage () {return age
;
}
public void Setage (Integer age) {
this.age = age;
}
}
<?xml version= "1.0" encoding= "Utf-8"?> <!
DOCTYPE hibernate-mapping public
"-//hibernate/hibernate mapping DTD 3.0//en"
"http:// Hibernate.sourceforge.net/hibernate-mapping-3.0.dtd ">
/** * Created by IntelliJ idea.<br> * <B>USER</B>: leizhimin<br> * <B>DATE</B>: 20 08-4-23 15:37:43<br> * <b>note</b>: DAO interface */public interface Iuserdao {public void insert (User u
SER);
Public User find (Integer ID);
} Import org.hibernate.SessionFactory;
Import Org.springframework.orm.hibernate3.HibernateTemplate; /** * Created by IntelliJ idea.<br> * <B>USER</B>: leizhimin<br> * <B>DATE</B>: 200 8-4-23 15:15:55<br> * <B>NOTE</B>: DAO Implementation */public class Userdao implements Iuserdao {private Hib
Ernatetemplate hibernatetemplate; public void Setsessionfactory (Sessionfactory sessionfactory) {this.hibernatetemplate =new hibernatetemplate (SessionF
Actory);
public void Insert (user user) {hibernatetemplate.save (user);
SYSTEM.OUT.PRINTLN ("The ID of the saved user object:" +user.getid ()); Public user find (Integer ID) {User user = (user) HiBernatetemplate.get (User.class, id);
return user;
}
}
<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE beans Public "-//spring/dtd bean/en" "Http://www.springframework.org/dtd/spring-beans.dtd" > <beans> <bean id= "DataSource" class= "Org.springframework.jdbc.datasource.DriverManagerDataSource" > <property Name= "Driverclassname" > <value>com.mysql.jdbc.Driver</value> </property> <propert Y name= "url" > <value>jdbc:mysql://localhost:3306/springdb</value> </property> <PR Operty name= "username" > <value>root</value> </property> <property name= "Password"
> <value>leizhimin</value> </property> </bean> <bean id= "Sessionfactory" class= "Org.springframework.orm.hibernate3.LocalSessionFactoryBean" destroy-method= "Close" > <propert Y name= "DataSource" > <ref bean= "dataSource"/> </property> <pRoperty name= "Mappingresources" > <list> <value>com/lavasoft/springnote/ch06_hbm_02protx/use
r.hbm.xml</value> </list> </property> <property name= "Hibernateproperties" > <props> <prop key= "Hibernate.dialect" > Org.hibernate.dialect.MySQLDialect </ prop> </props> </property> </bean> <bean id= "Userdao class=" Com.lavasoft.spri
Ngnote.ch06_hbm_02proTx.UserDAO "> <property name=" sessionfactory "> <ref bean=" sessionfactory "/>
</property> </bean> </beans>
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.FileSystemXmlApplicationContext;
/**
* Created by IntelliJ idea.<br>
* <B>NOTE</B>: Test class, Client */public
class Springhibernatedemo {public
static void Main (string[] args) {
ApplicationContext context =new Filesystemxmlapplicationcontext ("D:\\_spring\\src\\com\\lavasoft\\springnote\\ch06_hbm_02protx\\bean-hbm_ Tx.xml ");
Create DAO object
Iuserdao Userdao = (Iuserdao) context.getbean ("Userdao");
User user = new user ();
User.setname ("Caterpillar");
User.setage (new Integer);
Userdao.insert (user);
user = Userdao.find (new Integer (1));
System.out.println ("Name:" + user.getname ());
}
}
Run Result:
Log4j:warn No Appenders could is found for logger (org.springframework.core.CollectionFactory).
Log4j:warn Please initialize the log4j system properly.
Id:18
name:jdbctemplate
Process finished with exit code 0 for the saved user object