美文网首页
SpringBoot学习day90:整合JDBC和MyBatis

SpringBoot学习day90:整合JDBC和MyBatis

作者: 开源oo柒 | 来源:发表于2019-11-25 21:02 被阅读0次

一、SpringBoot整合JDBC:

1.创建项目:

>使用IDEA搭建项目环境,新建一个空的项目;在项目中创建模块。

空项目
模块
创建完成的目录结构
  • 创建数据库表:
CREATE TABLE `users` (
  `userid` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) DEFAULT NULL,
  `userage` int(5) DEFAULT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;

2.修改POM文件,添加相关的依赖:

>添加Thymeleaf启 动 器 坐 标;JDBC启 动 器 坐 标 ;数 据 库 驱 动 坐 标;

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--thymeleaf启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--JDBC启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--MySql数据库驱动坐标-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <!--Druid数据源依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
  • 通过配置文件配置数据源和链接池:
spring.datasource.url=jdbc:mysql://localhost:3306/ssm
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
  • 创建实体类:
public class Users {
    private Integer userid;
    private String username;
    private Integer userage;

    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 Integer getUserage() {
        return userage;
    }
    public void setUserage(Integer userage) {
        this.userage = userage;
    }
}

3.创建Dao持久层:

Spring对数据库的操作在jdbc上面做了深层次的封装,使用spring的注入功能,可以把DataSource注册到JdbcTemplate之中。
JdbcTemplate主要提供的方法:
(1)execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
(2)update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate方法用于执行批处理相关语句;
(3)query方法及queryForXXX方法:用于执行查询相关语句;
(4)call方法:用于执行存储过程、函数相关语句。

  • 使用JbdcTemplate操作数据库:
    (1)查询所有用户:
@Override
    public List<Users> findAll() {
        String sql = "select *from users";
        return this.jdbcTemplate.query(sql, new RowMapper<Users>() {
            @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.setUserage(resultSet.getInt("userage"));
                return users;
            }
        });
    }

(2)添加用户:

@Repository
public class UserDaoImpl implements UsersDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void insertUser(Users user) {
        String sql = "insert into users(username,userage) values(?,?)";
        jdbcTemplate.update(sql, user.getUsername(), user.getUserage());
    }
}

(3)删除用户:

    @Override
    public void deleteUser(int userid) {
        String sql = "delete from users where userid=?";
        jdbcTemplate.update(sql, userid);
    }

(4)修改用户:

 @Override
    public Users findById(int id) {
        Users users = new Users();
        String sql = "select *from users where userid="+id;
//        Object[] arr = new Object[]{id};
        this.jdbcTemplate.query(sql,new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet resultSet) throws SQLException {
                users.setUserid(resultSet.getInt("userid"));
                users.setUsername(resultSet.getString("username"));
                users.setUserage(resultSet.getInt("userage"));
            }
        });
        return users;
    }

    @Override
    public void updateUser(Users users) {
        String sql = "update users set username=?,userage=? where userid=?";
        this.jdbcTemplate.update(sql,users.getUsername(),users.getUserage(),users.getUserid());
    }

4.创建Service:

(1)查询所有用户业务:

 @Override
    public List<Users> findAll() {
        return this.usersDao.findAll();
    }

(2)修改用户业务:

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UsersDao usersDao;

    @Override
    public void addUser(Users user) {
        usersDao.insertUser(user);
    }
}

(3)删除业务:


    @Override
    public void deleteUser(int userid) {
        usersDao.deleteUser(userid);
    }

(4)更新业务:

 @Override
    public Users findById(int userid) {
        return usersDao.findById(userid);
    }

    @Override
    public void updateUser(Users users) {
        usersDao.updateUser(users);
    }

5.创建页面:

(1)addUser添加页面:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<link rel="shortcut icon" href="../resources/favicon.ico" th:href="@{/static/favicon.ico}"/>
<head>
    <meta charset="UTF-8">
    <title>添加用户</title>
</head>
<body>
<form th:action="@{/user/addUser}" method="post">
    <p>
       用户名: <input type="text" name="username"/>
    </p>
    <p>
       年龄: <input type="text" name="userage"/>
    </p>
    <p>
       <input type="submit" value="添加"/>
    </p>
</form>
</body>
</html>
  • 解决 favicon.ico 解析问题
<linkrel="shortcuticon"href="../resources/favicon.ico"th:href="@{/static/favicon.ico}"/>

(2)展示数据:

    <table border="1px" align="center" width="500px">
        <tr >
            <th>ID</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>操作</th>
        </tr>
        <tr th:each="user : ${list}">
            <td th:text="${user.userid}"></td>
            <td th:text="${user.username}" ></td>
            <td th:text="${user.userage}"></td>
            <td>
                <a th:href="@{/user/findById(id=${user.userid})}">修改</a>
                <a th:href="@{/user/deleteUser(id=${user.userid})}">删除</a>
            </td>
        </tr>
    </table>

(3)修改页面:

<body>
<form th:action="@{/user/updateUser}" method="post">
    <p>
       <input type="hidden" name="userid" th:value="${user.userid}" />
    </p>
    <p>
        用户名: <input type="text" name="username" th:value="${user.username}"/>
    </p>
    <p>
        年龄: <input type="text" name="userage" th:value="${user.userage}"/>
    </p>
    <p>
        <input type="submit" value="修改"/>
    </p>
</form>
</body>
  • 实现效果:


    查询所有
    添加用户
    修改页面

二、SpringBoot整合MyBatis:

1.创建项目:

