引言
在刚开始学习javaweb开发时,接触到的开发模式是MVC,使用原生的servlet在tomcat中开发web项目,因此我在数据访问上也没有用开源框架,而是自己动手封装了一个数据库访问层,但之后对比流行的写法,犯的错误不少,学习到了很多。
最开始自己想法
最开始我的代码是如下放置的:
* bean (业务处理元对象,只包含get和set方法)
* jdbc (数据库访问层)
* tablemanger (继承MySQLManger 具体到每一个表的Manger)
* MySQLHelper.java
* MySQLManger.java
MySQLHelper.java是封装了数据库链接过程,并能放回链接对象。
/**
* 此类是jdbc驱动链接数据库类,封装了链接数据库过程,单例模式保证应用程序与数据库链接唯一
*/
public class MySQLHelper {
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost/taobao?useUnicode=true&characterEncoding=UTF8";
private static final String username = "xxxx";
private static final String password = "xxxxxx";
private Connection connection = null;
private static MySQLHelper instance;
public static Log log = LogFactory.getLog("SimpleLog");
private MySQLHelper(){
try {
Class.forName(JDBC_DRIVER);
log.info("注册jdbc驱动...");
connection = DriverManager.getConnection(DB_URL,username,password);
log.info("数据库链接成功!!!");
}catch (ClassNotFoundException e){
log.error("jdbc驱动注册失败!!!");
log.error(e.toString());
}catch (SQLException e){
log.error("数据库链接失败!!!");
log .error(e.toString());
}
}
public static synchronized MySQLHelper getInstance(){
if(instance !=null){
return instance;
}else{
instance = new MySQLHelper();
return instance;
}
}
public Connection getConnection() {
return connection;
}
public void setConnection(Connection connection) {
this.connection = connection;
}
}
MySQLManger封装了每一个manger获取数据库链接和关闭数据库链接方法。
public abstract class MySQLManger {
private MySQLHelper helper = null;
protected Connection connection = null;
public static Log log = LogFactory.getLog("SimpleLog");
public MySQLManger(){
helper = MySQLHelper.getInstance();
connection = helper.getConnection();
}
/**
* 关闭数据库链接,每次操作完成后必须调用close(),浪费资源
*/
public void close(){
Connection connection = helper.getConnection();
try {
if(connection!= null){
connection.close();
}
}catch (SQLException e){
log.error(e.toString());
}
}
}
我在数据访问的大致思路就是封装数据获取连接的操作,每个表都有一个不同的manger,使用不同的manger对不同的表进行数据访问存取。
下面是对user表的操作的Usermanger:
/**
* 此类是操作user表的类
*/
public class UserManger extends MySQLManger{
private Statement statement = null;
public UserManger(){
try {
statement = connection.createStatement();
}catch(SQLException e){
log.error(e.toString());
}
}
/**
* 添加一个用户数据
* @param id_number 帐号
* @param password 密码
* @param phonenumber 电话号码
* @param address 地址
* @param email_address 邮箱地址
*/
public void addUser(String id_number,String password ,String phonenumber, String address ,String email_address){
try {
statement.execute("INSERT INTO users(number,password ,phonenumber,address,email_address) VALUES ("
+"'"+id_number+"'"+","
+"'"