FULL STACK DEVELOPMENT
COMPREHENSIVE GUIDE
React + Spring Boot + PostgreSQL
React Spring Boot PostgreSQL
Frontend Backend Database
Complete Curriculum • Cheat Sheets • Best Practices
TABLE OF CONTENTS
PART 1: CURRICULUM & LEARNING PATH
1. Prerequisites & Foundations ........................... 4
2. Frontend Development with React ....................... 5
3. Backend Development with Spring Boot .................. 7
4. Database with PostgreSQL .............................. 9
5. Full Stack Integration ................................ 11
6. Advanced Topics ....................................... 13
7. Deployment & DevOps ................................... 14
PART 2: CHEAT SHEETS
React Cheat Sheet ........................................ 16
Spring Boot Cheat Sheet .................................. 22
PostgreSQL Cheat Sheet ................................... 28
Integration Patterns Cheat Sheet ......................... 33
PART 1: CURRICULUM & LEARNING PATH
Overview
This curriculum is designed to take you from foundational knowledge to professional-level full stack development.
The estimated completion time is 4-6 months with consistent daily practice. Each section builds upon the previous,
so follow the order for best results.
Phase Duration Focus Area
1. Foundations 2-3 weeks Prerequisites, tools setup, basic concepts
2. Frontend 4-6 weeks React fundamentals to advanced patterns
3. Backend 4-6 weeks Spring Boot APIs and architecture
4. Database 2-3 weeks PostgreSQL design and optimization
5. Integration 2-3 weeks Connecting all layers
6. Advanced 2-4 weeks Security, testing, performance
7. Deployment 1-2 weeks CI/CD, cloud deployment
1. Prerequisites & Foundations
1.1 Required Knowledge Before Starting
• HTML/CSS Fundamentals: Semantic HTML, CSS selectors, Flexbox, Grid, responsive design
• JavaScript Essentials: ES6+ syntax, async/await, array methods, DOM manipulation
• Java Basics: OOP concepts, collections, exception handling, generics
• SQL Fundamentals: Basic queries, joins, CRUD operations
• Git Version Control: Branching, merging, pull requests, conflict resolution
• Command Line: Basic terminal/shell commands, file navigation
1.2 Development Environment Setup
• IDE/Editors: VS Code (React), IntelliJ IDEA or Eclipse (Spring Boot)
• [Link]: v18+ with npm or yarn package manager
• Java: JDK 17+ (LTS recommended)
• PostgreSQL: v14+ with pgAdmin or DBeaver
• Docker: For containerized development and deployment
• Postman: API testing and documentation
• Git: With GitHub/GitLab account
1.3 Foundational Concepts to Master
• HTTP Protocol: Methods (GET, POST, PUT, DELETE), status codes, headers
• REST API Design: Resource naming, statelessness, HATEOAS principles
• JSON: Data format for API communication
• Authentication: Sessions, tokens, JWT basics
• Client-Server Architecture: Request/response cycle, separation of concerns
2. Frontend Development with React
2.1 React Fundamentals (Weeks 1-2)
• Understanding the Virtual DOM and React's rendering process
• JSX syntax and expressions
• Functional components vs class components (focus on functional)
• Props: passing data between components
• State management with useState hook
• Event handling and synthetic events
• Conditional rendering techniques
• Lists and keys for dynamic content
• Component composition and children props
2.2 React Hooks Deep Dive (Weeks 3-4)
• useState: Local state management, state updates, functional updates
• useEffect: Side effects, cleanup, dependency arrays, common patterns
• useContext: Global state without prop drilling
• useReducer: Complex state logic, actions, reducers
• useRef: DOM references, mutable values that persist
• useMemo: Expensive calculations optimization
• useCallback: Function memoization for performance
• Custom Hooks: Extracting reusable logic into custom hooks
2.3 State Management (Week 5)
• Context API: When to use, provider pattern, multiple contexts
• Redux Toolkit: Store setup, slices, async thunks, selectors
• Zustand: Lightweight alternative, when to choose it
• React Query/TanStack Query: Server state management, caching, mutations
2.4 Routing & Navigation (Week 5)
• React Router v6: Routes, Links, NavLinks
• Dynamic routes and URL parameters
• Nested routes and layouts
• Programmatic navigation with useNavigate
• Protected routes and authentication guards
• Route loaders and error boundaries
2.5 Forms & Validation (Week 6)
• Controlled vs uncontrolled components
• React Hook Form: Registration, validation, error handling
• Yup/Zod schema validation
• File uploads and form data
• Multi-step forms and form wizards
2.6 API Integration (Week 6)
• Fetch API and Axios for HTTP requests
• Handling loading, error, and success states
• Custom hooks for API calls (useApi pattern)
• Interceptors for authentication tokens
• Error handling and retry logic
2.7 Advanced Patterns (Week 7)
• Component design patterns: HOCs, render props, compound components
• Performance optimization: [Link], lazy loading, code splitting
• Error boundaries for graceful error handling
• Portals for modals and tooltips
• Suspense for data fetching
2.8 Styling Solutions
• CSS Modules: Scoped CSS, composition
• Tailwind CSS: Utility-first approach, configuration
• Styled Components: CSS-in-JS, dynamic styling
• Component Libraries: Material-UI, Chakra UI, Shadcn/ui
3. Backend Development with Spring Boot
3.1 Spring Framework Fundamentals (Weeks 1-2)
• Dependency Injection: IoC container, @Autowired, constructor injection
• Spring Beans: Bean lifecycle, scopes, configuration
• Annotations: @Component, @Service, @Repository, @Controller
• Application Context: Bean factory, application events
• Configuration: [Link]/yml, profiles, externalized config
3.2 Building REST APIs (Weeks 2-3)
• @RestController: Creating RESTful endpoints
• Request Mapping: @GetMapping, @PostMapping, @PutMapping, @DeleteMapping
• Path Variables & Request Params: Dynamic URLs and query parameters
• Request Body: @RequestBody for JSON deserialization
• Response Handling: ResponseEntity, status codes, headers
• DTO Pattern: Data Transfer Objects for API contracts
• Validation: @Valid, Bean Validation annotations
3.3 Data Persistence with JPA (Weeks 3-4)
• Spring Data JPA: Repository pattern, auto-generated queries
• Entity Mapping: @Entity, @Table, @Column annotations
• Relationships: @OneToMany, @ManyToOne, @ManyToMany, cascade types
• Query Methods: Derived queries, @Query annotation, native queries
• Pagination & Sorting: Pageable, Sort, Page responses
• Transactions: @Transactional, isolation levels, propagation
3.4 Service Layer Architecture (Week 4)
• Separation of concerns: Controller → Service → Repository
• Business logic encapsulation
• Exception handling with @ControllerAdvice
• Custom exceptions and error responses
• Logging with SLF4J and Logback
3.5 Security with Spring Security (Weeks 5-6)
• Authentication: UserDetailsService, password encoding
• JWT Integration: Token generation, validation, refresh tokens
• Authorization: Role-based access, @PreAuthorize, method security
• Security Filter Chain: Custom filters, CORS configuration
• OAuth2: Social login integration basics
3.6 API Documentation (Week 6)
• OpenAPI/Swagger: springdoc-openapi integration
• Annotations: @Operation, @ApiResponse, @Schema
• Swagger UI: Interactive API testing interface
3.7 Testing (Week 7)
• Unit Testing: JUnit 5, Mockito for mocking dependencies
• Integration Testing: @SpringBootTest, TestRestTemplate
• Repository Testing: @DataJpaTest with H2 in-memory database
• MockMvc: Controller layer testing without server
4. Database with PostgreSQL
4.1 PostgreSQL Fundamentals (Week 1)
• Installation and configuration
• psql command-line interface
• Database and schema creation
• Data types: VARCHAR, TEXT, INTEGER, BIGINT, NUMERIC, BOOLEAN, TIMESTAMP, UUID,
JSON/JSONB
• Table creation with constraints
4.2 Database Design (Week 1-2)
• Normalization: 1NF, 2NF, 3NF principles and when to denormalize
• Primary Keys: Serial, BIGSERIAL, UUID strategies
• Foreign Keys: Referential integrity, ON DELETE/UPDATE actions
• Indexes: B-tree, Hash, GIN, GiST - when to use each
• Constraints: UNIQUE, NOT NULL, CHECK, EXCLUDE
• Entity Relationship Diagrams: Visual database modeling
4.3 Advanced Queries (Week 2)
• Complex JOINs: INNER, LEFT, RIGHT, FULL OUTER, CROSS
• Subqueries and Common Table Expressions (CTEs)
• Window functions: ROW_NUMBER, RANK, LAG, LEAD, SUM OVER
• Aggregate functions with GROUP BY and HAVING
• UNION, INTERSECT, EXCEPT set operations
• JSON/JSONB operators and functions
4.4 Performance Optimization (Week 3)
• EXPLAIN ANALYZE: Query plan analysis
• Index Optimization: Composite indexes, partial indexes, covering indexes
• Query Optimization: Avoiding N+1, efficient JOINs
• Connection Pooling: HikariCP configuration
• Partitioning: Range, list, hash partitioning for large tables
• Vacuuming: VACUUM, ANALYZE, autovacuum tuning
4.5 Database Administration
• Backup and restore: pg_dump, pg_restore
• User management and permissions
• Monitoring and logging
• Replication basics
5. Full Stack Integration
5.1 Connecting React to Spring Boot
• API Client Setup: Axios instance with base URL configuration
• Environment Variables: .env files for API endpoints
• CORS Configuration: Enabling cross-origin requests in Spring Boot
• Request/Response Flow: Understanding the full data cycle
5.2 Authentication Flow
• Login form → API call → JWT token received
• Storing tokens securely (httpOnly cookies vs localStorage considerations)
• Attaching tokens to subsequent requests (Axios interceptors)
• Token refresh mechanism
• Protected routes in React based on auth state
• Logout flow and token invalidation
5.3 Data Flow Patterns
• CRUD Operations: Create, Read, Update, Delete through the full stack
• Optimistic Updates: UI updates before server confirmation
• Pagination: Backend pagination with frontend controls
• Search/Filter: Query parameters from React to Spring Boot
• Real-time Updates: WebSocket integration basics
5.4 Error Handling Across Layers
• Global exception handler in Spring Boot
• Standardized error response format
• Frontend error interceptors
• User-friendly error messages
• Validation error display
5.5 File Upload/Download
• Multipart file upload from React
• MultipartFile handling in Spring Boot
• File storage strategies (local, S3)
• Serving files with proper content types
• Progress indicators for uploads
6. Advanced Topics
6.1 Testing Strategy
• Frontend Testing: Jest, React Testing Library, component testing
• E2E Testing: Cypress or Playwright for full flow testing
• API Testing: Postman collections, Newman for CI
• Backend Testing: Unit, integration, and contract testing
• Test Coverage: Setting and maintaining coverage goals
6.2 Performance Optimization
• Frontend: Code splitting, lazy loading, bundle analysis
• Backend: Caching with Redis, query optimization
• Database: Query analysis, connection pooling
• Network: Compression, CDN usage
6.3 Security Best Practices
• HTTPS everywhere
• Input validation and sanitization
• SQL injection prevention (parameterized queries)
• XSS prevention (content security policy)
• CSRF protection
• Rate limiting
• Security headers configuration
6.4 Monitoring & Observability
• Application logging strategies
• Spring Boot Actuator endpoints
• Metrics collection (Micrometer, Prometheus)
• Distributed tracing basics
• Error tracking (Sentry integration)
7. Deployment & DevOps
7.1 Containerization with Docker
• Dockerfile for React (multi-stage build with Nginx)
• Dockerfile for Spring Boot application
• Docker Compose for local development
• Environment variable management
• Volume mounting for databases
7.2 CI/CD Pipeline
• GitHub Actions: Build, test, deploy workflows
• Pipeline Stages: Lint → Test → Build → Deploy
• Artifact Management: Docker registry, JAR artifacts
• Environment Management: Dev, staging, production
7.3 Cloud Deployment Options
• AWS: EC2, RDS, S3, Elastic Beanstalk, ECS
• Heroku: Quick deployment for Spring Boot and React
• Railway/Render: Modern PaaS alternatives
• Vercel: Frontend deployment with edge functions
• DigitalOcean: App Platform, managed databases
7.4 Production Checklist
• Environment-specific configurations
• Database migrations strategy (Flyway/Liquibase)
• SSL/TLS certificate setup
• Domain and DNS configuration
• Backup and disaster recovery plan
• Monitoring and alerting setup
• Documentation and runbooks
PART 2: CHEAT SHEETS
REACT CHEAT SHEET
Components & JSX
Syntax What It Does Example
function Name() {} Defines a functional component function Button() {
return <button>Click</button>;
}
return (<JSX>) Returns JSX to render return (
<div className="card">
<h1>Title</h1>
</div>
);
<Component /> Renders a component <Button />
<Header title="Home" />
{expression} Embeds JS expression in JSX <p>{[Link]}</p>
<span>{2 + 2}</span>
className="name" Adds CSS class (not class) <div className="container">
<p className="text-bold">Hi</p>
</div>
style={{prop: val}} Inline styles as object <div style={{
backgroundColor: "blue",
padding: "10px"
}}>
<>{children}</> Fragment - no extra DOM node <>
<Header />
<Main />
</>
export default Exports component as default export default function App() {
return <Main />;
}
Props
Syntax What It Does Example
function C({prop}) Destructures props in params function Card({title, desc}) {
return <h1>{title}</h1>;
}
prop={value} Passes prop to child <Card title="Hello" count={5} />
prop={callback} Passes function as prop <Button onClick={handleClick} />
{...obj} Spreads object as props <Card {...cardData} />
{children} Accesses nested content function Box({children}) {
return <div>{children}</div>;
}
propName = default Default prop value function Card({title = "Untitled"})
PropTypes Runtime type checking [Link] = {
title: [Link]
};
React Hooks
Syntax What It Does Example
useState(initial) Creates state variable const [count, setCount] =
useState(0);
setState(newVal) Updates state directly setCount(5);
setName("John");
setState(prev => ...) Updates based on previous setCount(prev => prev + 1);
setItems(p => [...p, item]);
useEffect(() => {}) Runs side effect useEffect(() => {
fetchData();
}, []);
useEffect(() => {}, []) Runs once on mount useEffect(() => {
[Link]("Mounted");
}, []);
useEffect(() => {}, [dep]) Runs when dep changes useEffect(() => {
fetchUser(userId);
}, [userId]);
return () => cleanup Cleanup function useEffect(() => {
const id = setInterval(...);
return () => clearInterval(id);
}, []);
useContext(Context) Consumes context value const theme = useContext(ThemeContext);
useRef(initial) Creates mutable ref const inputRef = useRef(null);
<input ref={inputRef} />
useReducer(fn, init) State with reducer pattern const [state, dispatch] =
useReducer(reducer, initial);
useMemo(() => val, []) Memoizes computed value const sorted = useMemo(() =>
[Link](), [items]);
useCallback(fn, []) Memoizes function const handleClick = useCallback(
() => setCount(c => c+1), []);
Event Handling
Syntax What It Does Example
onClick={handler} Click event <button onClick={handleClick}>
Click Me
</button>
onChange={handler} Input change event <input onChange={(e) =>
setVal([Link])} />
onSubmit={handler} Form submit event <form onSubmit={handleSubmit}>
...
</form>
[Link]() Prevents default behavior const handleSubmit = (e) => {
[Link]();
// process form
};
[Link] Gets input value onChange={(e) =>
setEmail([Link])}
onFocus / onBlur Focus events <input onFocus={handleFocus}
onBlur={handleBlur} />
onKeyDown={handler} Keyboard events <input onKeyDown={(e) =>
[Link] === "Enter" && submit()} />
Conditional Rendering
Syntax What It Does Example
{cond && <Comp />} Renders if truthy {isLoggedIn && <Dashboard />}
{[Link] > 0 && <List />}
{cond ? <A /> : <B />} Ternary rendering {isAdmin ? <AdminPanel />
: <UserPanel />}
{cond ? <A /> : null} Render or nothing {loading ? <Spinner /> : null}
if/else in function Early return pattern if (loading) return <Spin />;
if (error) return <Err />;
return <Data />;
Lists & Keys
Syntax What It Does Example
{[Link](item => ...)} Renders list of items {[Link](user =>
<UserCard key={[Link]}
user={user} />
)}
key={unique} Unique identifier for item <li key={[Link]}>{[Link]}</li>
{[Link]().map()} Filter then render {[Link](t => ![Link])
.map(t => <Todo key={[Link]} />)}
{[Link]((item, i) =>)} Access index (avoid as key) {[Link]((item, index) =>
<div key={[Link]}>{index + 1}</div>)}
React Router v6
Syntax What It Does Example
<BrowserRouter> Wraps app for routing <BrowserRouter>
<App />
</BrowserRouter>
<Routes> Container for Route defs <Routes>
<Route path="/" .../>
</Routes>
<Route path="" element={}> Defines a route <Route path="/users"
element={<Users />} />
<Route path=":id"> Dynamic route parameter <Route path="/user/:id"
element={<UserDetail />} />
useParams() Gets URL parameters const { id } = useParams();
// /user/123 → id = "123"
useNavigate() Programmatic navigation const navigate = useNavigate();
navigate("/home");
<Link to=""> Navigation link <Link to="/about">About</Link>
<NavLink> Link with active state <NavLink to="/home"
className={({isActive}) => ...}>
<Outlet /> Renders child routes // In layout component
<Outlet />
useSearchParams() Access query params const [params] = useSearchParams();
[Link]("page")
API Calls (Axios)
Syntax What It Does Example
[Link](url) GET request const res = await [Link](
"/api/users");
setUsers([Link]);
[Link](url, data) POST request await [Link]("/api/users",
{ name: "John", email: "..." });
[Link](url, data) PUT request (full update) await [Link](`/api/users/${id}`,
updatedUser);
[Link](url, data) PATCH request (partial) await [Link](`/api/users/${id}`,
{ name: "Jane" });
[Link](url) DELETE request await [Link](
`/api/users/${id}`);
[Link]({...}) Create configured instance const api = [Link]({
baseURL: "[Link]
});
[Link] Add auth header [Link](
cfg => {
[Link] = token;
return cfg;
});
try/catch Handle errors try {
await [Link](url);
} catch (err) {
setError([Link]);
}
SPRING BOOT CHEAT SHEET
Core Annotations
Syntax What It Does Example
@SpringBootApplication Main entry point @SpringBootApplication
public class MyApp {
public static void main(...) {...}
}
@RestController REST API controller @RestController
@RequestMapping("/api")
public class UserController {}
@Service Business logic layer @Service
public class UserService {
// business methods
}
@Repository Data access layer @Repository
public interface UserRepo
extends JpaRepository<User, Long> {}
@Component Generic Spring bean @Component
public class EmailHelper {}
@Autowired Dependency injection @Autowired
private UserService userService;
// or constructor injection
@Configuration Configuration class @Configuration
public class AppConfig {
@Bean
public Service service() {...}
}
@Bean Defines a Spring bean @Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
@Value("${prop}") Injects config value @Value("${[Link]}")
private String secret;
REST Controller Mappings
Syntax What It Does Example
@GetMapping("/path") Handles GET requests @GetMapping("/users")
public List<User> getAll() {
return [Link]();
}
@GetMapping("/{id}") GET with path variable @GetMapping("/users/{id}")
public User getById(
@PathVariable Long id) {...}
@PostMapping("/path") Handles POST requests @PostMapping("/users")
public User create(
@RequestBody UserDTO dto) {...}
@PutMapping("/{id}") Handles PUT requests @PutMapping("/users/{id}")
public User update(
@PathVariable Long id,
@RequestBody UserDTO dto) {...}
@DeleteMapping("/{id}") Handles DELETE requests @DeleteMapping("/users/{id}")
public void delete(
@PathVariable Long id) {...}
@PathVariable Extracts URL path param @GetMapping("/users/{id}")
public User get(@PathVariable Long id)
@RequestParam Extracts query param @GetMapping("/users")
public List<User> search(
@RequestParam String name) {...}
@RequestBody Deserializes JSON body public User create(
@RequestBody CreateUserDTO dto)
@RequestHeader Extracts header value public void process(
@RequestHeader("X-Token") String t)
Response Handling
Syntax What It Does Example
ResponseEntity<T> Full response control public ResponseEntity<User> get() {
return [Link](user);
}
[Link]() Returns 200 OK return [Link](data);
[Link]() Returns 201 Created URI loc = [Link]("/users/" + id);
return ResponseEntity
.created(loc).body(user);
[Link]() Returns 204 No Content return [Link]()
.build();
[Link]() Returns 404 Not Found return [Link]()
.build();
[Link]() Returns 400 Bad Request return [Link]()
.body(errors);
.status(HttpStatus.X) Custom status code return ResponseEntity
.status([Link])
.body(msg);
.headers(headers) Add custom headers HttpHeaders h = new HttpHeaders();
return [Link]()
.headers(h).body(data);
JPA Entity Annotations
Syntax What It Does Example
@Entity Marks class as entity @Entity
@Table(name = "users")
public class User {...}
@Table(name = "") Specifies table name @Table(name = "app_users")
@Id Primary key field @Id
@GeneratedValue(...)
private Long id;
@GeneratedValue Auto-generate ID @GeneratedValue(
strategy = [Link])
@Column Column configuration @Column(name = "email",
nullable = false, unique = true)
private String email;
@OneToMany One-to-many relation @OneToMany(mappedBy = "user",
cascade = [Link])
private List<Order> orders;
@ManyToOne Many-to-one relation @ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToMany Many-to-many relation @ManyToMany
@JoinTable(name = "user_roles")
private Set<Role> roles;
@JoinColumn Foreign key column @JoinColumn(name = "category_id")
@Enumerated Enum mapping @Enumerated([Link])
private Status status;
@CreatedDate Auto-set creation time @CreatedDate
private LocalDateTime createdAt;
Spring Data JPA Repository
Syntax What It Does Example
extends JpaRepository<T,ID> Full CRUD + pagination public interface UserRepo
extends JpaRepository<User, Long> {}
findById(id) Find by primary key Optional<User> user =
[Link](1L);
findAll() Get all entities List<User> users =
[Link]();
save(entity) Insert or update User saved = [Link](user);
deleteById(id) Delete by ID [Link](1L);
findByField(value) Derived query by field List<User> findByEmail(String email);
findByFieldContaining LIKE query List<User> findByNameContaining(
String name);
findByFieldAndField Multiple conditions User findByEmailAndStatus(
String email, Status status);
findByFieldOrderBy With sorting List<User> findByStatusOrderByNameAsc(
Status status);
@Query("JPQL") Custom JPQL query @Query("SELECT u FROM User u
WHERE [Link] = true")
List<User> findActiveUsers();
@Query(native=true) Native SQL query @Query(value = "SELECT * FROM...",
nativeQuery = true)
findAll(Pageable) Pagination support Page<User> page = [Link](
[Link](0, 10));
Validation Annotations
Syntax What It Does Example
@Valid Triggers validation public User create(
@Valid @RequestBody UserDTO dto)
@NotNull Field cannot be null @NotNull(message = "Required")
private String name;
@NotBlank Not null and not empty @NotBlank
private String email;
@NotEmpty Collection not empty @NotEmpty
private List<String> tags;
@Size(min, max) String/collection size @Size(min = 2, max = 100)
private String name;
@Min / @Max Numeric bounds @Min(0) @Max(150)
private Integer age;
@Email Valid email format @Email
private String email;
@Pattern(regexp) Regex pattern match @Pattern(regexp = "^[A-Z]{3}$")
private String code;
@Past / @Future Date validation @Past
private LocalDate birthDate;
Exception Handling
Syntax What It Does Example
@ControllerAdvice Global exception handler @ControllerAdvice
public class GlobalHandler {}
@ExceptionHandler Handles specific exception @ExceptionHandler(
[Link])
public ResponseEntity<?> handle(
NotFoundException ex) {...}
@ResponseStatus Sets HTTP status @ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException
extends RuntimeException {}
throw new Exception() Throw custom exception throw new NotFoundException(
"User not found");
[Link] / yml
Syntax What It Does Example
[Link] Application port [Link]=8080
[Link] Database URL [Link]=
jdbc:postgresql://localhost/mydb
[Link] Database username [Link]=postgres
[Link] Database password [Link]=secret
[Link]-auto Schema generation [Link]-auto=
update # or: none, create, validate
[Link]-sql Log SQL queries [Link]-sql=true
[Link] Log level [Link]=INFO
[Link]=DEBUG
[Link] Active profile [Link]=dev
POSTGRESQL CHEAT SHEET
Common Data Types
Syntax What It Does Example
INTEGER / INT 4-byte signed integer age INTEGER
BIGINT 8-byte signed integer id BIGINT
SERIAL Auto-incrementing int id SERIAL PRIMARY KEY
BIGSERIAL Auto-incrementing bigint id BIGSERIAL PRIMARY KEY
VARCHAR(n) Variable-length string name VARCHAR(100)
TEXT Unlimited length string description TEXT
BOOLEAN True/false value active BOOLEAN DEFAULT true
TIMESTAMP Date and time created_at TIMESTAMP
TIMESTAMPTZ Timestamp with timezone created_at TIMESTAMPTZ DEFAULT NOW()
DATE Date only (no time) birth_date DATE
NUMERIC(p,s) Exact decimal price NUMERIC(10,2)
UUID Universally unique ID id UUID DEFAULT gen_random_uuid()
JSONB Binary JSON (preferred) metadata JSONB
ARRAY Array of values tags TEXT[]
Table Operations (DDL)
Syntax What It Does Example
CREATE TABLE Creates new table CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
DROP TABLE Deletes table DROP TABLE IF EXISTS users;
ALTER TABLE ADD Adds column ALTER TABLE users
ADD COLUMN email VARCHAR(255);
ALTER TABLE DROP Removes column ALTER TABLE users
DROP COLUMN temp_field;
ALTER TABLE ALTER Modifies column ALTER TABLE users
ALTER COLUMN name TYPE TEXT;
ALTER TABLE RENAME Renames column/table ALTER TABLE users
RENAME COLUMN name TO full_name;
CREATE INDEX Creates index CREATE INDEX idx_user_email
ON users(email);
CREATE UNIQUE INDEX Unique index CREATE UNIQUE INDEX idx_email
ON users(email);
DROP INDEX Removes index DROP INDEX IF EXISTS idx_user_email;
CRUD Operations
Syntax What It Does Example
INSERT INTO Inserts new row INSERT INTO users (name, email)
VALUES ('John', 'john@[Link]');
INSERT ... RETURNING Insert and return data INSERT INTO users (name)
VALUES ('Jane')
RETURNING id, name;
SELECT * FROM Selects all columns SELECT * FROM users;
SELECT cols FROM Selects specific columns SELECT id, name, email
FROM users;
SELECT ... WHERE Filters rows SELECT * FROM users
WHERE active = true;
UPDATE ... SET Updates rows UPDATE users
SET name = 'John Doe'
WHERE id = 1;
UPDATE ... RETURNING Update and return UPDATE users SET active = false
WHERE id = 1
RETURNING *;
DELETE FROM Deletes rows DELETE FROM users
WHERE id = 1;
DELETE ... RETURNING Delete and return DELETE FROM users
WHERE id = 1
RETURNING *;
UPSERT (ON CONFLICT) Insert or update INSERT INTO users (id, name)
VALUES (1, 'John')
ON CONFLICT (id)
DO UPDATE SET name = [Link];
WHERE Clause Operators
Syntax What It Does Example
= / <> / != Equality / inequality WHERE status = 'active'
WHERE role <> 'admin'
> / < / >= / <= Comparisons WHERE age >= 18
WHERE price < 100
AND / OR Logical operators WHERE active = true AND age > 18
IN (values) Match any in list WHERE status IN ('active', 'pending')
NOT IN Not in list WHERE id NOT IN (1, 2, 3)
BETWEEN Range inclusive WHERE age BETWEEN 18 AND 65
LIKE Pattern match WHERE name LIKE 'John%'
WHERE email LIKE '%@[Link]'
ILIKE Case-insensitive LIKE WHERE name ILIKE '%john%'
IS NULL / IS NOT NULL Null checks WHERE deleted_at IS NULL
EXISTS Subquery exists WHERE EXISTS (
SELECT 1 FROM orders
WHERE orders.user_id = [Link])
ANY / ALL Compare to array WHERE id = ANY(ARRAY[1,2,3])
JOIN Operations
Syntax What It Does Example
INNER JOIN Matching rows only SELECT [Link], [Link]
FROM users u
INNER JOIN orders o ON [Link] = o.user_id;
LEFT JOIN All left + matching right SELECT [Link], [Link]
FROM users u
LEFT JOIN orders o ON [Link] = o.user_id;
RIGHT JOIN All right + matching left SELECT [Link], [Link]
FROM users u
RIGHT JOIN orders o ON [Link] = o.user_id;
FULL OUTER JOIN All rows from both SELECT [Link], [Link]
FROM users u
FULL OUTER JOIN orders o ON [Link] = o.user_id;
CROSS JOIN Cartesian product SELECT * FROM colors
CROSS JOIN sizes;
Self JOIN Table joins itself SELECT [Link], [Link] AS manager
FROM employees e
LEFT JOIN employees m ON e.mgr_id = [Link];
Aggregation & Grouping
Syntax What It Does Example
COUNT(*) Counts all rows SELECT COUNT(*) FROM users;
COUNT(col) Counts non-null values SELECT COUNT(email) FROM users;
SUM(col) Sum of values SELECT SUM(amount) FROM orders;
AVG(col) Average of values SELECT AVG(price) FROM products;
MIN(col) / MAX(col) Min/max value SELECT MIN(age), MAX(age)
FROM users;
GROUP BY Groups rows SELECT status, COUNT(*)
FROM orders
GROUP BY status;
HAVING Filters groups SELECT user_id, COUNT(*)
FROM orders
GROUP BY user_id
HAVING COUNT(*) > 5;
ORDER BY Sorts results SELECT * FROM users
ORDER BY created_at DESC;
LIMIT / OFFSET Pagination SELECT * FROM users
ORDER BY id
LIMIT 10 OFFSET 20;
DISTINCT Unique values only SELECT DISTINCT category
FROM products;
Advanced Queries
Syntax What It Does Example
WITH (CTE) Common Table Expression WITH active_users AS (
SELECT * FROM users
WHERE active = true
)
SELECT * FROM active_users;
Subquery Nested query SELECT * FROM users
WHERE id IN (
SELECT user_id FROM orders
);
COALESCE First non-null value SELECT COALESCE(nickname, name)
FROM users;
NULLIF Returns null if equal SELECT NULLIF(a, b) FROM t;
CASE WHEN Conditional expression SELECT name,
CASE
WHEN age < 18 THEN 'minor'
ELSE 'adult'
END AS category
FROM users;
CAST / :: Type conversion SELECT CAST(id AS TEXT);
SELECT id::TEXT;
STRING_AGG Concatenate strings SELECT STRING_AGG(name, ', ')
FROM users;
ARRAY_AGG Aggregate into array SELECT ARRAY_AGG(tag)
FROM post_tags
GROUP BY post_id;
Window Functions
Syntax What It Does Example
ROW_NUMBER() OVER() Sequential row number SELECT name,
ROW_NUMBER() OVER(
ORDER BY created_at) AS rn
FROM users;
RANK() OVER() Rank with gaps SELECT name, score,
RANK() OVER(
ORDER BY score DESC) AS rank
FROM players;
DENSE_RANK() OVER() Rank without gaps SELECT name, score,
DENSE_RANK() OVER(
ORDER BY score DESC)
FROM players;
PARTITION BY Partition window SELECT dept, name,
ROW_NUMBER() OVER(
PARTITION BY dept
ORDER BY salary DESC)
FROM employees;
LAG(col, n) Previous row value SELECT date, amount,
LAG(amount, 1) OVER(
ORDER BY date) AS prev_amt
FROM sales;
LEAD(col, n) Next row value SELECT date, amount,
LEAD(amount, 1) OVER(
ORDER BY date) AS next_amt
FROM sales;
SUM() OVER() Running total SELECT date, amount,
SUM(amount) OVER(
ORDER BY date) AS running_total
FROM sales;
JSONB Operations
Syntax What It Does Example
->> Get JSON value as text SELECT data->>'name'
FROM users;
-> Get JSON value as JSON SELECT data->'address'
FROM users;
#>> Get nested value as text SELECT data#>>'{address,city}'
FROM users;
@> Contains JSON SELECT * FROM users
WHERE data @> '{"active": true}';
? Key exists SELECT * FROM users
WHERE data ? 'email';
jsonb_set() Update JSON field UPDATE users SET data =
jsonb_set(data, '{name}',
'"John"');
|| Merge JSON objects UPDATE users SET data =
data || '{"verified": true}';
jsonb_array_elements Expand JSON array SELECT * FROM users,
jsonb_array_elements(data->'tags')
AS tag;
Constraints
Syntax What It Does Example
PRIMARY KEY Unique identifier id SERIAL PRIMARY KEY
FOREIGN KEY References other table user_id INT REFERENCES users(id)
UNIQUE No duplicate values email VARCHAR(255) UNIQUE
NOT NULL Cannot be null name VARCHAR(100) NOT NULL
DEFAULT Default value active BOOLEAN DEFAULT true
CHECK Value constraint age INT CHECK (age >= 0)
ON DELETE CASCADE Delete related rows FOREIGN KEY (user_id)
REFERENCES users(id)
ON DELETE CASCADE
ON DELETE SET NULL Set null on delete FOREIGN KEY (category_id)
REFERENCES categories(id)
ON DELETE SET NULL
INTEGRATION PATTERNS CHEAT SHEET
React + Spring Boot Connection
Pattern What It Does Example
Axios Instance Configured API client const api = [Link]({
baseURL: "[Link]
});
Environment Variables API URL config REACT_APP_API_URL=[Link]
const api = [Link]({
baseURL: [Link].REACT_APP_API_URL
});
CORS Config Allow cross-origin @Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(...) {
[Link]("/api/**")
.allowedOrigins("[Link]
}
};
}
}
JWT Authentication Flow
Step React (Frontend) Spring Boot (Backend)
1. Login const res = await [Link]( @PostMapping("/auth/login")
"/auth/login", credentials); public ResponseEntity<?> login(
[Link]( @RequestBody LoginRequest req) {
"token", [Link]); // authenticate & return JWT
}
2. Store Token [Link]("token", jwt); Return token in response body
// or use httpOnly cookie or set httpOnly cookie
3. Send Token [Link]( @Bean
config => { SecurityFilterChain filterChain(
[Link] = HttpSecurity http) {
`Bearer ${token}`; // configure JWT filter
return config; }
});
4. Validate Handle 401 responses JwtAuthenticationFilter
Redirect to login validates token on each request
5. Refresh Check token expiry @PostMapping("/auth/refresh")
Call refresh endpoint return new access token
Error Handling Pattern
Layer Implementation Example
Backend Exception Custom exception class public class ResourceNotFoundException
extends RuntimeException {
public ResourceNotFoundException(String msg) {
super(msg);
}
}
Backend Handler @ControllerAdvice handler @ExceptionHandler([Link])
public ResponseEntity<?> handleNotFound(
ResourceNotFoundException ex) {
return [Link](404)
.body([Link]("error", [Link]()));
}
Frontend Interceptor Axios error interceptor [Link](
response => response,
error => {
if ([Link] === 401) {
// redirect to login
}
return [Link](error);
}
);
Frontend Component Try-catch in async try {
const data = await [Link]("/users");
setUsers(data);
} catch (err) {
setError([Link]?.data?.error);
}
Docker Configuration
File Purpose Content
React Dockerfile Build frontend image # Build stage
FROM node:18-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production stage
FROM nginx:alpine
COPY --from=build /app/build /usr/share/nginx/html
Spring Dockerfile Build backend image FROM eclipse-temurin:17-jdk-alpine
WORKDIR /app
COPY target/*.jar [Link]
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "[Link]"]
[Link] Multi-container setup version: "3.8"
services:
frontend:
build: ./frontend
ports: ["3000:80"]
backend:
build: ./backend
ports: ["8080:8080"]
environment:
- SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/mydb
depends_on: [db]
db:
image: postgres:15
environment:
- POSTGRES_DB=mydb
- POSTGRES_PASSWORD=secret
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:
Recommended Project Structure
Frontend (React):
src/
■■■ components/ # Reusable UI components
■ ■■■ common/ # Buttons, inputs, modals
■ ■■■ layout/ # Header, Footer, Sidebar
■■■ pages/ # Route-level components
■■■ hooks/ # Custom React hooks
■■■ services/ # API call functions
■■■ context/ # React Context providers
■■■ utils/ # Helper functions
■■■ styles/ # Global styles
Backend (Spring Boot):
src/main/java/com/example/
■■■ config/ # Configuration classes
■■■ controller/ # REST controllers
■■■ service/ # Business logic
■■■ repository/ # Data access (JPA)
■■■ model/ # Entity classes
■ ■■■ entity/ # JPA entities
■ ■■■ dto/ # Data Transfer Objects
■■■ exception/ # Custom exceptions
■■■ security/ # Security config, JWT
■■■ util/ # Utility classes
ADDITIONAL RESOURCES
Official Documentation
• React: [Link]
• Spring Boot: [Link]/projects/spring-boot
• PostgreSQL: [Link]/docs/
• Spring Data JPA: [Link]/projects/spring-data-jpa
• React Router: [Link]
• Axios: [Link]
Recommended Learning Platforms
• freeCodeCamp - Free comprehensive courses
• The Odin Project - Full stack curriculum
• Baeldung - Spring Boot tutorials
• Josh W. Comeau - React deep dives
• Spring Academy - Official Spring courses
Essential Tools
• VS Code Extensions: ES7 React Snippets, Prettier, ESLint, Thunder Client
• IntelliJ Plugins: Lombok, Spring Boot Assistant, Database Tools
• Database Tools: pgAdmin, DBeaver, DataGrip
• API Testing: Postman, Insomnia, Thunder Client
• Version Control: GitHub Desktop, GitKraken, SourceTree
Final Notes
This guide covers the essential knowledge needed to become a proficient full stack developer with React, Spring
Boot, and PostgreSQL. Remember that consistent practice is key — build projects, contribute to open source, and
never stop learning. The technology landscape evolves rapidly, so stay curious and keep your skills updated.
Good luck on your full stack journey!