All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.sylinx.hbatis.db.dialect.DefaultDialect Maven / Gradle / Ivy

There is a newer version: 2.0.0.RELEASE
Show newest version
package cn.sylinx.hbatis.db.dialect;

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

import cn.sylinx.hbatis.db.dialect.fs.FluentSqlCreator;
import cn.sylinx.hbatis.db.dialect.fs.FluentSqlCreatorFactory;
import cn.sylinx.hbatis.db.dialect.sql.SqlBuilder;
import cn.sylinx.hbatis.db.dialect.sql.SqlBuilderFactory;
import cn.sylinx.hbatis.type.TypeHandler;
import cn.sylinx.hbatis.type.TypeHandlerRegistry;

@SuppressWarnings("unchecked")
public abstract class DefaultDialect implements Dialect {

	@Override
	public void setParameters(PreparedStatement pst, Object... params) throws SQLException {

		for (int i = 0, size = params.length; i < size; i++) {
			setParameter(pst, i + 1, params[i]);
		}
	}

	protected void setParameter(PreparedStatement pst, int index, Object param) throws SQLException {

		TypeHandler handler = crateTypeHandler(param);
		if (handler != null) {
			handler.setParameter(pst, index, param);
		} else {
			pst.setObject(index, param);
		}
	}

	private TypeHandler crateTypeHandler(Object param) {

		if (param == null) {
			return TypeHandlerRegistry.getInstance().getUnknownTypeHandler();
		}

		Class clz = (Class) param.getClass();
		return TypeHandlerRegistry.getInstance().getTypeHandler(clz);
	}

	@Override
	public void setParameters(PreparedStatement pst, List params) throws SQLException {
		for (int i = 0, size = params.size(); i < size; i++) {
			setParameter(pst, i + 1, params.get(i));
		}
	}

	@Override
	public  T getResult(ResultSet rs, String columnName, Class clz) throws SQLException {

		TypeHandler handler = TypeHandlerRegistry.getInstance().getTypeHandler(clz);
		if (handler != null) {
			return handler.getResult(rs, columnName);
		}

		return (T) rs.getObject(columnName);
	}

	@Override
	public  T getResult(ResultSet rs, int columnIndex, Class clz) throws SQLException {

		TypeHandler handler = TypeHandlerRegistry.getInstance().getTypeHandler(clz);
		if (handler != null) {
			return handler.getResult(rs, columnIndex);
		}

		return (T) rs.getObject(columnIndex);
	}

	@Override
	public  T getResult(CallableStatement cs, int columnIndex, Class clz) throws SQLException {

		TypeHandler handler = TypeHandlerRegistry.getInstance().getTypeHandler(clz);
		if (handler != null) {
			return handler.getResult(cs, columnIndex);
		}

		return (T) cs.getObject(columnIndex);
	}

	@Override
	public SqlBuilder getSqlBuilder() {
		return SqlBuilderFactory.get().getSqlBuilder(getDbType());
	}

	@Override
	public FluentSqlCreator getFluentSqlCreator() {
		return FluentSqlCreatorFactory.get().getFluentSqlCreator(getDbType());
	}

}