狂神SpringBoot学习笔记12天-Day 07 SpringBoot 整合数据库操作

7、SpringBoot整合数据库操作

7.1、整合JDBC

创建测试项目测试数据源

1、我去新建一个项目测试:springboot-data-jdbc ; 引入相应的模块!基础模块

2、项目建好之后,发现自动帮我们导入了如下的启动器

<dependency>    
    <groupId>org.springframework.boot</groupId>    
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>    
    <groupId>mysql</groupId>    
    <artifactId>mysql-connector-java</artifactId>    
    <scope>runtime</scope>
</dependency>

3、编写yaml配置文件连接数据库;

spring:
  datasource:
      username: root
      password: root
      url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&userUnicode=true&characterEncoding=utf-8
      driver-class-name: com.mysql.cj.jdbc.Driver

4、配置完这一些东西后,我们就可以直接去使用了,因为SpringBoot已经默认帮我们进行了自动配置;

去测试类测试一下

@SpringBootTest
class Springboot03JdbcApplicationTests {

    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {


        System.out.println(dataSource.getClass());

        Connection connection = dataSource.getConnection();
        
        System.out.println(connection);
        
        connection.close();


    }

结果:我们可以看到他默认给我们配置的数据源为 : class com.zaxxer.hikari.HikariDataSource , 我们并没有手动配置

我们来全局搜索一下,找到数据源的所有自动配置都在 :DataSourceAutoConfiguration文件:

@Import(
    {Hikari.class, Tomcat.class, Dbcp2.class, Generic.class, DataSourceJmxConfiguration.class}
)
protected static class PooledDataSourceConfiguration {
    protected PooledDataSourceConfiguration() {
    }
}

这里导入的类都在 DataSourceConfiguration 配置类下,可以看出 Spring Boot 2.2.5 默认使用HikariDataSource 数据源,而以前版本,如 Spring Boot 1.5 默认使用 org.apache.tomcat.jdbc.pool.DataSource 作为数据源;

HikariDataSource 号称 Java WEB 当前速度最快的数据源,相比于传统的 C3P0 、DBCP、Tomcat jdbc 等连接池更加优秀;

可以使用 spring.datasource.type 指定自定义的数据源类型,值为 要使用的连接池实现的完全限定名。

关于数据源我们并不做介绍,有了数据库连接,显然就可以 CRUD 操作数据库了。

但是我们需要先了解一个对象 JdbcTemplate

JDBCTemplate

1、有了数据源(com.zaxxer.hikari.HikariDataSource),然后可以拿到数据库连接(java.sql.Connection),有了连接,就可以使用原生的 JDBC 语句来操作数据库;

2、即使不使用第三方第数据库操作框架,如 MyBatis等,Spring 本身也对原生的JDBC 做了轻量级的封装,即JdbcTemplate。

3、数据库操作的所有 CRUD 方法都在 JdbcTemplate 中。

4、Spring Boot 不仅提供了默认的数据源,同时默认已经配置好了 JdbcTemplate 放在了容器中,程序员只需自己注入即可使用

5、JdbcTemplate 的自动配置是依赖 org.springframework.boot.autoconfigure.jdbc 包下的 JdbcTemplateConfiguration 类

JdbcTemplate主要提供以下几类方法:

  • execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
  • update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate方法用于执行批处理相关语句;
  • query方法及queryForXXX方法:用于执行查询相关语句;
  • call方法:用于执行存储过程、函数相关语句。

测试

编写一个Controller,注入 jdbcTemplate,编写测试方法进行访问测试;

@RestController
public class JDBCController {
    @Autowired
    JdbcTemplate jdbcTemplate;
//    查询数据库的所有信息
//    没有实体类 数据库中的数据怎么获取 Map
    @GetMapping("/userList")
    public List<Map<String,Object>> userList(){
        String sql="select * from user";
        List<Map<String, Object>> list_maps = jdbcTemplate.queryForList(sql);
        return list_maps;
    }

    @GetMapping("/addUser")
    public String addUser(){
        String sql="insert into mybatis.user(id,name,pwd) values (7,'小明','132214') ";
        jdbcTemplate.update(sql);
        return "update-ok";
    }

