Blog System Backend Design (2) - Encapsulating Database Operations


Other design of the blog system backend:

1. Preparation and design database

2. Get blog list page function

3. Get the blog details page function

4. Login page function

5. The mandatory login function of the login page

6. Display user information and logout function

7. Publish function

Encapsulate database operations


This step is mainly to encapsulate some basic database operations for later use.

1. Create a db.sql file




Create a db.sql file in the src directory , and implement the statement of building .

-- 这个文件是用来写建库建表的语句的
-- if not exists 是判断当前要创建的数据是否存在
create database if not exists blog_system;

use blog_system;

-- 删除旧表,重新创建新表,删除是为了残留的数据对后续的程序有负面影响
-- if not exists 是为了判断当前的表是否存在
drop table if not exists user;
drop table if not exists blog;

-- 创建博客表
create table blog (
    blogId int primary key auto_increment,
    title varchar(128),
    content varchar(4096),
    postTime dateTime,
    userId int
);

-- 创建用户表
create table user (
    userId int primary key auto_increment,
    username varchar(20) unique, -- 要求用户名要和别人不重复
    password varchar(20)
);

2. Encapsulate the connection operation of the database


To create a new DBUtil class, implement the following code in this class.

public class DBUtil {
    
    
    private static DataSource dataSource = new MysqlDataSource();

    static {
    
    
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/blog_system?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        // 你的数据库密码是什么就写什么,没有就不写
        ((MysqlDataSource) dataSource).setPassword("000000");
    }
    
    // 通过这个方法来建立连接
    public static Connection getConnection() throws SQLException {
    
    
        return dataSource.getConnection();
    }

