A. JDBC dynamic query
Dynamic query: according to the conditions given by the user to decide what kind of query execution.
1.1 Code
// dynamic query
public List selectDeptByProperty(Departments
departments){
Connection conn =null;
PreparedStatement ps =null;
ResultSet rs = null;
List list = new ArrayList<>();
try{
conn =JdbcUtil.getConnection();
String sql = genSQL(departments);
System.out.println(sql);
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
Departments dept = new Departments();
dept.setDepartmentId(rs.getInt("department_id"));
dept.setDepartmentName(rs.getString("department_name"));
dept.setLocationId(rs.getInt("location_id"));
list.add(dept);
}
}catch(Exception e){
e.printStackTrace ();
}finally{
JdbcUtil.closeResource(ps, conn, rs);
}
return list;
}
// splicing sql statement to be executed
private String genSQL(Departments dept){
StringBuffer sb = new StringBuffer("select * from departments where 1=1 ");
if(dept.getDepartmentId() > 0){
sb.append(" and department_id =
").append(dept.getDepartmentId());
}
if(dept.getDepartmentName() != null &&
dept.getDepartmentName().length() > 0){
sb.append(" and department_name =
'").append(dept.getDepartmentName()).append("'");
}if(dept.getLocationId() > 0){
sb.append(" and location_id =
").append(dept.getLocationId());
}
return sb.toString();
}
2. The application layering
2.1 What is the application hierarchy
Application by creating different packages to tiered project, the project will be divided according to the code to do specific functions, and stored in different packages.
2.2 hierarchical advantage
1, the hierarchical structure is divided into several application layers, each layer only solve part of the problem, through collaboration of the layers
Providing total solutions. Big problem is decomposed into a series of relatively independent sub-problems, localized in each layer, so that
It effectively reduces the size and complexity of a single problem, the first step in the realization of complex systems is the most crucial step points
solution.
2, hierarchical structure has good scalability, provides a flexible support for the evolution of growth in the application of the system, with
Good scalability. When adding new features without making changes to existing code, business logic can get the maximum limit
Reutilization.
3, layered architecture is easy to maintain. After the decomposition of the system, different functionalities are encapsulated in the different layers, and layers
The coupling between layers is significantly reduced. Therefore, when a layer to modify the code, they do not involve an interface between the layer and the layer, not
Serious impact on other layers.
2.3 three-tier structure
A three-layer structure is applied to the entire business is divided into:
- Interface layer (User Interface layer)
- Business logic layer service layer (Business Logic Layer)
- Dao layer data access layer (Data access layer)
I.e., to distinguish objects thought level "high cohesion and low coupling". In the software architecture design, the hierarchical structure is the most common and also the most important kind of structure.
3. Package common BaseDao
3.1 Package update
Different tables have different dao layer interface;
and dao layer interface, but also a common BaseDao interface (which can be seen, more abstract interfaces BaseDao!)
basedao interface implementation class:
TablenameDao interface implementation class:
TablenameDaoImpl class, additions and deletions to the table for these three operations, you can just call the update method BaseDaoImpl class can be done!
TablenameService interface implementation class:
3.2 Packaging query operation
3.2.1 Code
BaseDao Interface
public interface BaseDao {
public int executeUpdate(String sql,Object[] param);
public List find(String sql,Object[] param,Class
clazz);
}
BaseDaoImpl interface class
@Override
public List find(String sql, Object[] param, Class
clazz) {
Connection conn =null;
PreparedStatement ps =null;
ResultSet rs = null;
List list = new ArrayList<>();
try{conn = JdbcUtil.getConnection();
ps = conn.prepareStatement(sql);
//得到参数的个数
ParameterMetaData pmd = ps.getParameterMetaData();
//绑定参数
for(int i=0;i<pmd.getParameterCount();i++){
ps.setObject(i+1, param[i]);
}
//处理结果集
rs = ps.executeQuery();
//获取结果集的信息
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next()){
//完成 ORM 处理:通过 jdk 的反射
T bean =clazz.newInstance();//Departmens d = new
Department();
for(int i=0;i<rsmd.getColumnCount();i++){
//得到列名
String columnName = rsmd.getColumnName(i+1);
//获取列的值
Object value = rs.getObject(columnName);
//通过 BeanUtil 工具类将值当如到对象中
BeanUtils.setProperty(bean, columnName,
value);
}
list.add(bean);
}
}catch(Exception e){
e.printStackTrace();
}finally{
JdbcUtil.closeResource(ps, conn, rs);
}
return list;
}
DepartmentDao 接口
public interface DepartmentsDao extends BaseDao {
public List selectDeptByName(String
deptName);
public void insertDept(Departments dept);
public int updateDept(Departments dept);
public int deleteDeptById(int departmentId);
public List selectDeptByLikeName(String deptName);
}DepartmentDaoImpl 接口实现类
@Override
public List selectDeptByLikeName(String deptName) {
String sql ="select * from departments where
department_name like ?";
Object[] param = new Object[]{"%"+deptName+"%"};
return this.find(sql, param, Dept.class);
}
4. JDBC 驱动加载原理
4.1创建对象的方式
4.2创建对象时三个重要的步骤
•通过类加载器加载 class
•初始化所有静态部分
•为新生对象分配内存
4.3MySQL 驱动类的实例化过程
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}