Spring AOP动态代理例子

对Oracle数据库的部门表进行增删改查:

话不多说;

1.实体类可以不写.hbm.xml文件直接写注解方式:

package com.jadeon.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@SuppressWarnings("serial")
@Entity
@Table(name = "dept")
public class Dept implements Serializable {

	private Integer deptno;
	private String dname;
	private String loc;

	public Dept() {
		super();
	}

	public Dept(String dname, String loc) {
		super();
		this.dname = dname;
		this.loc = loc;
	}
	
	public Dept(Integer deptno,String dname, String loc) {
		super();
		this.deptno = deptno;
		this.dname = dname;
		this.loc = loc;
	}

	@Id
	@Column(name="deptno")
	@GenericGenerator(name="myGenerator",strategy="increment")
	@GeneratedValue(generator="myGenerator")
	public Integer getDeptno() {
		return deptno;
	}

	public void setDeptno(Integer deptno) {
		this.deptno = deptno;
	}

	@Column(name="dname")
	public String getDname() {
		return dname;
	}

	public void setDname(String dname) {
		this.dname = dname;
	}

	@Column(name="loc")
	public String getLoc() {
		return loc;
	}

	public void setLoc(String loc) {
		this.loc = loc;
	}

}

2.dao接口

 

 

package com.jadeon.dao;

import java.util.List;

public interface BasicDao {
	
	public void saveBasic(T o);
	
	public void updateBasicById(T o);
	
	public void delBasicById(T o);
	
	public T selectBasicById(T o,String column,Object byId);
	
	public List seletctAllBasic(T o);
	
}

实现dao接口类

package com.jadeon.dao.impl;

import java.util.List;

import org.hibernate.criterion.Restrictions;

import com.jadeon.dao.BasicDao;
import com.jadeon.util.DBHelper;

public class BasicDaoImpl implements BasicDao {
	
	@Override
	public void saveBasic(T o) {
		 DBHelper.openSession().save(o);
	}

	@Override
	public void updateBasicById(T o) {
		DBHelper.openSession().merge(o);
	}

	@Override
	public void delBasicById(T o) {
		DBHelper.openSession().delete(o);
	}

	@SuppressWarnings("unchecked")
	@Override
	public T selectBasicById(T o, String column, Object byId) {
		return (T) DBHelper.openSession().createCriteria(o.getClass()).add(Restrictions.eq(column, byId))
				.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List seletctAllBasic(T o) {
		return DBHelper.openSession().createCriteria(o.getClass()).list();
	}

}

3.service接口类

package com.jadeon.service;

import java.util.List;

import com.jadeon.entity.Dept;

public interface DeptService {

	public void saveDept(Dept info);
	
	public void updateDeptById(Dept info);
	
	public Dept selectDeptById(Integer byId);
	
	public List seletctAllDept();

	public void delDeptById(Integer byId);

}

实现service接口类

package com.jadeon.service.impl;

import java.util.List;

import com.jadeon.dao.BasicDao;
import com.jadeon.dao.impl.BasicDaoImpl;
import com.jadeon.entity.Dept;
import com.jadeon.service.DeptService;

public class DeptServiceImpl implements DeptService {

	private BasicDao dao = new BasicDaoImpl();
	@Override
	public void saveDept(Dept info) {
		dao.saveBasic(info);
	}

	@Override
	public void updateDeptById(Dept info) {
		dao.updateBasicById(info);
	}

	@Override
	public void delDeptById(Integer byId) {
		Dept info = dao.selectBasicById(new Dept(), "deptno", byId);
		dao.delBasicById(info);
	}

	@Override
	public Dept selectDeptById(Integer byId) {
		return dao.selectBasicById(new Dept(), "deptno", byId);
	}

	@Override
	public List seletctAllDept() {
		return dao.seletctAllBasic(new Dept());
	}

}

4.帮助类(DBHelper):

package com.jadeon.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class DBHelper {

	private static SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
	private static Session session;
	
	public static Session openSession(){
           //判断session是否打开
         if (session == null || !session.isOpen()) 
			session = sessionFactory.openSession();
		return session;
	}
}

5.strutsxml和Hibernate.cfg.xml、web.xml配置文件

 






    

    
            /allDept.jsp
            /updateDept.jsp
        
        
    






  
  