    @GetMapping("/updateUser/{id}")
    public String updateUser(@PathVariable("id") int id){
        String sql="update mybatis.user set name=?,pwd=? where id="+id;
//        封装
        Object[] objects=new Object[2];
        objects[0]="22222";
        objects[1]="11111111111111111";
        jdbcTemplate.update(sql,objects);
        return "update-ok";
    }

    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") int id){
        String sql="delete from mybatis.user where id=?";
        jdbcTemplate.update(sql,id);
        return "delete-ok";
    }
}

7.2、整合Druid数据源

Druid简介

​ Java程序很大一部分要操作数据库,为了提高性能操作数据库的时候,又不得不使用数据库连接池。

​ Druid 是阿里巴巴开源平台上一个数据库连接池实现,结合了 C3P0、DBCP 等 DB 池的优点,同时加入了日志监控。

​ Druid 可以很好的监控 DB 池连接和 SQL 的执行情况,天生就是针对监控而生的 DB 连接池。

​ Druid已经在阿里巴巴部署了超过600个应用,经过一年多生产环境大规模部署的严苛考验。

​ Spring Boot 2.0 以上默认使用 Hikari 数据源,可以说 Hikari 与 Driud 都是当前 Java Web 上最优秀的数据源,我们来重点介绍 Spring Boot 如何集成 Druid 数据源,如何实现数据库监控。

​ Github地址:https://github.com/alibaba/druid/

​ com.alibaba.druid.pool.DruidDataSource 基本配置参数如下:

配置数据源

1、添加上 Druid 数据源依赖

<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.21</version>
</dependency>

2、切换数据源;之前已经说过 Spring Boot 2.0 以上默认使用 com.zaxxer.hikari.HikariDataSource 数据源,但可以 通过 spring.datasource.type 指定数据源。

spring:
  datasource:
      username: root
      password: root
      url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&userUnicode=true&characterEncoding=utf-8
      driver-class-name: com.mysql.cj.jdbc.Driver
      type: com.alibaba.druid.pool.DruidDataSource

3、切换成功!既然切换成功,就可以设置数据源连接初始化大小、最大连接数、等待时间、最小连接数 等设置项;可以查看源码

#SpringBoot默认是不注入这些的,需要自己绑定
#druid数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedS​tatements: true

#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许报错,java.lang.ClassNotFoundException: org.apache.Log4j.Properity
#则导入log4j 依赖就行
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionoProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500​

5.看到需要用到log4j,所以需要在pom中导入log4j的依赖

<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

6、现在需要程序员自己为 DruidDataSource 绑定全局配置文件中的参数,再添加到容器中,而不再使用 Spring Boot 的自动生成了;我们需要 自己添加 DruidDataSource 组件到容器中,并绑定属性;

@Configuration
public class DruidConfig {

    /*
       将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
       绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
       @ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中
       前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
     */
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

}

7、去测试类中测试一下;看是否成功!

@SpringBootTest
class SpringbootDataJdbcApplicationTests {
//DI注入数据源
@Autowired
DataSource dataSource;

@Test
public void contextLoads() throws SQLException {
    //看一下默认数据源
    System.out.println(dataSource.getClass());
    //获得连接
    Connection connection =   dataSource.getConnection();
    System.out.println(connection);

    DruidDataSource druidDataSource = (DruidDataSource) dataSource;
    System.out.println("druidDataSource 数据源最大连接数:" + druidDataSource.getMaxActive());
    System.out.println("druidDataSource 数据源初始化连接数:" + druidDataSource.getInitialSize());

    //关闭连接
    connection.close();
}}

配置Druid数据源监控

@Configuration
public class DruidConfig {
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }


    //后台监控功能 web.xml
//    因为SpringBoot内置了servlet容器 所以没有web.xml,替代方法:ServletRegistrationBean
    @Bean
    public ServletRegistrationBean StatViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
//      后台需要有人登陆
//        账号密码设置
        HashMap<String, String> initParameters = new HashMap<>();
//        增加配置
//       登录的key 是固定的  loginUsername loginPassword
        initParameters.put("loginUsername","admin");
        initParameters.put("loginPassword","123456");

//      允许谁可以访问
        initParameters.put("allow","");
//       禁止谁能访问
//        initParameters.put("sdsadasd","192.24.2345.23");

        bean.setInitParameters(initParameters);
        return bean;
    }

