Java框架技术 :Spring和JDBCTemplate+Spring和MyBatis

实验目的、内容及要求:

实验目的:

  1. 掌握Spring和JDBCTemplate操作数据库
  2. 掌握Spring和MyBatis操作数据库

实验内容:

1.在计算机上实现模拟查询学生成绩的操作,要求如下:

(1)构建User类和Student类,对应数据库中的两个表,类属性如下:

A.Student类,属性(sid,sname,sex,age,suid)

B.User,属性(uid,username,password)

(2)假设User类所对应的方法是login(username,password),完成该类中的这个方法在dao层的接口和实现类,以及service层的接口和实现类

(3)假设Student类所对应的方法是查询所有学生信息(List<Student> findStudent())以及根据id查询学生信息(Student findStudentById(int id))以及根据名字模糊查找学生信息(List<Student> findStudentByName(String name))这三个方法,完成这三个方法在dao和service层的构建以及调用关系,注意,这里所有的查询只能查询到跟当前登录成功的User对应的数据;

(4)提供main方法测试,使用Scanner类来完成控制台的输入指令:1.用户登录 2.退出,当用户登录成功之后,开始有新指令:1.查找所有学生、2.根据id查找学生、3.根据学生姓名查找学生;完成以上5个功能;

2.操作完成之后,把代码以及效果截图粘贴到该文档中进行提交

实验仪器设备(实验环境):

运行环境:Windows 10

开发工具:IntelliJ IDEA 

运行环境:Java 21

实验过程包括实现思路、实验步骤/实现代码、实验结果/运行图

  • 在计算机上实现学生成绩管理系统,要求如下:
  • 首先 先构建文件目录 Spring_jdbc

   然后导入项目依赖在pom.xml 而且Java版本 为21 

  • <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    
        <modelVersion>4.0.0</modelVersion>
        <groupId>org.example</groupId>
        <artifactId>Spring_jdbc</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <properties>
            <maven.compiler.source>21</maven.compiler.source>
            <maven.compiler.target>21</maven.compiler.target>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>5.3.1</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>5.3.1</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>5.3.1</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>5.3.1</version>
            </dependency>
        <dependency>
    
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>5.3.1</version>
        </dependency>
        <dependency>
    
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.1</version>
        </dependency>
        <dependency>
    
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.3.1</version>
        </dependency>
    
            <dependency>
    
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.23</version>
    
            </dependency>
    
            <dependency>
    
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
    
                <version>1.2</version>
    
            </dependency>
    
    
        </dependencies>
    
    </project>

 接着构建实体类

User 类

package com.Spring.Pojo;


public class User {

  private long uid;
  private String username;
  private String password;


  public long getUid() {
    return uid;
  }

  public void setUid(long uid) {
    this.uid = uid;
  }


  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;
  }

  @Override
  public String toString() {
    return "User{" +
            "uid=" + uid +
            ", username='" + username + '\'' +
            ", password='" + password + '\'' +
            '}';
  }
}

Student 类 

package com.Spring.Pojo;


public class Student {

  private long sid;
  private String sname;
  private String sex;
  private long age;
  private long suid;


  public long getSid() {
    return sid;
  }

  public void setSid(long sid) {
    this.sid = sid;
  }


  public String getSname() {
    return sname;
  }

  public void setSname(String sname) {
    this.sname = sname;
  }


  public String getSex() {
    return sex;
  }

  public void setSex(String sex) {
    this.sex = sex;
  }


  public long getAge() {
    return age;
  }

  public void setAge(long age) {
    this.age = age;
  }


  public long getSuid() {
    return suid;
  }

  public void setSuid(long suid) {
    this.suid = suid;
  }

  @Override
  public String toString() {
    return "Student{" +
            "sid=" + sid +
            ", sname='" + sname + '\'' +
            ", sex='" + sex + '\'' +
            ", age=" + age +
            ", suid=" + suid +
            '}';
  }
}

Dao 层 :

UserDao接口 (这里只是实现了登录方法 仅用于测试学习JDBCTemplate的用法)

package com.Spring.Dao;

import com.Spring.Pojo.User;

import java.util.List;

public interface UserDao {
    void login(String userName, String password);
}

 UserDaoImpl 类

package com.Spring.Dao;

