首先,来一个干货,图中包括了使用Spring需要的jar包。
第一步:在写项目之前我们先把jar包导入,然后建立beans.xml文件,以下为内容:
代码解释:
1、此部分为schema,,它定义了xml文档的结构,内容和语法,包括元素和属性、关系的结构以及数据类型等等。
2、 Spring接管数据库,不用我们自己编写连接数据库的代码,此项工作由Spring帮助我们完成,Spring将Connection打开放入ThreadLocal中。注意id名必须为dataSource
3、配置事务管理器,Spring采用声明性事务来解决本地事务的提交以及回滚操作。
4、component-scan 将com.icss.biz及com.icss.dao扫描
第二步:把dataSource通过注解方法,注入到BaseDao(也可以通过set方式注入)
package com.icss.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class BaseDao extends JdbcDaoSupport {
/**
* 从ThreadLocal中取数据库连接 (如果ThreadLocal中为null,就打开一个新连接)
*/
public Connection openConnection() throws Exception{
return this.getConnection(); //从spring的上下文中获取一个Conntion对象
}
@Autowired
public void setMyDataSource(org.springframework.jdbc.datasource.DriverManagerDataSource dataSource){
super.setDataSource(dataSource);
}
第三步:Dao层关键:@Repository(“bookDao”)
package com.icss.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.icss.dto.CBook;
import com.icss.entiy.TBook;
@Repository("bookDao")
public class BookDao extends BaseDao{
/**
*修改图书数量
* @param num>0Ϊ�ӿ�� num<0Ϊ�����
* @throws Exception
*/
public int updateBookNum(String isbn,int num) throws Exception{
String sql = "update tbook set num=num+? where isbn=?";
Connection conn = this.openConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, num);
ps.setString(2, isbn);
int rows = ps.executeUpdate();
ps.close();
return rows;
}
/*
* 获得图书信息
*/
public TBook getBookInfo(String isbn)throws Exception {
TBook bk=null;
String sql="select * from tbook where isbn=?";
Connection conn = this.openConnection();
PreparedStatement ps= conn.prepareStatement(sql);
ps.setString(1, isbn);
ResultSet rs= ps.executeQuery();
while(rs.next()){
bk=new TBook();
bk.setAuthor(rs.getString("author"));
bk.setBname(rs.getString("bname"));
bk.setCid(rs.getString("cid"));
bk.setIsbn(rs.getString("isbn"));
bk.setNum(rs.getInt("num"));
bk.setPdate(rs.getDate("pdate"));
bk.setPicurl(rs.getString("picurl"));
bk.setPress(rs.getString("press"));
bk.setPrice(rs.getDouble("price"));
}
rs.close();
ps.close();
return bk;
}
public List getMainBooks() throws Exception{
List books=null;
String sql="select * from tbook b,TCategory c where b.cid=c.cid order by b.pdate desc limit 0,20";
Connection conn = this.openConnection();
PreparedStatement ps= conn.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
books = new ArrayList<>(20);
while(rs.next()){
CBook bk = new CBook();
bk.setAuthor(rs.getString("author"));
bk.setBname(rs.getString("bname"));
bk.setCid(rs.getString("cid"));
bk.setCname(rs.getString("cname"));
bk.setIsbn(rs.getString("isbn"));
bk.setNum(rs.getInt("num"));
bk.setPdate(rs.getDate("pdate"));
bk.setPicurl(rs.getString("picurl"));
bk.setPress(rs.getString("press"));
bk.setPrice(rs.getDouble("price"));
books.add(bk);
}
rs.close();
ps.close();
return books;
}
}
第四步:biz层关键:@Service(“bookBiz”)
@Autowired
private UserDao userDao;
@Autowired
private BookDao bookDao;
package com.icss.biz;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.icss.dao.BookDao;
import com.icss.dao.UserDao;
import com.icss.dto.CBook;
import com.icss.entiy.TBook;
import com.icss.exception.InputEmptyException;
@Service("bookBiz")
public class BookBiz {
@Autowired
private UserDao userDao;
@Autowired
private BookDao bookDao;
/**
* ��ȡ���ﳵ�е�ͼ������
* @param isbns
* @return
* @throws Exception
*/
public List getShopcarData(Set isbns) throws Exception{
return userDao.getShopcarData(isbns);
}
/*
* ��ȡͼ��������Ϣ
*/
public TBook getBookInfo(String isbn)throws Exception{
return bookDao.getBookInfo(isbn);
}
/**
* ��ȡǰ20��ͼ��
* @return
* @throws Exception
*/
public List getMainBooks() throws Exception{
return bookDao.getMainBooks();
}
}
事务回滚实例:
@Transactional(rollbackFor=Throwable.class)
package com.icss.biz;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.icss.dao.BookDao;
import com.icss.dao.OrderDao;
import com.icss.dao.UserDao;
import com.icss.entiy.TBook;
import com.icss.entiy.TOrder;
import com.icss.entiy.TUser;
import com.icss.entiy.TorderDetail;
import com.icss.exception.InputEmptyException;
import com.icss.util.OrderUtil;
@Service("userBiz")
public class UserBiz {
@Autowired
private UserDao userDao;
@Autowired
private OrderDao orderDao;
@Autowired
private BookDao bookDao;
/**
* ͼ付款
* @param user
* @param books
* @return �����ܶ�
* @throws Exception
*/
@Transactional(rollbackFor=Throwable.class)
public double payBookMoney(TUser user,Map books) throws Exception{
if(user == null){
throw new InputEmptyException("用户名不能为空");
}
if(books == null || books.size()==0){
throw new InputEmptyException("图书数量不能为空");
}
double allMoney = 0;
List tbooks = getShopcarData(books.keySet());
for(TBook bk : tbooks){
allMoney = allMoney + bk.getPrice()*books.get(bk.getIsbn());
}
userDao.updateUserAccount(user.getUname(),-allMoney); //修改账户余额
TOrder order = getNewOrder(user,allMoney);
orderDao.addNewOrder(order); //new一个新订单
user.setDno(order.getDno());
Set keys = books.keySet();
for(String isbn : keys){
TorderDetail detail = new TorderDetail();
detail.setBcount(books.get(isbn));
detail.setBprice(getBookPrice(isbn,tbooks));
detail.setDno(order.getDno());
detail.setIsbn(isbn);
orderDao.addOrderDetail(detail); //添加一个新订单
bookDao.updateBookNum(isbn, -books.get(isbn));
}
return allMoney;
}
第五步:使用getBean()调用
private BookBiz bookBiz = (BookBiz)AppContext.getBean(“bookBiz”);
package com.icss.action;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.icss.biz.BookBiz;
import com.icss.biz.OrderBiz;
import com.icss.entiy.TBook;
import com.icss.util.AppContext;
import com.icss.util.Log;
/**
* Servlet implementation class BookDetailSvl
*/
@WebServlet("/BookDetailSvl")
public class BookDetailSvl extends HttpServlet {
private static final long serialVersionUID = 1L;
private BookBiz bookBiz = (BookBiz)AppContext.getBean("bookBiz");
/**
* @see HttpServlet#HttpServlet()
*/
public BookDetailSvl() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String isbn=request.getParameter("isbn");
TBook book=null;
try {
book=bookBiz.getBookInfo(isbn);
request.setAttribute("book", book);
request.getRequestDispatcher("/WEB-INF/main/BookDetail.jsp").forward(request, response);
} catch (Exception e) {
Log.logger.error(e.getMessage());
request.setAttribute("msg", "�����쳣�������Ա��ϵ");
request.getRequestDispatcher("/WEB-INF/err/error.jsp").forward(request,response);
}
}
}
AppContext的主要代码
package com.icss.util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppContext {
public static ApplicationContext context; //静态变量
static{
context = new ClassPathXmlApplicationContext("beans.xml"); //读取beans.xml文件
}
public static Object getBean(String beanName){
return context.getBean(beanName);
}
}
总结:
@Autowired:它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。 通@Autowired的使用来消除 set ,get方法。
@Repository() :它用于将数据访问层 (DAO 层 ) 的类标识为 Spring Bean。
@Service():告诉spring创建一个实现类的实例,用于Biz层注解。
@Transactional:是声明式事务管理 编程中使用的注解。