添加启动器
  • 修改POM文件,添加依赖:
        <!--MySql数据库驱动坐标-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <!--Druid数据源依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    <build>
     <!-- 配置资源拷贝插件-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.properties</include>
                    <include>**/*.html</include>
                </includes>
            </resource>
        </resources>
    </build>
  • 添加generator配置文件:

添加 generator 插件坐标;并运行generator插件生成代码。
(1)generator配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <context id="testTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/ssm" userId="root"
            password="root">
        </jdbcConnection>
        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 
            NUMERIC 类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- targetProject:生成PO类的位置 -->
        <javaModelGenerator targetPackage="com.zlw.springbootmybatis.pojo"
            targetProject=".\src\main\java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.zlw.springbootmybatis.mapper"
            targetProject=".\src\main\java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="com.zlw.springbootmybatis.mapper"
            targetProject=".\src\main\java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!-- 指定数据库表 -->
        <table schema="" tableName="users"></table>
    </context>
</generatorConfiguration>

(2)插件坐标:

       <plugins>
            <!--配 置 Generator插 件 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.38</version>
                    </dependency>
                </dependencies>
                <!--指 定 配 置 文 件 的 路 径 -->
                <configuration>
                    <configurationFile>${project.basedir}/src/main/resources/generatorConfig.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
        </plugins>
运行
生成的文件
  • 修改启动类:

修改启动类添加@MapperScan 注解

@SpringBootApplication
@MapperScan("com.zlw.springbootmybatis.mapper")//指定扫描接口和映射文件的配置
public class SpringbootMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisApplication.class, args);
    }
}
  • 使用yml配置数据源和连接池:

application.properties和application.yml文件能放在以下四个位置。
(1) 外置,在相对于应用程序运行目录的/config子目录里。
(2) 外置,在应用程序运行的目录里。
(3) 内置,在config包内。
(4) 内置,在Classpath根目录。

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm
    password: root
    username: root
    type: com.alibaba.druid.pool.DruidDataSource

2.创建Service:

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UsersMapper usersMapper;

    /**
     * 添加用户
     * @param users
     */
    @Override
    public void insertUser(Users users) {
        this.usersMapper.insert(users);
    }

    /**
     * 查询所有
     * @return
     */
    @Override
    public List<Users> findAll() {
        UsersExample usersExample = new UsersExample();
        return this.usersMapper.selectByExample(usersExample);
    }

    /**
     * 删除用户
     * @param usersid
     */
    @Override
    public void deleteUser(int usersid) {
        this.usersMapper.deleteByPrimaryKey(usersid);
    }

    /**
     * 查询指定用户
     */
    @Override
    public Users findById(int userid) {
        return this.usersMapper.selectByPrimaryKey(userid);
    }

    /**
     * 修改用户
     * @param users
     */
    @Override
    public void update(Users users) {
        this.usersMapper.updateByPrimaryKey(users);
    }
}

3.创建Controller:

  • 页面跳转:
@Controller
public class PageShow {
    @RequestMapping("/{page}")
    public String showPage(@PathVariable String page){
        return page;
    }
}
  • UsersController:
@Controller
@RequestMapping("/user")
public class UsersController {

    @Autowired
    private UserService userService;
    @RequestMapping("addUser")
    public String addUser(Users user) {
        userService.insertUser(user);
        return "redirect:/user/findAll";
    }

    @RequestMapping("findAll")
    public String findAll(Model model){
        List<Users> list = userService.findAll();
        model.addAttribute("list",list);
        return "listUser";
    }

    @RequestMapping("delete")
    public String deleteUser(int id){
        userService.deleteUser(id);
        return "redirect:/user/findAll";
    }

    @RequestMapping("findById")
    public String findById(Model model,int id){
        Users user = userService.findById(id);
        model.addAttribute("user",user);
        return "updateUser";
    }
    @RequestMapping("updateUser")
    public String updateUser(Users users){
        userService.update(users);
        return "redirect:/user/findAll";
    }
}

4.创建页面

(1)addUser添加页面:

<body>
<form th:action="@{/user/addUser}" method="post">
    <p>
        用户名: <input type="text" name="username"/>
    </p>
    <p>
        年龄: <input type="text" name="userage"/>
    </p>
    <p>
        <input type="submit" value="添加"/>
    </p>
</form>
<p>
    <a th:href="@{/user/findAll}">查看</a>
</p>
</body>

(2)listUser展示数据:

<body>
<table border="1px" align="center" width="500px">
    <tr>
        <th>ID</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>操作</th>
    </tr>
    <tr th:each="user : ${list}">
        <td th:text="${user.userid}"></td>
        <td th:text="${user.username}"></td>
        <td th:text="${user.userage}"></td>
        <td>
            <a th:href="@{/user/findById(id=${user.userid})}">修改</a>
            <a th:href="@{/user/delete(id=${user.userid})}">删除</a>
        </td>
    </tr>
</table>
<a th:href="@{/addUser}">添加</a>
</body>

(3)updateUser修改页面:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<link rel="shortcut icon" href="../resources/favicon.ico" th:href="@{/static/favicon.ico}"/>
<head>
    <meta charset="UTF-8">
    <title>修改用户</title>
</head>
<body>
<form th:action="@{/user/updateUser}" method="post">
    <p>
        <input type="hidden" name="userid" th:value="${user.userid}"/>
    </p>
    <p>
        用户名: <input type="text" name="username" th:value="${user.username}"/>
    </p>
    <p>
        年龄: <input type="text" name="userage" th:value="${user.userage}"/>
    </p>
    <p>
        <input type="submit" value="修改"/>
    </p>
</form>
</body>
</html>
  • 实现效果:


    数据展示
    添加页面
    修改页面
  • 注意:

在yml配置文件中保证格式正确,特别是空格要仔细。
在POM配置文件中注意各驱动和插件依赖的版本号。

相关文章

网友评论

      本文标题:SpringBoot学习day90:整合JDBC和MyBatis

      本文链接:https://www.haomeiwen.com/subject/lkojwctx.html