import com.Spring.Pojo.User;
import com.Spring.Util;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.util.List;


public class UserDaoImpl implements UserDao {
    static JdbcTemplate jdbcTemplate = Util.getjdbcTemplate();

    @Override
    public void login(String userName, String password) {
        System.out.println("用户名:" + userName + "密码:" + password);
        String sql = "select * from user where username=? and password=?";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
        try {
            User user = jdbcTemplate.queryForObject(sql, rowMapper, userName, password);
            if (user != null) {
                System.out.println("登录成功");
            }
        } catch (Exception e) {
            System.out.println("登录失败");
        }

    }


}

 StudentDao 类

package com.Spring.Dao;

import com.Spring.Pojo.Student;

import java.util.List;
import java.util.Map;

public interface StudentDao {
   public List<Student> findStudent();
    public List<Student> findStudentById(int id);
    public List<Student> findStudentByName(String name);
}

StudentDaoImpl 类

package com.Spring.Dao;

import com.Spring.Pojo.Student;
import com.Spring.Util;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.util.List;

public class StudentDaoImpl implements StudentDao {
    static Student student = new Student();
    static JdbcTemplate jdbcTemplate = Util.getjdbcTemplate();


    @Override
    public List<Student> findStudent() {
        String sql = "select * from student";
        RowMapper<Student> rowMapper = new BeanPropertyRowMapper<Student>(Student.class);
        return jdbcTemplate.query(sql, rowMapper);
    }
    @Override
    public List<Student> findStudentById(int id) {
            String sql = "select s.* from student s ,user u where s.suid = u.uid and uid=?";
            RowMapper<Student> rowMapper = new BeanPropertyRowMapper<Student>(Student.class);
            return  jdbcTemplate.query(sql, rowMapper, id);
    }

@Override
public List<Student> findStudentByName(String name) {
    String sql = "select * from student where sname like concat('%',?,'%')";
    RowMapper<Student> rowMapper = new BeanPropertyRowMapper<Student>(Student.class);
    return jdbcTemplate.query(sql, rowMapper, name);
}
}

 Service层:

StudentService:

package com.Spring.Service;

import com.Spring.Pojo.Student;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: kevin
 * @Date: 2024/04/24/14:19
 * @Description:
 */
public interface StudentService  {
    public List<Student> findStudent();
    public List<Student> findStudentById();
    public List<Student> findStudentByName();
}

 StudentServiceImpl:(注意这里的id是通过管理员的id对应查找学生的信息)

package com.Spring.Service;

import com.Spring.Dao.StudentDao;
import com.Spring.Dao.StudentDaoImpl;
import com.Spring.Pojo.Student;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * <p>
 * &#064;Author:  kevin
 * &#064;Date:  2024/04/24/14:18
 * &#064;Description:
 */
public class StudentServiceImpl implements StudentService {
    List<Student> students = new ArrayList<>();
    static Scanner scanner = new Scanner(System.in);


    static StudentDao studentDao = new StudentDaoImpl();


    @Override
    public List<Student> findStudent() {
        students = studentDao.findStudent();
        for (Student student : students) {
            System.out.println(student);
        }
        return null;
    }


    @Override
    public List<Student> findStudentById() {
        int id = 0;
        System.out.println("请输入管理员id");
        id = scanner.nextInt();
        students = studentDao.findStudentById(id);
        for (Student student : students) {
            System.out.println(student);
        }

        return null;
    }


    @Override
    public List<Student> findStudentByName() {
        String name = null;
        System.out.println("请输入学生姓名(模糊查找)");
        name = scanner.next();
        students = studentDao.findStudentByName(name);
        for (Student student : students) {
            System.out.println(student);
        }
        return null;
    }
}

UserService 接口:

package com.Spring.Service;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: kevin
 * @Date: 2024/04/24/14:17
 * @Description:
 */
public interface UserService {
    void login();
}

UserServiceImpl 类

package com.Spring.Service;

import com.Spring.Dao.UserDao;
import com.Spring.Dao.UserDaoImpl;

import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: kevin
 * @Date: 2024/04/24/14:18
 * @Description:
 */
