JDBCTemplate

一、步骤

  1. 加载驱动:Class.forName("com.mysql.jdbc.Driver");
  2. 创建连接:Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8", "root", "root");
  3. 执行预处理语句:PreparedStatement preparedStatement = connection.prepareStatement(sql);
  4. 获取结果集:int row = preparedStatement.executeUpdate();ResultSet resultSet = preparedStatement.executeQuery();
  5. 关闭连接:connection.close();

二、事务相关

数据库的事务包含多个操作,在所有操作都成功时,提交事务,所有操作都生效,只要有一个操作不成功,事务回滚,所有操作都不生效。

  1. ThreadLocal类是线程独立的存储空间,可以用来存放一个对象,同一个线程中所有的该类的对象都会访问同一块存储空间,所有得到的都是同一个对象。使用ThreadLocal类,可以使每次操作(每个线程)中得到的Connection都是同一个对象
    • public static final ThreadLocal CONNECTION_THREAD_LOCAL = new ThreadLocal();
    • CONNECTION_THREAD_LOCAL.set(connection);
    • CONNECTION_THREAD_LOCAL.get();
    • CONNECTION_THREAD_LOCAL.remove();
  2. 使用connection.setAutoCommit(false);设置非自动提交
  3. 使用connection.commit();进行事务提交
  4. 使用connection.rollback();进行事务回滚

三、示例代码

package user.controller;

import user.entity.User;
import user.service.UserService;
import user.service.impl.UserServiceImpl;

public class UserController {
    private static UserService userService = null;

    static {
        userService = UserServiceImpl.getInstance();
    }

    public static void main(String[] args) {
        System.out.println(userService.create(new User(0, "leif", 24)));
        System.out.println(userService.changeById(new User(1, "lbc", 24)));
        System.out.println(userService.removeById(1));
        System.out.println(userService.findById(1));
        System.out.println(userService.findAll());
    }
}
package user.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import user.dao.UserDao;
import user.entity.User;
import user.jdbc.JDBCCallback;
import user.jdbc.JDBCTemplate;

public class UserDaoImpl implements UserDao {
    private static JDBCTemplate jdbcTemplate = null;

    static {
        jdbcTemplate = (JDBCTemplate) JDBCTemplate.getInstance();
    }

    private UserDaoImpl() {}

    private static volatile UserDaoImpl userDaoImpl = null;

    public static UserDaoImpl getInstance() {
        if (userDaoImpl == null) {
            synchronized (UserDaoImpl.class) {
                if (userDaoImpl == null) {
                    userDaoImpl = new UserDaoImpl();
                }
            }
        }

        return userDaoImpl;
    }

    @Override
    public int insert(User user) {
        return jdbcTemplate.doDML("INSERT INTO user(name, age) VALUES (?, ?)", new Object[] {user.getName(), user.getAge()});
    }

    @Override
    public int deleteById(int id) {
        return jdbcTemplate.doDML("DELETE FROM user WHERE id = ?", new Object[] {id});
    }

    @Override
    public int updateById(User user) {
        return jdbcTemplate.doDML("UPDATE user SET name = ?, age = ? WHERE id = ?", new Object[] {user.getName(), user.getAge(), user.getId()});
    }

    @Override
    public User selectById(int id) {
        return jdbcTemplate.doDQL("SELECT * FROM user WHERE id = ?", new Object[] {id}, new JDBCCallback() {
            @Override
            public User resultSetToObject(ResultSet resultSet) {
                User user = new User();

                try {
                    user.setId(resultSet.getInt("id"));
                    user.setName(resultSet.getString("name"));
                    user.setAge(resultSet.getInt("age"));
                } catch (SQLException e) {
                    e.printStackTrace();
                }

                return user;
            }
        }).get(0);
    }

    @Override
    public List selectAll() {
        return jdbcTemplate.doDQL("SELECT * FROM user", null, new JDBCCallback() {
            @Override
            public User resultSetToObject(ResultSet resultSet) {
                User user = new User();

                try {
                    user.setId(resultSet.getInt("id"));
                    user.setName(resultSet.getString("name"));
                    user.setAge(resultSet.getInt("age"));
                } catch (SQLException e) {
                    e.printStackTrace();
                }

                return user;
            }
        });
    }
}
package user.dao;

import java.util.List;

import user.entity.User;

public interface UserDao {
    public abstract int insert(User user);

    public abstract int deleteById(int id);

    public abstract int updateById(User user);

    public abstract User selectById(int id);

    public abstract List selectAll();
}
package user.entity;

public class User {
    private int id;
    private String name;
    private int age;

    public User() {}

    public User(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
}
package user.jdbc;

import java.sql.ResultSet;

public interface JDBCCallback {
    public abstract T resultSetToObject(ResultSet resultSet);
}
package user.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import user.util.JDBCUtil;

public class JDBCTemplate {
    private JDBCTemplate() {}

    private static volatile JDBCTemplate jdbcTemplate = null;

    public static JDBCTemplate getInstance() {
        if (jdbcTemplate == null) {
            synchronized (JDBCTemplate.class) {
                if (jdbcTemplate == null) {
                    jdbcTemplate = new JDBCTemplate<>();
                }
            }
        }

        return jdbcTemplate;
    }

    public int doDML(String sql, Object[] objects) {
        int row = 0;
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = JDBCUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql);

            if (objects != null) {
                for (int counter = 0; counter < objects.length; counter++) {
                    preparedStatement.setObject(counter + 1, objects[counter]);
                }
            }

            row = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.getClose(null, preparedStatement, null);
        }

        return row;
    }

    public List doDQL(String sql, Object[] objects, JDBCCallback jdbcCallback) {
        List tList = new ArrayList();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = JDBCUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql);

            if (objects != null) {
                for (int counter = 0; counter < objects.length; counter++) {
                    preparedStatement.setObject(counter + 1, objects[counter]);
                }
            }

            resultSet = preparedStatement.executeQuery();

            while (resultSet.next()) {
                T t = jdbcCallback.resultSetToObject(resultSet);
                tList.add(t);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.getClose(connection, preparedStatement, resultSet);
        }

        return tList;
    }
}
package user.service.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import user.dao.UserDao;
import user.dao.impl.UserDaoImpl;
import user.entity.User;
import user.service.UserService;
import user.util.JDBCUtil;

public class UserServiceImpl implements UserService {
    private static UserDao userDao = null;

    static {
        userDao = UserDaoImpl.getInstance();
    }

    private UserServiceImpl() {}

    private static volatile UserServiceImpl userServiceImpl = null;

    public static UserServiceImpl getInstance() {
        if (userServiceImpl == null) {
            synchronized (UserServiceImpl.class) {
                if (userServiceImpl == null) {
                    userServiceImpl = new UserServiceImpl();
                }
            }
        }

        return userServiceImpl;
    }

    @Override
    public int create(User user) {
        int row = 0;
        Connection connection = JDBCUtil.getConnection();

        try {
            row = userDao.insert(user);
            connection.commit();
        } catch (Exception e) {
            try {
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }

            throw new RuntimeException(e.getMessage());
        } finally {
            JDBCUtil.getClose(connection, null, null);
        }

        return row;
    }

    @Override
    public int removeById(int id) {
        int row = 0;
        Connection connection = JDBCUtil.getConnection();

        try {
            row = userDao.deleteById(id);
            connection.commit();
        } catch (Exception e) {
            try {
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }

            throw new RuntimeException(e.getMessage());
        } finally {
            JDBCUtil.getClose(connection, null, null);
        }

        return row;
    }

    @Override
    public int changeById(User user) {
        int row = 0;
        Connection connection = JDBCUtil.getConnection();

        try {
            row = userDao.updateById(user);
            connection.commit();
        } catch (Exception e) {
            try {
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }

            throw new RuntimeException(e.getMessage());
        } finally {
            JDBCUtil.getClose(connection, null, null);
        }

        return row;
    }

    @Override
    public User findById(int id) {
        return userDao.selectById(id);
    }

    @Override
    public List findAll() {
        return userDao.selectAll();
    }
}
package user.service;

import java.util.List;

import user.entity.User;

public interface UserService {
    public abstract int create(User user);

    public abstract int removeById(int id);

    public abstract int changeById(User user);

    public abstract User findById(int id);

    public abstract List findAll();
}
package user.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtil {
    public static final Properties PROPERTIES = PropertyUtil.getProperties("jdbcTest.properties");
    public static final String DRIVER = PROPERTIES.getProperty("driver");
    public static final String URL = PROPERTIES.getProperty("url");
    public static final String USERNAME = PROPERTIES.getProperty("username");
    public static final String PASSWORD = PROPERTIES.getProperty("password");
    public static final ThreadLocal CONNECTION_THREAD_LOCAL = new ThreadLocal();

    private JDBCUtil() {}

    public static Connection getConnection() {
        Connection connection = CONNECTION_THREAD_LOCAL.get();

        if (connection == null) {
            try {
                Class.forName(DRIVER);
                connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
                connection.setAutoCommit(false);
                CONNECTION_THREAD_LOCAL.set(connection);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return connection;
    }

    public static void getClose(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
                CONNECTION_THREAD_LOCAL.remove();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
package user.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class PropertiesUtil {
    public static final String ROOT_PATH = PropertiesUtil.class.getResource("/").getPath();

    private PropertiesUtil() {}

    public static Properties getProperties(String fileName) {
        Properties properties = new Properties();

        try (
            FileInputStream fileInputStream = new FileInputStream(new File(ROOT_PATH + fileName));
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
        ) {
            properties.load(bufferedInputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return properties;
    }
}
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
username=root
password=root

你可能感兴趣的:(JDBCTemplate)