Examples of the use of DAO data access objects in Java's Spring framework

  • 2020-05-07 19:34:07
  • OfStack

Spring DAO JDBC
 
The main purpose of DAO (data access objects) support provided by Spring is to facilitate the use of different data access technologies in a standard manner, such as JDBC, Hibernate, or JDO. Not only does it allow you to easily switch between these persistence technologies, but it also allows you to code without having to worry about handling specific exceptions in various technologies.
To facilitate the use of various data access technologies such as JDBC, JDO, and Hibernate in one way or another, 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 classes:
JdbcDaoSupport - the base class for JDBC data access objects. One DataSource is required, along with JdbcTemplate for subclasses.
The base class of the HibernateDaoSupport-Hibernate data access object. One SessionFactory is required and HibernateTemplate is provided for subclasses. You can also choose to initialize directly by providing 1 HibernateTemplate, so you can reuse the latter Settings, such as SessionFactory, flush mode, exception translator (exception translator), and so on.
The base class of the JdoDaoSupport-JDO data access object. You need to set up one PersistenceManagerFactory and provide JdoTemplate for subclasses.  
The base class of the JpaDaoSupport-JPA data access object. You need 1 EntityManagerFactory and provide JpaTemplate for subclasses.  
This section focuses on Sping's 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(24), 
  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>: 2008-4-22 15:34:36<br> 
* <b>Note</b>: DAO interface  
*/ 
public interface IUserDAO { 
  public void insert(User user); 

  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>:  The base class DAO , which provides data source injection  
*/ 
public class BaseDAO { 
  private 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> 
* <b>Date</b>: 2008-4-22 15:36:04<br> 
* <b>Note</b>: DAO implementation  
*/ 
public class UserDAO extends 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 id=" + 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 name="url"> 
      <value>jdbc:mysql://localhost:3306/springdb</value> 
    </property> 
    <property 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"/> 
    </property> 
  </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(22)); 
    IUserDAO userDAO = (IUserDAO) context.getBean("userDAO"); 
    userDAO.insert(user); 
    user = userDAO.find(new Integer(1)); 
    System.out.println("name: " + user.getName()); 
  } 
}

 
Operation results:


log4j:WARN No appenders could be 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 Hibernate
 
HibernateDaoSupport - the base class of the Hibernate data access object. One SessionFactory is required, along with HibernateTemplate for subclasses. You can also choose to initialize it directly by providing 1 HibernateTemplate, so you can reuse the latter Settings, such as SessionFactory, flush mode, exception translator (exception translator), and so on.

This section focuses on Sping's support for HibernateTemplate.

Here's an example:
 


drop table if exists user; 

/*==============================================================*/ 
/* Table: user                         */ 
/*==============================================================*/ 
create table user 
( 
  id          bigint AUTO_INCREMENT not null, 
  name         varchar(24), 
  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"> 

<hibernate-mapping> 

  <class name="com.lavasoft.springnote.ch06_hbm_02deTx.User" 
      table="user"> 

    <id name="id" column="id"> 
      <generator class="native"/> 
    </id> 

    <property name="name" column="name"/> 

    <property name="age" column="age"/> 

  </class> 

</hibernate-mapping>

 


/** 
* Created by IntelliJ IDEA.<br> 
* <b>User</b>: leizhimin<br> 
* <b>Date</b>: 2008-4-23 15:37:43<br> 
* <b>Note</b>: DAO interface  
*/ 
public interface IUserDAO { 
  public void insert(User user); 
  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>: 2008-4-23 15:15:55<br> 
* <b>Note</b>: DAO implementation  
*/ 
public class UserDAO implements IUserDAO { 
  private HibernateTemplate hibernateTemplate; 

  public void setSessionFactory(SessionFactory sessionFactory) { 
    this.hibernateTemplate =new HibernateTemplate(sessionFactory); 
  } 

  public void insert(User user) { 
    hibernateTemplate.save(user); 
    System.out.println(" The saved User The object's ID:"+user.getId()); 
  } 

  public User find(Integer id) { 
    User user =(User) hibernateTemplate.get(User.class, id); 
    return user; 
  } 
}

 


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; 
  } 
}

0

 


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; 
  } 
}

1

 
Operation results:


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; 
  } 
}

2


Related articles: