CST438 Software Engineering: Module 1
CST438 Software Engineering: Module 1
Readings:
In the readings for this week Ch.1 What is Software Engineering the book examines the differences between "Software Engineering" and "Programming". Where software engineering the focus seems to stem in the maintainability of the code with respect to time, while "programming" is focused on just if the "code works". Two very different mindsets scaling in complexity for software engineering while it seems programming only deals with low-count dimensions. The primary train of thought that software engineers should have according to the book is to have the mindset of "what is the expected lifespan of your code?" and to continually ask the question in regards to security, performance etc. The book also covers dependencies and how it holds a contributing factor to the aforementioned mindset.
Dependencies are separate applications in themselves and with each version change also contain changes in their code as well. It also noted Hyrum's law in regards to this relationship, "with a sufficient number of users of an API, it does not matter what you promise in the contract: all observable behaviors of your system will be depended on by somebody."
Version Control Policies are highly valued as they allow for processes to scale.
When making decisions, its better to have a majority of support is a type of data, as most decisions are also multi-faceted, decisions are hardly ever based on strictly data.
Lab: Building a Customer Order API
composed below is general notes I took on the lab, in order to better understand the setup operations of an API
Spring Boot Java Framework
Restful API's
- Best Practices
- REST (REpresentation State Transfer)
- created by Roy Fielding in PhD thesis
- a way for programs to exchange and manipulate data over the internet using HTTP methods:
- GET (retrieval of data)
- POST (creation of data)
- DELETE (deletion of data)
- PUT (modification of existing data)
- data is identified with a URI (Uniform Resource Identifier)
Send HTTP Request
Receive JSON Response
Client
Server
- HTTP Requests are stateless, all info required to process requests is contained within it, even authentication if required.
- Clients can cache freq accessed data locally to reduce server load.
- REST uses JSON or XML in practice
- sucessful responses have status code of 200 or 201
Introduction to Spring Server
- SPring supports the "Model-View_Controller" design pattern
- Model part consists of JPA (Java Persistence Architecture) Entity Class
- view determines how data from the controller is formatted for the client
- Controller is an object created and managed by the Spring Server.
- Dependency Injection: ?
JPA and Database
- JPA (Java Persistence Architecture) is a mapping layer over a relational databasee where tables appear as virtual collection of Java object called entities.
- Entities can have relationships with other entities and are mapped to foreign keys in the tables(think Relational Databases):
- One-to-One
- One-to-Many
- Many-to-Many
- Inheritance is also a feature Entities can have
- Eager and Lazy Relationships, can affect performance ask LLM?
A Repository Interface
public interface CustomerRepository extends CrudRepository<Customer, Integer>
- repo interface for each entity type supports operations to retrieve, delete, create and update entity classes.
- repo inherit from Spring CrudRepository and specifies the Entity class name and primary key datatype.
- The repo will inherit basic methods for
- findById( primary key value )
- findAll( )
- delete( entity object )
- deleteById( primary key value)
- deleteAll( )
- existsById( primary key value )
- save( entity object)
Transaction Support
If you want a controller method which does multiple operations to be atomic, then the controller method needs to be annotated as @Transactional
- If the method ends normally, the transaction is committed.
- If the methods terminates with an exception, and the exception is a type of Java Runtime exception or is listed on the @Transactional annotation, then the transaction is rolled back.
- If the exception is not a type of Runtime exception and not listed on the annontation, the transaction is still committed.
Spring Security
Spring has:
- Basic Authentication
- JWT Security
- JSON Web Token, is a key signed by the server to prevent tampering
- OAuth2
- used for single sign on where a security server authenticates a client and returns a signed key that can be used across multiple application servers.
Debugging in Java
Logger logger = LoggerFactory.getLogger(LoggingController.class);
logger.error('An Error Message')
// Spring server listens on port number 8080 by default
server.port // property to specify a port number
server.port=8081
Lab 1: Notes
- Go to start.spring.io
- Enter these settings:
- project: maven
- language: java
- Spring Boot: 3.5.3
- Group: "com.cst438"
- Artifact: "lab1"
- Name: "lab1"
- Description: "cst438 lab1"
- packaging: jar
- java: 17
- Dependencies
- Spring Boot Dev Tools
- Spring Web
- SQL: Spring Data JPA
- Database: H2 Database
- I/O: Validation
- Generate Download Extract and open folder in IDE
- Enter these settings:
1. Setup Stucture for the SQL Tables
properties and adding sql tables
- Go to src>main>resources>applications.properties and add:
spring.datasource.url="jdbc:h2:mem:testdb"
temporary databasespring.jpa.hibernate.ddl-auto=none
- under resources add file for sql database
schema.sql
- this is where you enter your database sql code to generate the tables
generate the structs that will represent the tables
- Create a package folder in
com.cst438
, titleddomain
- create new files within Consisting of table name
Customer.java
Order.java
package com.cst438.domain;
import jakarta.persistence.*;
@Entity
public class Customer {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="cust_id")
int customerId;
private String name;
private String email;
private String password;
@OneToMany(mappedBy="customer")
@OrderBy("orderDate desc, orderId desc")
private List<Order> orders;
// autogenerate... getters & setters
}
package com.cst438.domain;
import jakarta.persistence.*;
import java.util.BigDecimal;
import java.sql.Date;
@Entity
@Table(name="ordertab")
public class Order {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int orderId;
private Date orderDate;
private String item;
private int quantity;
private BigDecimal price;
@ManyToOne
@JoinColumn(name="cust_id", nullable=false)
private Customer customer;
// autogenerate... getters & setters
}
Generate the interfaces that will translate between SQL DB and Java
package com.cst438.domain;
import org.springFramework.data.repository.CrudRepository;
public interface CustomerRepository extends CrudRepository<Customer, Integer> {
Customer findCustomerByEmail(String email);
}
package com.cst438.domain;
import org.springFramework.data.repository.CrudRepository;
public interface OrderRepository extends CrudRepository<Order, Integer> {
}
Generate Data Transfer Objects
- these are used in order to pass data
- Create a new package in
com.cst438
titleddto
- create
CustomerDTO
andOrderDTO
as records
package com.cst438.dto;
public record CustomerDTO(
int customerId,
String name,
String email,
String password
) {
}
package com.cst438.dto;
public record OrderDTO(
int orderId;
Date orderDate;
String item;
int quantity;
BigDecimal price;
) {
}
Controller Generation
- Create a package title
controller
incom.cst438
: - this is where a majority of your logic will take place for your api
- create a CustomerController class
package com.cst438.controller;
public class CustomerController(
CustomerRepository customerRepository
OrderRepository orderRepository
) {
this.customerRepository = customerRepository
this.OrderRepostiory = orderRepository
}
Comments
Post a Comment