    // 通过这个方法来释放资源
    public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet) {
    
    
        if (resultSet != null) {
    
    
            try {
    
    
                resultSet.close();
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }

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

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


jdbc:mysql://127.0.0.1:3306/ blog_system ?characterEncoding=utf8&useSSL=false blog_system

in the above statement is your database name.

3. Create entity class


The entity class created here is actually the class corresponding to the records in the table.

For example:
The blog table corresponds to the Blog class, and an object of Bolg corresponds to a record in the table.

The user table corresponds to the User class, and an object of User corresponds to a record in the table.

Next create a new Blog and User class.


(1) Write the code in the Blog class

public class Blog {
    
    
    private int blogId;
    private String title;
    private String content;
    private Timestamp postTime;
    private int userId;
}




The members in the above code should be the same as the attributes in the blog table.

On the basis of the above code, Getter and Setter methods are also generated.

After right-clicking, click the circled location



Then click Getter and Setter in the interface that appears



Select all the members that appear in the interface, and click OK.



complete code

import java.sql.Timestamp;

public class Blog {
    
    
    private int blogId;
    private String title;
    private String content;
    private Timestamp postTime;
    private int userId;

    public int getBlogId() {
    
    
        return blogId;
    }

    public void setBlogId(int blogId) {
    
    
        this.blogId = blogId;
    }

    public String getTitle() {
    
    
        return title;
    }

    public void setTitle(String title) {
    
    
        this.title = title;
    }

    public String getContent() {
    
    
        return content;
    }

    public void setContent(String content) {
    
    
        this.content = content;
    }

    public Timestamp getPostTime() {
    
    
        return postTime;
    }

    public void setPostTime(Timestamp postTime) {
    
    
        this.postTime = postTime;
    }

    public int getUserId() {
    
    
        return userId;
    }

    public void setUserId(int userId) {
    
    
        this.userId = userId;
    }
}



(2) Write the code in the User class.

User should also pay attention to the fact that these members must be consistent with the attributes in the user table.



The remaining steps can be the same as (1), the following is the complete code.

public class User {
    
    
    private int userId;
    private String username;
    private String password;

    public int getUserId() {
    
    
        return userId;
    }

    public void setUserId(int userId) {
    
    
        this.userId = userId;
    }

    public String getUsername() {
    
    
        return username;
    }

    public void setUsername(String username) {
    
    
        this.username = username;
    }

    public String getPassword() {
    
    
        return password;
    }

    public void setPassword(String password) {
    
    
        this.password = password;
    }
}

4. Encapsulate database addition, deletion, modification and query operations


Create a BlogDao and UserDao class, and implement some methods in this class to perform addition, deletion, modification and query operations.

4.1 Create methods in the BlogDao class


Through this class , the basic operations for the blog table are encapsulated.
The modification operation is not involved here for the time being, and the modification operation can also be realized by deleting and adding.

public class BlogDao {
    
    
    // 1.新增一个博客
    public void add(Blog blog) {
    
    

    }

    // 2.根据博客 id 来查询指定博客(博客详情页)
    public Blog selectById(int blogId) {
    
    
        return null;
    }

    // 3.直接查询出数据库中所有的博客列表(博客列表页)
    public List<Blog> selectAll() {
    
    
        return null;
    }
    
    // 4.删除指定博客
    public void delete(int blogId) {
    
    
        
    }
}



When you click to publish an article, the add method will be triggered to add a blog. When you click to view the full text on the blog
list page, selectById will be triggered to jump to the blog details page . The selectAll method can query all blog lists, and the delete button corresponding to the delete method will be implemented later. ① Implement the add method to implement new operations.



// 1.新增一个博客
public void add(Blog blog) {
    
    
    Connection connection = null;
    PreparedStatement statement = null;
    try {
    
    
        // 1.和数据库建立连接
        connection = DBUtil.getConnection();
        // 2.构造 sql
        String sql = "insert into blog values(null, ?, ?, ?, ?)";
        statement = connection.prepareStatement(sql);
        // 替换操作
        statement.setString(1, blog.getTitle());
        statement.setString(2, blog.getContent());
        statement.setTimestamp(3, blog.getPostTime());
        statement.setInt(4, blog.getUserId());
        // 3.执行 sql
        statement.executeUpdate();
    } catch (SQLException e) {
    
    
        e.printStackTrace();
    }finally {
    
    
        // 4.释放资源
        DBUtil.close(connection, statement, null);
    }
}


Because it is a new operation, the sql statement involved here is insert into blog values() .

The parameters in values ​​should be consistent with the previously built blog table.



Because the auto-increment primary key does not need to be set manually, it can be set to null to let it be automatically assigned, so the first parameter is null.
The next few parameters are replaced by the placeholder ? , which will be replaced with the corresponding attribute in the blog table in subsequent operations. So the next few parameters are? . Therefore, the constructed sql statement is: insert into blog values(null, ?, ?, ?, ?) ② Implement the selectById method to query the specified blog



// 2.根据博客 id 来查询指定博客(博客详情页)
public Blog selectById(int blogId) {
    
    
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    try {
    
    
        // 1.和数据库建立连接
        connection = DBUtil.getConnection();
        // 2.构造查询 sql
        String sql = "select * from blog where biogId = ?";
        statement = connection.prepareStatement(sql);
        statement.setInt(1, blogId);
        // 3.执行 sql
        resultSet = statement.executeQuery();
        // 4.遍历结果集和 由于 blogId 在 bolg 表中是唯一的(主键)
        // 此时的查询结果要么是没有查到任何数据,要么只有一条记录
        // 此处可以不使用 while,使用 if 判定即可
        if (resultSet.next()) {
    
    
            Blog blog = new Blog();
            // 把从数据库中读到信息设置到 blog 对象中
            blog.setBlogId(resultSet.getInt("blogId"));
            blog.setTitle(resultSet.getString("title"));
            blog.setContent(resultSet.getString("content"));
            blog.setPostTime(resultSet.getTimestamp("postTime"));
            blog.setUserId(resultSet.getInt("userId"));
            return blog;
        }
    } catch (SQLException throwables) {
    
    
        throwables.printStackTrace();
    }finally {
    
    
        // 4.释放资源
        DBUtil.close(connection, statement, resultSet);
    }
    return null;
}


Because it is to complete the specified query, its sql statement is select * from blog where biogId = ?
Replace the parameter blogId in the method with the placeholder to complete the specified condition query.

When traversing the result set, since the blogId is unique (primary key) in the bolg table, the result of the query either does not find any data or only has one record.

Therefore, you don't need to use while here, but just use if to judge once.


③ Implement the selectAll method to query all blog lists

// 3.直接查询出数据库中所有的博客列表(博客列表页)
public List<Blog> selectAll() {
    
    
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    List<Blog> blogs = new ArrayList<>();
    try {
    
    
        // 1.和数据库建立连接
        connection = DBUtil.getConnection();
        // 2.构造查询 sql
        String sql = "select * from blog";
        statement = connection.prepareStatement(sql);
        // 3.执行sql - 增删改 使用 executeUpdate 查使用 executeQuery
        resultSet = statement.executeQuery();
        // 4.遍历结果集合
        while (resultSet.next()) {
    
    
            Blog blog = new Blog();
            // 把从数据库中读到信息设置到 blog 对象中
            blog.setBlogId(resultSet.getInt("blogId"));
            blog.setTitle(resultSet.getString("title"));
            // 需要注意的是在博客列表页是不需要把整个正文全部显示出来的
            // 这里可以可以设置一个显示的篇幅
            String content = resultSet.getString("content");
            // 将篇幅的长度设置为 128
            if (content.length() >= 128) {
    
    
                // 如果篇幅大于 128 就提取 128 长度的篇幅
                // 这只是一个随便设置的篇幅长度
                // 如果最终显示出来效果不好看,还可以随时更改
                content = content.substring(0, 128) + "...";
            }
            blog.setContent(content);
            blog.setPostTime(resultSet.getTimestamp("postTime"));
            blog.setUserId(resultSet.getInt("userId"));
            // 调用 add 方法添加进去
            blogs.add(blog);
        }
    } catch (SQLException throwables) {
    
    
        throwables.printStackTrace();
    } finally {
    
    
        //  释放资源
        DBUtil.close(connection, statement, resultSet);
   }
    return blogs;
}


It should be noted that the entire text does not need to be displayed on the blog list page,
so the displayed length can be set here.

Here it is set to 128, which is just a random length, if the final display does not look good, you can change it at any time.

Here is to query all blog lists, so use while to traverse the result set and sum.


④ Implement delete to delete the specified blog

 // 4.删除指定博客
 public void delete(int blogId) {
    
    
     Connection connection = null;
     PreparedStatement statement = null;
     try {
    
    
         // 1.和数据库建立连接
         connection = DBUtil.getConnection();
         // 2.构造查询 sql
         String sql = "delete * from blog where blogId = ?";
         statement = connection.prepareStatement(sql);
         statement.setInt(1, blogId);
         // 3.执行sql - 增删改 使用 executeUpdate 查使用 executeQuery
         statement.executeUpdate();
     } catch (SQLException throwables) {
    
    
         throwables.printStackTrace();
     } finally {
    
    
         DBUtil.close(connection, statement, null);
     }
 }


The delete operation is to find the blog to be deleted through the parameter blogId in the method, and then delete it.
The general implementation of the above four methods is the same, but there are individual operations that are different.

It is necessary to establish a connection with the database, construct sql statements, execute sql statements, and finally release resources .
For the query operation, there will be a step of traversing the result set, and the rest of the steps are also consistent.

And when executing sql statements, if it is adding, deleting and modifying, executeUpdate must be used ,
and if it is a query operation, executeQuery must be used .

4.2 Create a method in the UserDao class


Through this class, encapsulate the basic operations on blog table.

// 1.根据 userId 来查用户信息
public User selectById(int userId) {
    
    

}

// 2.根据 username 来查用户信息
public User selectByUsername(String username) {
    
    
    
}



① Implement the selectById method to query user information based on userId.

// 1.根据 userId 来查用户信息
public User selectById(int userId) {
    
    
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    try {
    
    
        // 1.和数据库建立连接
        connection = DBUtil.getConnection();
        // 2.构造 sql 语句
        String sql = "select * from user where userId = ?";
        statement = connection.prepareStatement(sql);
        statement.setInt(1, userId);
        // 3.执行 sql
        resultSet = statement.executeQuery();
        // 4.遍历结果集合
        if (resultSet.next()) {
    
    
            User user = new User();
            user.setUserId(resultSet.getInt("userId"));
            user.setUsername(resultSet.getString("username"));
            user.setPassword(resultSet.getString("password"));
            return user;
        }
    } catch (SQLException throwables) {
    
    
        throwables.printStackTrace();
    } finally {
    
    
        // 5.释放资源
        DBUtil.close(connection, statement, resultSet);
    }
    return null;
}



② Implement the selectByUsername method to query user information based on username.

This method is similar to the method above, except that two steps are different.

first step:

The sql statement constructed by the above method: select * from user where userId = ? .
Changed to the following sql statement.

// 2.构造 sql 语句
String sql = "select * from user where username = ?";


Second step:

Change the **statement.setInt(1, userId);** statement in the above method to the following statement.

statement.setString(1, username);


Mainly change the int type to String type, and change userId to username.

Guess you like

Origin blog.csdn.net/m0_63033419/article/details/130472825