---
# System prepended metadata

title: lab2 20230515

---

# lab2 20230515
# CourseBean
```
package com.ctbcbank.demo.lab2.bean;

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CourseBean {
//	cascade fetch mappedBy
//	定義id
//	設定生成策略
//	定義其他欄位與屬性
//	...
//	....
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;
	private String name;
	private int price;
	private Date createdAt= new Date();
	private Date updatedAt= new Date();

//	使用callback 從7選1
//	@PrePersist
//	public void callMeWhenCreated() {
////		createdAt=目前時間
//		createdAt = new Date();
//	}
//
//	@PrePersist
//	public void callMeWhenUpdated() {
////		updatedAt=目前時間
//		updatedAt = new Date();
//	}

//	指定類別
	@ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
	@JoinColumn(name = "courseCategory_id",referencedColumnName="id")
	private CourseCategoryBean category;

//	記得從7選1 callback
//	@PreUpdate
//	public void callMeBeforeObjectDelete() {
////		this.category = category;
//	}

	public CourseBean(String name, int price) {
		super();
		this.name = name;
		this.price = price;
	}
}

```
# CourseCategoryBean
```
package com.ctbcbank.demo.lab2.bean;

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

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

import lombok.Data;
import lombok.NoArgsConstructor;

@Entity
@Data
@NoArgsConstructor
public class CourseCategoryBean {
//	定義id
//	設定生成策略
//	定義其他欄位與屬性
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY) // 設定必要的參數>生成的策略?
	private Long id;
	private String name;
//	private int price;
	
	@OneToMany(mappedBy="category",cascade = CascadeType.ALL,fetch=FetchType.EAGER)
	private List<CourseBean> courses = new ArrayList<>();

	public CourseCategoryBean(List<CourseBean> courses) {
		super();
		this.courses = courses;
	}
}
```
# ourseBeanRestController
```
package com.ctbcbank.demo.lab2.controller.rest;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ctbcbank.demo.lab2.bean.CourseBean;
import com.ctbcbank.demo.lab2.repository.CourseBeanRepository;
import com.ctbcbank.demo.lab2.service.CourseBeanService;

import lombok.extern.slf4j.Slf4j;

@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/api/course")
public class CourseBeanRestController {
	private static final String KEY1 = "data";
	@Autowired
	private CourseBeanRepository repository;
	@Autowired
	CourseBeanService service;
	
	@GetMapping("/all")
	public List<CourseBean> getAllCourses() {
		return service.getAllCourseBean();
	}
	
//	@Autowired
//	CourseBeanService service;
//	@RequestMapping(method=RequestMethod.GET)
//	List<CourseBean> getAllCourses() {
//		return service.getAllCourseBean();
//	}
//	@RequestMapping(method=RequestMethod.POST)
//	@ResponseStatus(HttpStatus.CREATED)
//	
//	CourseBean postCourseBean(@RequestBody CourseBean bean) {
//		return service.saveOrUpdateCourseBean(bean);
//	}
}

```
# CourseBeanRepository
```
package com.ctbcbank.demo.lab2.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import com.ctbcbank.demo.lab2.bean.CourseBean;

//如果是UUID，這裡就要換成UUID
public interface CourseBeanRepository extends CrudRepository<CourseBean, Long>,JpaRepository<CourseBean, Long> {
	CourseBean getReferenceById(long id);

	List<CourseBean> findAll();

	@Query("SELECT x FROM CourseBean x ORDER BY x.name, x.price,x.createdAt,x.updatedAt")
	List<CourseBean> findAllOrdeByName();
}

```
# CourseCategoryBeanRepository
```
package com.ctbcbank.demo.lab2.repository;

import java.util.List;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Service;

import com.ctbcbank.demo.lab2.bean.CourseCategoryBean;

@Service
public interface CourseCategoryBeanRepository extends CrudRepository<CourseCategoryBean, Long> {
	CourseCategoryBean getReferenceById(long id);
	List<CourseCategoryBean> findAll();
}
```
# CourseBeanRunner
```
package com.ctbcbank.demo.lab2.runner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.ctbcbank.demo.lab2.bean.CourseBean;
import com.ctbcbank.demo.lab2.repository.CourseBeanRepository;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@Order(1)
public class CourseBeanRunner implements CommandLineRunner {
	@Autowired
	CourseBeanRepository repository;

	@Override
	public void run(String... args) throws Exception {
		log.info("will access repository");
//		新增一筆資料	
//		修改屬性
//		儲存
//		h2 console看，應該會生效
		insertData();
		modifyData();
		getData();
		deleteData();
		
	}

	private void deleteData() {
		repository.deleteById(2l);
		log.info("2rd course has been delete!");
		
	}

	private void insertData() {
		CourseBean c1 = new CourseBean("Java0512", 20000);
		CourseBean c2 = new CourseBean("C#0512", 1000);
		CourseBean c3 = new CourseBean("Python12", 3000);
		CourseBean[] courseBean = { c1, c2, c3 };
		for (CourseBean c : courseBean) {
//			c.setCreatedAt(c.getCreatedAt());
			repository.save(c);
		}
	}

	private void modifyData() {
		CourseBean courseBean = repository.findById(1L).get();
		courseBean.setName("C#0511");
		courseBean.setPrice(1500);
//		courseBean.setUpdatedAt(courseBean.getUpdatedAt());
		CourseBean saveCourseBean = repository.save(courseBean);
		log.info("Course Modify Result:{}",saveCourseBean);
	}

	private void getData() {
		log.info("Data num:{}", repository.count());
		repository.findAll().forEach(c -> {
			log.info("store courseBean:{},{},{}", c.getId(), c.getName(), c.getPrice());
		});
	}
}
```
# CourseCategoryBeanRunner
```
package com.ctbcbank.demo.lab2.runner;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.ctbcbank.demo.lab2.bean.CourseBean;
import com.ctbcbank.demo.lab2.bean.CourseCategoryBean;
import com.ctbcbank.demo.lab2.repository.CourseCategoryBeanRepository;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@Order(2)
public class CourseCategoryBeanRunner implements CommandLineRunner {
//	@Autowired
//	CourseBeanRepository repository;
	@Autowired
	CourseCategoryBeanRepository repository;
	private List<CourseBean> courses = new ArrayList<>();

	@Override
	public void run(String... args) throws Exception {
		insertData();
		modifyData();
		getData();
		deleteData();
	}

	private void deleteData() {
		repository.deleteById(1l);
		log.info("1st category has been delete!");
	}

	private void getData() {
		log.info("Category num:{}", repository.count());
		repository.findAll().forEach(c -> {
			log.info("store courseCategoryBean:{},{}", c.getId(), c.getName());
		});
		
	}

	private void modifyData() {
		CourseCategoryBean courseCategoryBean = repository.findById(1L).get();
		courseCategoryBean.setName("courseCategory3");
		repository.save(courseCategoryBean);
//		CourseCategoryBean saveCourseCategoryBean = repository.save(courseCategoryBean);
//		log.info("CourseCategory Modify Result:{}",saveCourseCategoryBean);
	}

	private void insertData() {
		CourseBean c1 = new CourseBean("Java1", 1000);
		CourseBean c2 = new CourseBean("C#1", 2000);
//		CourseBean c3 = new CourseBean("C#2", 3000);
		CourseCategoryBean courseCategoryBean = new CourseCategoryBean();
		courseCategoryBean.setName("courseCategory1");
		CourseCategoryBean courseCategoryBean2 = new CourseCategoryBean();
		courseCategoryBean2.setName("courseCategory2");
		
//		新增c1、c3至同一個category，用來檢查刪除後2個course是否會被刪除
		c1.setCategory(courseCategoryBean);
//		c3.setCategory(courseCategoryBean);
		c2.setCategory(courseCategoryBean2);
		List<CourseBean> courses = new ArrayList<>();
		courses.add(c1);
		courses.add(c2);
//		courses.add(c3);

		courseCategoryBean.setCourses(courses);
//		CourseCategoryBean CourseCategorySave = repository.save(courseCategoryBean);
		repository.save(courseCategoryBean);
		repository.save(courseCategoryBean2);
//		log.info("courseCategoryBean:{}", repository.save(courseCategoryBean));

	}

}
```
# CourseBeanServiceJPAImplement
```
package com.ctbcbank.demo.lab2.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ctbcbank.demo.lab2.bean.CourseBean;
import com.ctbcbank.demo.lab2.repository.CourseBeanRepository;

@Component
public class CourseBeanServiceJPAImplement implements CourseBeanService{
	@Autowired
	private CourseBeanRepository repository;

	@Override
	public List<CourseBean> getAllCourseBean() {
		return repository.findAll();
	}

	@Override
	public CourseBean getCourseBeanById(long Id) {
		return repository.getReferenceById(Id);
	}

	@Override
	public CourseBean saveOrUpdateCourseBean(CourseBean bean) {
		return repository.save(bean);
	}

	@Override
	public void removeCourseBean(long id) {
		repository.deleteById(id);
		
	}

	@Override
	public void clearAll() {
		repository.deleteAll(getAllCourseBean());

	}

}

```
# CourseCategoryBeanServiceJPAImplement
```
package com.ctbcbank.demo.lab2.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ctbcbank.demo.lab2.bean.CourseCategoryBean;
import com.ctbcbank.demo.lab2.repository.CourseCategoryBeanRepository;
@Component
public class CourseCategoryBeanServiceJPAImplement implements CourseCategoryBeanService {
	@Autowired
	private CourseCategoryBeanRepository repository;
	@Override
	public List<CourseCategoryBean> getAllCourseCategoryBean() {
		return repository.findAll();
	}

	@Override
	public CourseCategoryBean getCourseCategoryBeanById(long id) {
		return repository.getReferenceById(id);
	}

	@Override
	public CourseCategoryBean saveOrUpdateCourseCategoryBean(CourseCategoryBean bean) {
		return repository.save(bean);
	}

	@Override
	public void removeCourseCategoryBean(long id) {
		repository.deleteById(id);
	}

	@Override
	public void clearAll() {
		repository.deleteAll(getAllCourseCategoryBean());
	}

}

```
# all.html
```
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<html>
<head>
<meta charset="UTF8">
<title>課程</title>
</head>
<body>
	<h1>課程列表</h1>
	<h3>
		<a href="./add">新增課程</a>
	</h3>
	<table th:inline="text" border="1">
		<tr>
			<td>id</td>
			<td>name</td>
			<td>price</td>
			<td>刪除</td>
			<td>修改</td>
		</tr>
		<tr th:each="obj:${data}">
			<td>[[${obj.id}]]</td>
			<td>[[${obj.name}]]</td>
			<td>[[${obj.price}]]</td>
			<td><a th:href="'del?idString='+${obj.id}">刪除</a></td>
			<td><a th:href="'mod?idString='+${obj.id}">修改</a></td>
		</tr>
	</table>
</body>
</html>
```









