###### tags: `Java` `CodeSnippets`
# Java Code Snippets
---
**Table Of Contents**
1. Block Comments
a. Attributes
b. Constructor
c. Getter and Setter
d. Method
e. Interface
f. Relationship
2. JSP Template
3. Model File Snippets
a. Template
b. Validation Snippets
c. Relationship Snippets
4. Repository File Snippets
5. Service File Snippets
6. Controller File Snippets
7. JSP Snippets
## 1. Quick Block Comments
Attributes Label
```
// ==========================
// ATTRIBUTES
// ==========================
```
Constructor Label
```
// ==========================
// CONSTRUCTOR
// ==========================
```
Getter and Setter Label
```
// ==========================
// GETTERS / SETTERS
// ==========================
```
Method Label
```
// ==========================
// METHODS
// ==========================
```
Interface Label
```
// ==========================
// INTERFACE
// ==========================
```
Relationship Label
```
// ==========================
// RELATIONSHIPS
// ==========================
```
## 2. JSP Template
```java!=
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!-- for forms -->
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
<!-- for validation -->
<%@ page isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head>
<!-- for Bootstrap CSS -->
<link rel="stylesheet" href="/webjars/bootstrap/css/bootstrap.min.css" />
<!-- YOUR own local CSS -->
<link rel="stylesheet" type="text/css" href="/css/style.css">
<!-- For any Bootstrap that uses JS -->
<script src="/webjars/bootstrap/js/bootstrap.min.js"></script>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<header>
<h1>Hello</h1>
</header>
</body>
</html>
```
## 3. Model File Snippets
### Base Model File Setup
```java!=
@Entity
@Table(name="classNames")
public class ClassName {
// ==========================
// ATTRIBUTES
// ==========================
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// private String <columnName>;
@Column(updatable = false)
@DateTimeFormat(pattern = "yyy-MM-dd")
private Date createdAt;
@DateTimeFormat(pattern = "yyy-MM-dd")
private Date updatedAt;
// ==========================
// RELATIONSHIPS
// ==========================
// ==========================
// CONSTRUCTOR
// ==========================
// Empty Contstuctor
public <ClassName>() {
}
// <!-- Here you will right click > Source > Generate Constructor Using Feilds > Uncheck id, createdAt and updatedAt and any NON required fields like in a one to many the one side -->
// <!-- It should fill in the constructor function -->
// <!-- Here you will right click again > Source > Generate Getters and Setters > Select all -->
// <!-- They will be filled in here -->
// ==========================
// GETTERS / SETTERS
// ==========================
@PrePersist
protected void onCreate() {
this.createdAt = new Date();
}
@PreUpdate
protected void onUpdate() {
this.updatedAt = new Date();
}
}
```
### Model File Validations
For Numbers Only - with our with out custom message
```java!=
@NotNull(message="Must have entry")
@NotNull
@Min(value = 1, message = "Age must be at least 1")
@Min(value = 59, message = "Age must not be more than 50")
```
This will only work for strings with and without custom message
```java!=
@NotEmpty(message="Must have a name")
@NotEmpty
```
For All others including strings
```java!=
@NotBlank
@Size(min=1, max=255, message="Needs to be between 1-255 characters")
@NotBlank(message="Custom message if desired")
```
### Model Relationship Snippets
Make sure that any classes that are connected to more than 1 model... user to bio and user to grade that the bio and grade lowercase class variable is different from each other
One to One - Base (created first)
```java!=
@OneToOne(mappedBy="class", cascade=CascadeType.ALL, fetch=FetchType.LAZY)
private Class class;
```
One to One - with base_id (created after base)
```java!=
@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name="class_id")
private Class class;
```
One to Many - One side
```java!=
@OneToMany(mappedBy="class", fetch = FetchType.LAZY) // this class var in mapped by MUST be the same as the private Class class lowercase var on the many side
private List<Class> classs; // lowercase should be plural
```
One to Many - Many side
```java!=
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="class_id")
private Class class;
```
Many to Many - with 3rd file for middle table
```java!=
// Side 1
@OneToMany(mappedBy="class", fetch=FetchType.LAZY)
private List<ClassClass> classs;
// Middle
// connect Side 1
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="class_id")
private Class class;
// connect Side 2
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="class_id")
private Class class;
// Side 2
@OneToMany(mappedBy="class", fetch=FetchType.LAZY)
private List<ClassOtherclass> classs;
```
Many to Many - without extra file
```java!=
// Goes on both
@ManyToMany(mappedBy="class", fetch=FetchType.LAZY)
@JoinTable(name="classclass"),
joinColumns = @JoinColumn(name="thisClass_id")
inverseJoinColumns = @JoinColumn(name = "otherClass_id")
private List<OtherClass> classs
```
## 4. Repository File Snippets
```java!=
@Repository
public interface <>Repository extends CrudRepository<<className>, Long> {
List<className> findAll();
}
```
## 5. Service File Snippets
```java!=
@Service
public class <>Service {
@Autowired
private <>Repository <>Repository;
public List<className> getAll(){
return <>Repository.fiindAll();
}
}
```
Crud Template
```java!
// ==========================
// CRUD METHODS
// ==========================
// create
public <MODEL_NAME> createOne(<MODEL_NAME> i) {
return <repo_name>.save(i);
}
// read all
public List<<MODEL_NAME>> getAll() {
return <repo_name>.findAll();
}
// read one
public <MODEL_NAME> getOne(Long id) {
return <repo_name>.findById(id).orElse(null);
}
// update
public <MODEL_NAME> updateOne(<MODEL_NAME> i) {
return <repo_name>.save(i);
}
// delete
public void deleteOne(Long id) {
<repo_name>.deleteById(id);
}
```
## 6. Controller File Snippets
```java!=
@Controller
public class HomeController {
@Autowired
private <>Service <>Service;
@GetMapping("/")
public String index(@ModelAttribute("className") ClassName className, Model model) {
model.addAttribute("all<className",<>Service.getAll());
return "index.jsp";
}
}
```
## 7. JSP Snippets
ForEach - looping through list
```java!=
<c:forEach items="${ all<className> }" var = "<className>">
<p>${ <className>.<columnName> } </p>
</c:forEach>
```
Table Set up
```java!=
<table>
<tr>
<th>Table Header</th>
<th>Table Header</th>
<th>Table Header</th>
</tr>
<c:forEach items="${ all<className> }" var = "<className>">
<tr>
<td>${ <className>.<columnName> }</td>
<td>${ <className>.<columnName> }</td>
<td>${ <className>.<columnName> }</td>
</tr>
</c:forEach>
</table>
```
Links within for loops (containing id)
```java!=
<a href="/route/${ class.id }/view">View</a>
```