配置完毕后,我们可以选择访问 :http://localhost:8080/druid/login.html

在访问http://localhost:8080/userList 后,可以实时监控数据库操作:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZckExO4u-1659439101291)(C:\Users\行走的面包树\AppData\Roaming\Typora\typora-user-images\image-20220729150145878.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EFixoAlp-1659439101292)(C:\Users\行走的面包树\AppData\Roaming\Typora\typora-user-images\image-20220729150324506.png)]

配置 Druid web 监控 filter 过滤器

@Bean
public FilterRegistrationBean webStaFilter(){
    FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
    bean.setFilter(new WebStatFilter());
    可以过滤那些请求呢
        HashMap<String,String> initParameters = new HashMap<>();
    这些东西不进行统计
        initParameters.put("exclusions","*.js,*.css,/druid/*");
    bean.setInitParameters(initParameters);
    return bean;
}

注意点:DruidConfig文件一定要添加配置注解,在里面配置的一些servlet和filter都要添加@Bean注解

7.3、整合Mybatis

官方文档:

​ http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

Maven仓库地址:

​ https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter/2.1.1

整合测试

1、导入 MyBatis 所需要的依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>

2、配置数据库连接信息(不变)

spring:
  datasource:
    username: root
    password: "000000"
    #?serverTimezone=UTC解决时区的报错
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    #Spring Boot 默认是不注入这些属性值的,需要自己绑定
    #druid 数据源专有配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
    #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
    
mybatis.type-aliases-package=com.hui.pojo
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

3、测试数据库是否连接成功!

4、创建实体类,导入 Lombok!

User

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
}

5、创建mapper目录以及对应的 Mapper 接口

UserMapper

@Mapper
@Repository
public interface UserMapper {

    List<User> queryUserList();

    User queryUserById(int id);

    int addUser(User user);

    int updateUser(User user);

    int deleteUser(int id);
}

UserMapper.xml

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hui.mapper.UserMapper">
    <select id="queryUserList" resultType="com.hui.pojo.User">
       select * from mybatis.user;
   </select>
    <select id="queryUserById" parameterType="int" resultType="com.hui.pojo.User">
       select * from mybatis.user where id=#{id}
    </select>
    <insert id="addUser" parameterType="com.hui.pojo.User">
        insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd});
    </insert>
    <update id="updateUser" parameterType="com.hui.pojo.User">
        update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
    </update>
    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id=#{id};
    </delete>
</mapper>

6、这里省略了业务层,故直接写控制层(Controller)

UserController

@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @GetMapping("/queryUserList")
    public List<User> queryUserList(){
        List<User> userList = userMapper.queryUserList();
        for (User user:userList) {
            System.out.println(user);
        }
        return userList;
    }
    @GetMapping("/addUser")
    public String addUser(){
        userMapper.addUser(new User (7,"小明","132214"));
        return "update-ok";
    }

    @GetMapping("/update")
    public String updateUser(){
        userMapper.updateUser(new User (7,"小红","132214"));
        return "update-ok";
    }

    @GetMapping("/delete")
    public String deleteUser(){
        userMapper.deleteUser(7);
        return "delete-ok";
    }
}

7、成功测试!

这里使用的数据库参考mybatis笔记mybatis里面的数据库!

7.4、员工管理系统项目整合mybatis操作

环境

  • mysql 8.0
  • idea 2018

环境配置

# 开启模板缓存(默认值: true )
spring.thymeleaf.cache=false
#我们的配置文件的真实位置 国际化
spring.messages.basename=i18n.login
#时间日期格式化
spring.mvc.date-format=yyyy-MM-dd
# 数据库驱动:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源名称
spring.datasource.name=defaultDataSource
# 数据库连接地址
spring.datasource.url=jdbc:mysql://localhost:3306/springbootweb?serverTimezone=UTC&userUnicode=true&characterEncoding=utf-8
# 数据库用户名&密码:
spring.datasource.username=root
spring.datasource.password=root
#整合mybatis
mybatis.type-aliases-package=com.hui.pojo
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

项目步骤

1、导入依赖

  <dependencies>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</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>

2、创建数据库

