MVC与三层架构

分包规范

  • web层

    com.xm.web.servlet
    com.xm.web.filter
    com.xm.web.listener
    jsp放在WebContent或者WEB-INF

  • Service层

    com.xm.service 放服务层接口
    com.xm.service.impl 放服务层实现

  • Dao层

    com.xm.dao 方法 dao接口
    com.xm.dao.impl 放dao实现

  • 实体类

    com.xm.domain | com.xm.beans | com.xm.entity | com.xm.pojo

  • 工具类

    com.xm.commons | com.xm.utils

在三层架构中使用事务

使用ThreadLocal创建一个线程变量,相当于一个Map集合,其key为线程id,value可以指定

public class DruidUtils{
    private static DruidDataSource dds;
    private static ThreadLocal<Connection> threadLocal;
    static {
        dds = new DruidDataSource();
        threadLocal  = new ThreadLocal<Connection>();
        InputStream is = DruidUtils.class.getClassLoader().getResourceAsStream("database.properties");
        Properties properties = new Properties();
        try {
            properties.load(is);
            //druid数据源工厂
            dds = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        Connection connection = threadLocal.get();
        if (connection == null) {
            //首次为空
            try {
                connection = dds.getConnection();
                threadLocal.set(connection);//取一个放入线程变量集合
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

    //开启事务
    public static void beginTranscation(){
        Connection connection = getConnection();
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //提交事务
    public static void commitTanscation(){
        Connection connection = getConnection();
        try {
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //回滚事务
    public static void rollbackTranscation(){
        Connection connection = getConnection();
        try {
            connection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //关闭
    public static void close(){
        try {
           Connection connection = getConnection();
           connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}