springjdbc简述
Spring将替我们完成所有使用JDBC API进行开发的单调乏味的、底层细节处理工作。
操作JDBC时Spring可以帮我们做这些事情:
定义数据库连接参数,打开数据库连接,处理异常,关闭数据库连接
我们仅需要关注:
声明SQL语句,处理每一次得到的结果
Spring JDBC模块有什么作用?
Spring的JDBC模块负责数据库资源管理和错误处理,大大简化了开发人员对数据库的操作,使得开发人员可以从繁琐的数据库操作中解脱出来,从而将更多的精力投入到编写业务逻辑当中。
一个较为简单的例子与讲解
1、创建个数据库,库名为shiyan, 表名userinfo
2、定义实体类
//实体类
public class UserInfo {
private int id;
private String name;
private String pwd;
private String realName;
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 String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public UserInfo(int id, String name, String pwd, String realName) {
this.id = id;
this.name = name;
this.pwd = pwd;
this.realName = realName;
}
public UserInfo() {
}
}
3、正对用户所做的操作写接口
import cn.yyj.entity.UserInfo;
import java.util.List;
public interface UserInfoDao {
//实现查所有 修改
public List<UserInfo> findUserAll();
public void Update(UserInfo ui);
}
4、实现类—实现这个方法
import cn.yyj.dao.UserInfoDao;
import cn.yyj.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Repository
//@Repository用在持久层的接口上,这个注解是将接口的一个实现类交给spring管理
public class UserInfoDaoImpl implements UserInfoDao {
//jdbcTemplate 模板 做了封装
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Autowired//自动装配
private JdbcTemplate jdbcTemplate;//get set 方法
@Override
public List<UserInfo> findUserAll() {
//sql语句 Userinfo是个接口 里面有未实现的方法 去实现他里面的方法
return jdbcTemplate.query("select * from userinfo", new RowMapper<UserInfo>() {//返回是一个集合list
@Nullable
@Override
public UserInfo mapRow(ResultSet rs, int i) throws SQLException {
UserInfo as = new UserInfo();
as.setId(rs.getInt(1));
as.setName(rs.getString(2));
as.setPwd(rs.getString(3));
as.setRealName(rs.getString(4));
return as;
}
});
}
@Override
public void Update(UserInfo ui) {
jdbcTemplate.update("UPDATE userinfo SET username=? WHERE id=?",ui.getName(),ui.getId());
}
}
5、Service
import cn.yyj.dao.UserInfoDao;
import cn.yyj.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
/* 1、 其getBean的默认名称是类名(头字母小写),可以@Service(“xxxx”)这样来指定,
2、其定义的bean默认是单例的,可以使用@Service(“beanName”) @Scope(“prototype”)来改变。
3、可以通过@PostConstruct和@PreDestroy指定初始化方法和销毁方法(方法名任意)
*/
public class UserInfoService {
@Autowired
private UserInfoDao userInfoDao;
//get set 方法
public UserInfoDao getUserInfoDao() {
return userInfoDao;
}
public void setUserInfoDao(UserInfoDao userInfoDao) {
this.userInfoDao = userInfoDao;
}
public List<UserInfo> findUserAll(){
return userInfoDao.findUserAll();
}
public void Update(UserInfo ui){
userInfoDao.Update(ui);
}
}
6、创建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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--自动扫描上下文包-->
<context:component-scan base-package="cn.yyj.*"></context:component-scan>
<!--配置数据源-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/shiyan"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--事务管理-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:advice id="txadvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
<tx:method name="update*" propagation="REQUIRED"></tx:method>
<tx:method name="*"></tx:method>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="services" expression="execution(* cn.yyj.dao.impl.*.*(..))"></aop:pointcut>
<aop:advisor advice-ref="txadvice" pointcut-ref="services"></aop:advisor>
</aop:config>
</beans>
7、构建测试类
import cn.yyj.entity.UserInfo;
import cn.yyj.service.UserInfoService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
UserInfoService us= (UserInfoService) ac.getBean("userInfoService");
List<UserInfo> list=us.findUserAll();
//遍历
for (UserInfo u:list){
System.out.println(u.getName());
}
}
}
结果:
总结:
消除样板代码.在过去在无服务器环境中进行JDBC调用的过去,总是有4-5步.加载驱动程序(Class.forName),获取连接,创建语句/预准备语句,执行查询并获取ResultSet,迭代结果集并获取结果,关闭您打开的所有句柄.尝试捕SQLExceptions和其他已检查的异常.
这得到了很多抽象,Spring工具允许您使用配置管理大量这些,简化并消除重复代码并消除大量JDBC错误.