DROP TABLE IF EXISTS `department`;
CREATE TABLE `department`  (
  `id` int(0) NOT NULL,
  `dname` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of department
-- ----------------------------
INSERT INTO `department` VALUES (101, '教学部');
INSERT INTO `department` VALUES (102, '市场部');
INSERT INTO `department` VALUES (103, '教研部');
INSERT INTO `department` VALUES (104, '运营部');
INSERT INTO `department` VALUES (105, '后勤部');

-- ----------------------------
-- Table structure for employee
-- ----------------------------
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee`  (
  `id` int(0) NOT NULL AUTO_INCREMENT,
  `ename` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `email` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `gender` int(0) NULL DEFAULT NULL,
  `birthday` datetime(0) NULL DEFAULT NULL,
  `did` int(0) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of employee
-- ----------------------------
INSERT INTO `employee` VALUES (1001, 'AA', 'A213567352@qq.com', 0, '2022-07-29 08:53:21', 101);
INSERT INTO `employee` VALUES (1002, 'BB', 'B213567352@qq.com', 1, '2022-07-29 08:53:21', 102);
INSERT INTO `employee` VALUES (1003, 'CC', 'C213567352@qq.com', 0, '2022-07-29 08:53:21', 103);
INSERT INTO `employee` VALUES (1004, 'DD', 'D213567352@qq.com', 1, '2022-07-29 08:53:21', 104);
INSERT INTO `employee` VALUES (1005, 'EE', 'E213567352@qq.com', 0, '2022-07-29 08:53:21', 105);
INSERT INTO `employee` VALUES (1008, '3443243', 'kkkkkkkkkkk195456653343@qq.com', 0, '1996-03-22 00:00:00', 105);
INSERT INTO `employee` VALUES (1009, '213231', '19556456653@qq.com', 1, '1996-03-22 00:00:00', 101);
INSERT INTO `employee` VALUES (1010, '21321312', 'A1953646653@163.com', 0, '1996-03-22 00:00:00', 103);

3、实体类(pojo)

Department

//部门表
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {

    private Integer id;
    private String dname;
}

Employee

//员工表
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
    private Integer id;
    private String ename;
    private String email;
    private Integer gender;
    private int did;
    private String birthday;
    private String dname;

4、数据类(mapper)

DepartmentMapper

@Repository
@Mapper
public interface DepartmentMapper {
    //获得所有部门信息
    List<Department> getAll();

    //通过ID的到部门
    int getIdByDname(@Param("dname") String dname);
}

EmployeeMapper

@Repository
@Mapper
public interface EmployeeMapper {
    //查询全部的员工信息
    List<Employee> getAll();

    //通过ID查询员工
    Employee getEmployeeById(@Param("id") int id);

    //通过ID删除员工
    int delete(@Param("id") int id);

    //增加一个员工
    int save(Employee employee);

    //修改员工
    int updateEmpById(Employee employee);
}

项目结构

DepartmentMapper.xml

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hui.mapper.DepartmentMapper">
    <select id="getAll" resultType="com.hui.pojo.Department">
        select * from springbootweb.department;
    </select>
    <!--<select id="getIdByDname" parameterType="int" resultType="com.hui.pojo.Employee">-->
        <!--select * from emps.department where id=#{id}-->
    <!--</select>-->

</mapper>

EmployeeMapper.xml

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hui.mapper.EmployeeMapper">
    <select id="getAll" resultType="Employee">
        select e.id,e.ename,e.email,e.gender,e.birthday,e.did,dname
        from springbootweb.employee e
        left join springbootweb.department d on d.id=e.did
    </select>

    <select id="getEmployeeById" resultType="Employee">
        select e.id,e.ename,e.email,e.gender,e.birthday,e.did,dname
        from springbootweb.employee e
        left join springbootweb.department d on d.id=e.did
        where e.id=#{id}
    </select>

    <insert id="save" parameterType="com.hui.pojo.Employee" useGeneratedKeys="true" keyProperty="id">
        insert into springbootweb.employee(ename, email, gender, birthday, did)
        values (#{ename}, #{email}, #{gender}, #{birthday}, #{did})
    </insert>
    <update id="updateEmpById" parameterType="com.hui.pojo.Employee">
        update springbootweb.employee
        set ename=#{ename},
            email=#{email},
            gender=#{gender},
            did=#{did},
            birthday=#{birthday}
        where id=#{id};
    </update>
    <delete id="delete" parameterType="int">
        delete from springbootweb.employee where id=#{id};
    </delete>
</mapper>

5、业务类(service)

DepartmentService

public interface DepartmentService {
    List<Department> getAll();
}

DepartmentServiceImpl

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> getAll() {
        return departmentMapper.getAll();
    }
}

EmployeeService

public interface EmployeeService {
    List<Employee> getAll();

    //通过ID查询员工
    Employee getEmployeeById(int id);

    //通过ID删除员工
    int delete(int id);

    //增加一个员工
    int save(Employee employee);

    int updateEmpById(Employee employee);
}

EmployeeServiceImpl

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public List<Employee> getAll() {
        return employeeMapper.getAll();
    }

    @Override
    public Employee getEmployeeById(int id) {
        return employeeMapper.getEmployeeById(id);
    }

    @Override
    public int delete(int id) {
        return employeeMapper.delete(id);
    }

    @Override
    public int save(Employee employee) {
        return employeeMapper.save(employee);
    }

    @Override
    public int updateEmpById(Employee employee) {
        return employeeMapper.updateEmpById(employee);
    }
}

6、控制层(controller)

EmployeeController

@Controller
public class EmployeeController {
//    正常情况下,调用业务层
//    这里我们没有写业务层和数据库 直接调用dao
//    @Autowired
//    EmployeeDao employeeDao;
//    @Autowired
//    DepartmentDao departmentDao;
//    @Autowired
//    DepartmentMapper departmentMapper;
//    @Autowired
//    EmployeeMapper employeeMapper;

      private final DepartmentServiceImpl departmentService;
      private final EmployeeServiceImpl employeeService;

    public EmployeeController(DepartmentServiceImpl departmentService, EmployeeServiceImpl employeeService) {
        this.departmentService = departmentService;
        this.employeeService = employeeService;
    }

    @RequestMapping("/emps")
    public String list(Model model){
        List<Employee>  employees =  employeeService.getAll();
        model.addAttribute("emps",employees);
        return "emp/list";
    }

    @GetMapping("/emp")
    public String toAddpage(Model model){
//        查出所有部门的信息
        List<Department> departments = departmentService.getAll();
        model.addAttribute("departments",departments);
        return "emp/add";
    }

    @PostMapping("/emp")
    public String addEmp(Employee employee){
        System.out.println(employee);
//        调用业务 保存员工信息
//        if(employee.getId()==null){
//            employee.setId(initID++);
//        }

//        输出员工
        employeeService.save(employee);
        //添加的操作
        return "redirect:/emps";
    }
//    跳转修改页面
    @GetMapping("/emp/{id}")
    public String toUpdateEmp(@PathVariable("id") Integer id,Model model){
        //        查出原来的数据
        Employee employee =  employeeService.getEmployeeById(id);
        model.addAttribute("emp",employee);
        //        查出所有部门的信息
        List<Department> departments = departmentService.getAll();
        model.addAttribute("departments",departments);
        return "emp/update";
    }
//    修改员工信息
    @PostMapping("/updateEmp")
    public String updateEmp(Employee employee){
        employeeService.updateEmpById(employee);
        return "redirect:/emps";
    }
//    删除员工
    @GetMapping("/delemp/{id}")
    public String deleteEmp(@PathVariable("id")int id ){
        employeeService.delete(id);
        return "redirect:/emps";
    }
}

LoginController

@Controller
public class LoginController {
//    登录
    @RequestMapping("/user/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Model model, HttpSession session){
//        具体的业务
        if(!StringUtils.isEmpty(username) && "123456".equals(password)){
            session.setAttribute("loginUser",username);
            return "redirect:/main.html";
        }else{
//            告诉用户,登录失败
            model.addAttribute("msg","用户名或者密码错误");
            return "index";
        }

    }
//    注销
    @RequestMapping("/user/logout")
    public String  logout(HttpSession session){
        session.invalidate();
        return "redirect:/index.html";
    }
}

至于前端页面的细改,可以参考上文博主的源码链接https://gitee.com/zy-hao/StudySpringBoot

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值