SpringBoot整合JDBC(二)

基本的增删查改功能。

添加用户

新建POJO

POJO(Plain Ordinary Java Object)简单的Java对象,实际就是普通JavaBeans。

public class Users {
    private Integer userid;
    private String username;
    private String usersex;

    public Integer getUserid() {
        return userid;
    }

    public void setUserid(Integer userid) {
        this.userid = userid;
    }

    public String getUsername() {
        return username;
    }

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

    public String getUsersex() {
        return usersex;
    }

    public void setUsersex(String usersex) {
        this.usersex = usersex;
    }
}
创建页面(基于Thymeleaf)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Title</title>
</head>
<body>
    <form th:action="@{/user/addUser}" method="post">
        <input type="text" username="username"><br/>
        <input type="text" usersex="usersex"><br/>
        <input type="submit" value="OK"/>
    </form>
</body>
</html>

Thymeleaf于templates目录下,不能直接跳转。故需要一个页面跳转的Controller。

@Controller
public class PageController {
    /**
     * 页面跳转方法
     */
    @RequestMapping("/{page}")
    public String showPage(@PathVariable String page) {
        return page;
    }
}

"favicon.ico"问题的解决:

<link rel="shortcut icon" href="../static/icon/Cicon1.ico" th:href="@{../static/icon/Cicon1.ico}"/>
业务实现

后端业务的实现主要依靠于Controller、Service和Dao的配合。

Controller
@Controller
@RequestMapping("/user")    //前缀,用于前端页面的定位
public class UserController {
    @Autowired
    private UsersService usersService;
    /**
     * 添加用户
     * @return
     */
    @RequestMapping("/addUser")
    public String addUser(Users users) {
        try {
            this.usersService.addUser(users);
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        return "redirect:/success"; //重定向
    }
}

Service

接口层:

public interface UsersService {
    void addUser(Users users);
}

实现层(Impl):

/**
 * 用户管理业务层
 */
@Service
public class UsersServiceImpl implements UsersService {
    @Autowired
    private UsersDao usersDao;

    /**
     * 添加用户
     * @param users
     */
    @Override
    @Transactional  //考虑到事务问题,操作为DML时需该注解
    public void addUser(Users users) {
        this.usersDao.insertUsers(users);
    }
}
Dao

接口层:

public interface UsersDao {
    void insertUsers(Users users);
}

实现层:

/**
 * 持久层
 */
@Repository
public class UsersDaoImpl implements UsersDao {
    //数据源自带,注入后即可使用相关API
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 添加用户
     * @param users
     */
    @Override
    public void insertUsers(Users users) {
        String sql = "insert into users(username, usersex) values(?, ?)";
        this.jdbcTemplate.update(sql, users.getUsername(), users.getUsersex());
    }
}

查询用户

showUser.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:th="http://www.thymeleaf.org">
<link rel="shortcut icon" href="../static/icon/Cicon1.ico" th:href="@{/static/icon/Cicon1.ico}"/>
<head>
    <title>ShowUsers</title>
</head>
<body>
    <table border="1" align="center">
        <tr>
            <th>UserID</th>
            <th>UserName</th>
            <th>UserSex</th>
            <th>Operation</th>
        </tr>
        <tr th:each="u : ${list}">
            <td th:text="${u.userid}"></td>
            <td th:text="${u.username}"></td>
            <td th:text="${u.usersex}"></td>
            <td>
                <a th:href="@{/user/preUpdateUser(id=${u.userid})}">Change</a>
                <a th:href="@{/user/deleteUser(id=${u.userid})}">Delete</a>
            </td>
        </tr>
    </table>
</body>
</html>
Controller
 	/**
     * 查询全部用户
     */
    @RequestMapping("/findUserAll")
    public String findUserAll(Model model) {
        List<Users> list = null;
        try {
            list = this.usersService.findUserAll();
            model.addAttribute("list", list);
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        return "showUsers";
    }
Service
	/**
     * 查询全部用户
     * @return
     */
    @Override   //查询并不需要加事务
    public List<Users> findUserAll() {
        return this.usersDao.selectUserAll();
    }
Dao
	/**
     * 查询全部用户
     * @return
     */
    @Override
    public List<Users> selectUserAll() {
        String sql = "select * from users";
        //在query中创建List,直接调用RowMapper返回即可
        return this.jdbcTemplate.query(sql, new RowMapper<Users>() {
            /**
             * 结果集的映射
             * @param resultSet
             * @param i resultSet的迭代因子
             * @return
             * @throws SQLException
             */
            @Override
            public Users mapRow(ResultSet resultSet, int i) throws SQLException {
                Users users = new Users();
                users.setUserid(resultSet.getInt("userid"));
                users.setUsername(resultSet.getString("username"));
                users.setUsersex(resultSet.getString("usersex"));
                return users;
            }
        });
    }

更新用户

预更新查询
updateUser.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:th="http://www.thymeleaf.org">
<link rel="shortcut icon" href="../static/icon/Cicon1.ico" th:href="@{/static/icon/Cicon1.ico}"/>
<head>
    <title>updateUser</title>
</head>
<body>
    <form th:action="@{/user/updateUser}" method="post">
        <input type="hidden" name="userid" th:value="${user.userid}">
        <input type="text" name="username" th:value="${user.username}"><br>
        <input type="text" name="usersex" th:value="${user.usersex}"><br>
        <input type="button" value="OK">
    </form>
</body>
</html>
Controller
	/**
     * 预更新用户查询
     */
    @RequestMapping("/preUpdateUser")
    public String preUpdateUser(Integer id, Model model) {
        try {
            Users user = this.usersService.findUserById(id);
            model.addAttribute("user", user);
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        return "updateUser";
    }
Service
	/**
     * 预更新查询
     * @param id
     * @return
     */
    @Override
    public Users findUserById(Integer id) {
        return this.usersDao.selectUserById(id);
    }
Dao
@Override
    public Users selectUserById(Integer id) {
        Users user = new Users();
        String sql = "select * from users where userid = ?";
        Object[] arr = new Object[]{id};
        this.jdbcTemplate.query(sql, arr, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet resultSet) throws SQLException {
                user.setUserid(resultSet.getInt("userid"));
                user.setUsername(resultSet.getString("username"));
                user.setUsersex(resultSet.getString("usersex"));
            }
        });
        return user;
    }
更新用户信息
Controller
 	/**
     * 更新用户
     */
    @RequestMapping("/updateUser")
    public String updateUser(Users users) {
        try {
            this.usersService.modifyUser(users);
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        return "redirect:/success";
    }
Service
	/**
     * 更新用户
     * @param users
     */
    @Override
    @Transactional
    public void modifyUser(Users users) {
        this.usersDao.updateUser(users);
    }
Dao
    /**
     * 更新用户
     * @param users
     */
    @Override
    public void updateUser(Users users) {
        String sql = "update users set username = ?, usersex = ? where userid = ?";
        this.jdbcTemplate.update(sql, users.getUsername(), users.getUsersex(), users.getUserid());
    }
删除指定用户
Controller
    /**
     * 删除用户
     * @param id
     * @return
     */
    @RequestMapping("deleteUser")
    public String deleteUser(Integer id) {
        try {
            this.usersService.dropUser(id);
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        return "redirect:/success";
    }
Service
    /**
     * 删除用户
     * @param id
     */
    @Override
    public void dropUser(Integer id) {
        this.usersDao.deletUserById(id);
    }
Dao
    /**
     * 删除用户
     * @param id
     */
    @Override
    public void deletUserById(Integer id) {
        String sql = "delete from users where userid = ?";
        this.jdbcTemplate.update(sql, id);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot整合MyBatis-Plus非常简单,可以按照以下步骤进行操作: 1. 添加MyBatis-Plus和相关依赖:在`pom.xml`文件中添加以下依赖: ```xml <dependencies> <!-- Spring Boot Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- MyBatis-Plus Starter --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>最新版本号</version> </dependency> <!-- MySQL Connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> ``` 自行替换`最新版本号`为MyBatis-Plus的最新版本号。 2. 配置数据源信息:在`application.properties`(或`application.yml`)文件中配置数据库连接信息,例如: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 3. 创建实体类和Mapper接口:创建与数据库表对应的实体类,使用`@TableName`注解指定表名,然后创建对应的Mapper接口,继承自`BaseMapper`。 ```java @TableName("user") // 指定对应的表名 public class User { private Long id; private String name; // getter和setter方法省略... } public interface UserMapper extends BaseMapper<User> { } ``` 4. 编写业务逻辑:可以创建Service层来封装业务逻辑,使用`@Service`注解标记为Spring的Bean。 ```java @Service public class UserService { @Autowired private UserMapper userMapper; public User getUserById(Long id) { return userMapper.selectById(id); } // 其他业务方法... } ``` 5. 使用MyBatis-Plus提供的API:MyBatis-Plus提供了丰富的API,可以方便地操作数据库,例如查询、插入、更新和删除等操作。 ```java @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/users/{id}") public User getUser(@Pa
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值