public class UserServiceImpl implements UserService{
    static Scanner scanner = new Scanner(System.in);
    static UserDao userDao = new UserDaoImpl();
    @Override
    public void login() {
        String userName = null;
        String password = null;
        System.out.println("请输入用户名");
        userName = scanner.next();
        System.out.println("请输入密码");
        password = scanner.next();
        userDao.login(userName,password);
    }
}

 另外一个Util 类 :(这是用来接收 jdbcTemplate 方法的)

package com.Spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

public class Util {
    private static JdbcTemplate jdbcTemplate =null;
    static {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
    }
    public static JdbcTemplate getjdbcTemplate(){
        return jdbcTemplate;
    }

}

最后一个配置文件 ApplicationContext.xml(数据库的配置信息也在这里)

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

最后用了main 类 的主函数来测试

main:

package com.Spring;

import com.Spring.Service.StudentService;
import com.Spring.Service.StudentServiceImpl;
import com.Spring.Service.UserService;
import com.Spring.Service.UserServiceImpl;
import com.sun.source.tree.ContinueTree;
import com.sun.tools.javac.Main;

import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: kevin
 * @Date: 2024/04/24/14:15
 * @Description:
 */
public class main {
    static Scanner scanner = new Scanner(System.in);
    static StudentService studentService = new StudentServiceImpl();
    static UserService userService = new UserServiceImpl();

    public static void main(String[] args) {
        System.out.println("请输入操作:1.学生管理系统,2.管理员管理系统");
        int a;
        try {

            a = scanner.nextInt();
            if (a == 1) {
                while (true) {
                    System.out.println("请输入操作:1.查询所有学生信息 2.根据管理员id查询学生信息 3.根据名字模糊查找学生信息 4.退出");
                    int i = scanner.nextInt();
                    switch (i) {
                        case 1:
                            studentService.findStudent();
                            break;
                        case 2:
                            studentService.findStudentById();
                            break;
                        case 3:
                            studentService.findStudentByName();
                            break;
                        case 4:
                            System.exit(0);
                    }
                }
            }
            if (a == 2) {
                while (true) {
                    System.out.println("请输入操作:1.登录  2.退出");
                    int i = scanner.nextInt();
                    switch (i) {
                        case 1:
                            userService.login();
                            break;
                        case 2:
                            System.exit(0);
                            break;
                        default:
                            System.out.println("输入有误");
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("输入有误");
        }
    }
}

我的数据库是 MySQL 5.7版本  数据库名字为spring 

创建两个数据库表(student,user)

目录

 并在User表里面插入两条数据


 并在User表里面插入两条数据

最终来测试一下

  • 31
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring数据库编程和MyBatis框架是两种不同的数据库访问方式,它们有以下区别: 1. 设计理念: - Spring数据库编程是基于Spring框架的一种数据库访问方式,它提供了一套统一的API和一系列的模板,用于简化数据库操作Spring数据库编程注重于整合各种数据访问技术,提供了更高层次的抽象和更强大的功能。 - MyBatis框架是一种轻量级的持久层框架,它通过XML或注解的方式将SQL语句与Java代码进行映射,提供了灵活的SQL编写和结果映射功能。 2. 配置方式: - Spring数据库编程需要在Spring配置文件中配置数据源、事务管理器等相关信息,并使用Spring提供的JdbcTemplate等模板进行数据库操作。 - MyBatis框架需要配置MyBatis的核心配置文件,其中包括数据库连接信息、映射文件路径等,同时还需要编写SQL映射文件或使用注解进行SQL语句与Java代码的映射。 3. SQL编写方式: - Spring数据库编程使用JdbcTemplate等模板提供的方法进行SQL操作,可以直接在Java代码中编写SQL语句。 - MyBatis框架将SQL语句与Java代码进行分离,可以通过XML文件或注解的方式编写SQL语句,提供了更灵活的SQL编写方式。 4. 对象关系映射: - Spring数据库编程可以使用Spring提供的ORM框架(如Hibernate)进行对象关系映射 - MyBatis框架本身不提供对象关系映射功能,但可以与其他ORM框架(如Hibernate)结合使用。 5. 社区支持和生态系统: - Spring是一个非常庞大且活跃的开源框架,有着广泛的社区支持和完善的生态系统。 - MyBatis也有一定的社区支持,但相对于Spring来说规模较小。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值