//一个model对应一张表中的字段
public class Student
private UUID id;
private String name;
public UUID getId()
return id;
public void setId(UUID id)
this.id = id;
public String getName()
return name;
public void setName(String name)
this.name = name;
public Student(UUID id, String name)
this.id = id;
this.name = name;
public Student()
(2)Dao层
数据访问层,和Model层交互。实现接口,对数据库的访问。完成增删改查功能
//定义操作数据库的方法
public interface StudentDao
Optional<Student> selectStudentById(UUID id);
List<Student> selectAllStudents();
int insertStudent(Student student);
int upgradeStudent(Student student);
int deleteStudent(UUID id);
定义接口的实现,因为没有实现和数据库直接相连,就使用假数据。
@Repository
@Resource
public class FakeStudentDao implements StudentDao
private static List<Student> database = new ArrayList<>();
@Override
public Optional<Student> selectStudentById(UUID id)
for(Student s : database)
if(s.getId().equals(id))
return Optional.of(s);
return Optional.empty();
@Override
public List<Student> selectAllStudents()
return database;
@Override
public int insertStudent(Student student)
UUID id = UUID.randomUUID();
database.add(new Student(id,student.getName()));
return 1;
@Override
public int upgradeStudent(Student student)
// 先找到这个要更新的student的信息
int indexToUpdate = -1;
for(int i = 0;i<database.size();i++)
if(student.getId().equals(database.get(i).getId()))
indexToUpdate = i;
break;
if(indexToUpdate<0) return -1;
database.set(indexToUpdate,student);
return 1;
@Override
public int deleteStudent(UUID id)
Optional<Student> optionalStudent = selectStudentById(id);
if(!optionalStudent.isPresent())
return -1;
database.remove(optionalStudent.get());
return 1;
@Service
public class StudentService
private StudentDao studentDao;
@Autowired
public StudentService(StudentDao studentDao)
this.studentDao = studentDao;
public List<Student> getAllStudents()
return studentDao.selectAllStudents();
public int addStudent(Student student )
return studentDao.insertStudent(student);
public int upgradeStudent(Student student )
return studentDao.upgradeStudent(student);
public int deleteStudent(UUID id)
return studentDao.deleteStudent(id);