  	oracle.jdbc.OracleDriver
  	jdbc:oracle:thin:localhost:1521:orcl
  	scott
  	tiger
  	org.hibernate.dialect.OracleDialect
  	
  	true
  	
	
	
  
  



  spring_02_proxy
  
    index.jsp
  

	
		struts
		org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
	
	
	
		struts
		/*
	

6.代理类:

package com.jadeon.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.hibernate.Session;

public class TranscationDynamicProxy implements InvocationHandler{
	
	private Object obj;//需要代理的目标对象  
	
	private Session session;

	public TranscationDynamicProxy() {
		super();
	}

	public TranscationDynamicProxy(Object obj,Session session) {
		super();
		this.obj = obj;
		this.session = session;
	}

	/***
	 * 实例化代理对象
	 * 
	 * @param args
	 * @return
	 */
	public static Object newInstance(Object args,Session session){//将目标对象传入进行代理  
		// 1. 实例化对象
		// 2. 定义的接口,所需要完成事情
		// 3. 开始做事情
		return Proxy.newProxyInstance(
				args.getClass().getClassLoader(), 
				args.getClass().getInterfaces(), 
				new TranscationDynamicProxy(args,session));//返回代理对象  
	}

	// 开始做事情 什么时候触发呢?
	// 在实例化LogDynamicProxy对象时 会触发该方法
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Object result = null;
		try {
			System.out.println("begin recording log...");
			session.beginTransaction().begin();
			result = method.invoke(obj, args);//调用invoke方法,result 存储该方法的返回值  
			session.beginTransaction().commit();
			System.out.println("end recording log...");
		} catch (Exception e) {
			e.printStackTrace();
			session.beginTransaction().rollback();
		} finally {
			//session.close();
		}
		return result;
	}

}


7.action测试类:

package com.jadeon.action;

import java.util.ArrayList;
import java.util.List;

import com.jadeon.entity.Dept;
import com.jadeon.proxy.TranscationDynamicProxy;
import com.jadeon.service.DeptService;
import com.jadeon.service.impl.DeptServiceImpl;
import com.jadeon.util.DBHelper;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class DeptAction extends ActionSupport {

	private List infos = new ArrayList();
	private Dept info = new Dept();

	DeptService service = (DeptService) TranscationDynamicProxy.newInstance(new DeptServiceImpl(), DBHelper.openSession());

	public String getAllDept() {

		infos = service.seletctAllDept();

		return "success";
	}

	public String savaDept() {

		service.saveDept(info);

		return getAllDept();
	}

	public String updateDeptById() {

		if (info.getDname() == null && info.getDeptno() > 0 && info.getLoc() == null) {
			info = service.selectDeptById(info.getDeptno());
			return "update";
		}else{
			service.updateDeptById(info);
			return getAllDept();
		}
	}

	public String delDeptById() {
		
		service.delDeptById(info.getDeptno());

		return getAllDept();
	}

	public List getInfos() {
		return infos;
	}

	public void setInfos(List infos) {
		this.infos = infos;
	}

	public Dept getInfo() {
		return info;
	}

	public void setInfo(Dept info) {
		this.info = info;
	}

}

主页面:




DEPT TABLE INFORMATION


	
SELECT ALL DEPT INFORMATION

查询和删除部门.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>




DEPT TABLE INFORMATION


	

DEPT TABLE INFORMATION

DEPTNO DNAME LOC OPERATION
${dept.deptno} ${dept.dname} ${dept.loc} delete | update
add

添加部门.jsp

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>




DEPT TABLE INFORMATION




	

UPDATE TABLE INFORMATION

DNAME LOC

修改部门.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>




DEPT TABLE INFORMATION




	

UPDATE TABLE INFORMATION

DNAME LOC

 

 

 

你可能感兴趣的:(后端)