1. 通过JNDI获得DataSource
不常用
2. 从第三方连接池获得DataSource
Jakarta Commons DBCP
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
...
url
...
username
...
passwd
</bean>
3. 使用jdbcTemplate
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="datasource"
<ref bean="myDataSource"/>
</property>
</bean>
4. jdbcTemplate执行sql
Object[] params = new Object[]{4,"msg4"};
jdbcTemplate.update("insert into t_message(id,name) value(?,?)",params);
jdbcTemplate.update
5. 从数据库中读数据
JdbcTemplate 可以通过query方法获得单条或多条记录,可以通过实现RowCallbackHandler接口,RowMapper接口获得一条记录,转化为对象
jdbcTemplate.query(sql,new Object[]{id}, new org.springframework.jdbc.core.RowCallbackHandler(){
public void processRow(ResultSet rs) throws SQLException{
message = new MyMessage();
message.setId(id);
message.setName(rs.getString("name"));
}
}
....
jdbcTemplate.query(sql,new Object[]{id}, new OneMessage());
内嵌类
public class OneMessage implements RowMapper{
public Object mapRow(ResultSet rs, int row num) throws SQLException{
....
}
}
6. 使用Hibernate
在xml中配置SessionFactory
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="hibernateProperties">
<props>
show_sql, cache, 数据库连接类型,用户名,密码
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.spring...HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
7. lazy
MyMessage message = (MyMessage)hibernateTemplate.load(MyMessage.class,1);
System.out.println(message.getId())
System.out.println(message.getName()) //[color=red]出错[/color]
默认情况下Hibernate 3 采用 lazy方式装载数据,当MyMessage装载完ID属性值时,NAME属性值并未马上装载,直接调用会出错
解决办法1
在class.hbm.xml, 将<class>标签的属性设为false
<class name="MyMessage" table="t__message" lazy="false">
...
</class>
解决办法2
org.hibernate.Session session = hibernateTemplate.getSessionFactory().openSession();
MyMessage message = (MyMessage)session.load(MyMessage.class,1)
System.out.println(message.getId())
System.out.println(message.getName()) 不会出错