Skip to content
Snippets Groups Projects
Commit 0ebd777f authored by fz2907's avatar fz2907
Browse files

Added the spring db connection package, and set up the properties file.

Add ExampleRepository.java and ExampleService.java to show how to make Spring service to interact with DB.
parent da19d30d
No related branches found
No related tags found
3 merge requests!27Sprint 1 done,!7Changed DB port from 3306 to 3307. So it will not interrupt with your own local MySQL,!6Service to DB connection is ready.
......@@ -4,11 +4,14 @@
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="af5ba6fa-a4b6-4030-a5d4-1a5d3d23a59d" name="Changes" comment="added docker-compose.yml to create the database">
<list default="true" id="af5ba6fa-a4b6-4030-a5d4-1a5d3d23a59d" name="Changes" comment="Added the spring db connection package, and set up the properties file.">
<change afterPath="$PROJECT_DIR$/BackendFolder/SwitchRoom/src/main/java/vt/CS5934/SwitchRoom/repositories/ExampleRepository.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/BackendFolder/SwitchRoom/src/main/java/vt/CS5934/SwitchRoom/services/ExampleService.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/BackendFolder/SwitchRoom/build.gradle" beforeDir="false" afterPath="$PROJECT_DIR$/BackendFolder/SwitchRoom/build.gradle" afterDir="false" />
<change beforePath="$PROJECT_DIR$/BackendFolder/SwitchRoom/src/main/java/vt/CS5934/SwitchRoom/controllers/ExampleController.java" beforeDir="false" afterPath="$PROJECT_DIR$/BackendFolder/SwitchRoom/src/main/java/vt/CS5934/SwitchRoom/controllers/ExampleController.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/BackendFolder/SwitchRoom/src/main/java/vt/CS5934/SwitchRoom/models/ExampleModel.java" beforeDir="false" afterPath="$PROJECT_DIR$/BackendFolder/SwitchRoom/src/main/java/vt/CS5934/SwitchRoom/models/ExampleModel.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/BackendFolder/SwitchRoom/src/main/resources/application.properties" beforeDir="false" afterPath="$PROJECT_DIR$/BackendFolder/SwitchRoom/src/main/resources/application.properties" afterDir="false" />
<change beforePath="$PROJECT_DIR$/DataBaseFolder/MySQL/docker-compose.yml" beforeDir="false" afterPath="$PROJECT_DIR$/DataBaseFolder/MySQL/docker-compose.yml" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
......@@ -25,16 +28,44 @@
<state>
<projects_view>
<tree_state>
<expand />
<expand>
<path>
<item name="" type="6a2764b6:ExternalProjectsStructure$RootNode" />
<item name="SwitchRoom" type="f1a62948:ProjectNode" />
</path>
</expand>
<select />
</tree_state>
</projects_view>
</state>
</system>
</component>
<component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES">
<list>
<option value="Class" />
</list>
</option>
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="JpbToolWindowState">
<option name="myId2FirstActivated">
<map>
<entry key="com.haulmont.jpb.jpaInspector" value="true" />
<entry key="com.haulmont.jpb.jpaPalette" value="true" />
<entry key="com.haulmont.jpb.jpaStructure" value="true" />
</map>
</option>
<option name="myId2Visible">
<map>
<entry key="com.haulmont.jpb.jpaInspector" value="false" />
<entry key="com.haulmont.jpb.jpaPalette" value="false" />
<entry key="com.haulmont.jpb.jpaStructure" value="true" />
</map>
</option>
</component>
<component name="MarkdownSettingsMigration">
<option name="stateVersion" value="1" />
</component>
......@@ -47,10 +78,27 @@
"keyToString": {
"RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"last_opened_file_path": "D:/Code"
"last_opened_file_path": "D:/Code/switchroom",
"project.structure.last.edited": "Project",
"project.structure.proportion": "0.0",
"project.structure.side.proportion": "0.0",
"settings.editor.selected.configurable": "preferences.lookFeel"
}
}]]></component>
<component name="RunManager" selected="Docker.MySQL: Compose Deployment">
<component name="RunManager" selected="Application.SwitchRoomApplication">
<configuration name="SwitchRoomApplication" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="vt.CS5934.SwitchRoom.SwitchRoomApplication" />
<module name="SwitchRoom.main" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="vt.CS5934.SwitchRoom.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="MySQL: Compose Deployment" type="docker-deploy" factoryName="docker-compose.yml" temporary="true" server-name="Docker">
<deployment type="docker-compose.yml">
<settings>
......@@ -75,6 +123,7 @@
<recent_temporary>
<list>
<item itemvalue="Docker.MySQL: Compose Deployment" />
<item itemvalue="Application.SwitchRoomApplication" />
<item itemvalue="Docker.MySQL.db: Compose Deployment" />
</list>
</recent_temporary>
......@@ -102,7 +151,14 @@
<option name="project" value="LOCAL" />
<updated>1665804763932</updated>
</task>
<option name="localTasksCounter" value="3" />
<task id="LOCAL-00003" summary="Added the spring db connection package, and set up the properties file.">
<created>1665806544671</created>
<option name="number" value="00003" />
<option name="presentableId" value="LOCAL-00003" />
<option name="project" value="LOCAL" />
<updated>1665806544671</updated>
</task>
<option name="localTasksCounter" value="4" />
<servers />
</component>
<component name="Vcs.Log.Tabs.Properties">
......@@ -118,6 +174,7 @@
</component>
<component name="VcsManagerConfiguration">
<MESSAGE value="added docker-compose.yml to create the database" />
<option name="LAST_COMMIT_MESSAGE" value="added docker-compose.yml to create the database" />
<MESSAGE value="Added the spring db connection package, and set up the properties file." />
<option name="LAST_COMMIT_MESSAGE" value="Added the spring db connection package, and set up the properties file." />
</component>
</project>
\ No newline at end of file
......@@ -19,9 +19,9 @@ repositories {
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
//implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
implementation 'mysql:mysql-connector-java:8.0.30'
// implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
// implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.session:spring-session-core'
......
......@@ -6,10 +6,14 @@ package vt.CS5934.SwitchRoom.controllers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import vt.CS5934.SwitchRoom.models.ExampleModel;
import vt.CS5934.SwitchRoom.models.ResponseModel;
import vt.CS5934.SwitchRoom.services.ExampleService;
import java.util.List;
/**
* The "@RestController" made the class into rest handle class
......@@ -19,11 +23,17 @@ import vt.CS5934.SwitchRoom.models.ResponseModel;
@RestController
@RequestMapping("example")
public class ExampleController {
/**
* Autowired is a Spring feature that it will create or looking for the existing object in memory.
* It usually uses on Repository class, Service class, or some globe object in the class.
*/
@Autowired
ExampleService exampleService;
/**
* You can use logger.[trace,debug,info,warn,error]("messages") to log into file
*/
Logger logger = LoggerFactory.getLogger(ExampleController.class);
private final Logger logger = LoggerFactory.getLogger(ExampleController.class);
/**
* This function handles GET request on url "/example"
......@@ -32,11 +42,18 @@ public class ExampleController {
@GetMapping
public ResponseModel getExample() {
logger.info("You reached the getExample() function.");
return new ResponseModel(
"This this a example String response",
HttpStatus.OK,
"Some Json Object Later");
try{
List<ExampleModel> exampleModels = exampleService.getAllExampleModelsFromDB();
return new ResponseModel(
"This this a example String response",
HttpStatus.OK,
exampleModels);
}catch (Exception e){
return new ResponseModel(
"Error occur on get All ExampleModels, Error info is: " + e,
HttpStatus.OK,
null);
}
}
/**
......@@ -46,10 +63,19 @@ public class ExampleController {
*/
@GetMapping("/{userId}")
public ResponseModel getExampleWithInput(@PathVariable long userId){
return new ResponseModel(
"This this a example String response",
HttpStatus.OK,
"You GET this function with id = "+ userId);
try{
ExampleModel exampleModel = exampleService.getExampleModelWithIDFromDB(userId);
return new ResponseModel(
"This this a example String response",
HttpStatus.OK,
exampleModel);
}catch (Exception e){
return new ResponseModel(
"Error occur on get ExampleModel with user_id == " + userId
+ "Error info is: " + e,
HttpStatus.OK,
null);
}
}
/**
......@@ -59,6 +85,7 @@ public class ExampleController {
*/
@GetMapping("/detail/{userId}")
public ResponseModel getExampleDetailWithInput(@PathVariable long userId){
return new ResponseModel(
"This this a example String response",
HttpStatus.OK,
......@@ -71,7 +98,7 @@ public class ExampleController {
*/
@RequestMapping("/getUser")
public ResponseModel getExampleUser(){
ExampleModel user = new ExampleModel(233, "example-user");
ExampleModel user = new ExampleModel( "example-user");
return new ResponseModel(
"There is your example user info",
HttpStatus.OK,
......@@ -86,10 +113,22 @@ public class ExampleController {
@PostMapping("/newUser")
public ResponseModel handlePost(@RequestBody ExampleModel newUser){
logger.info("You reached the handlePost() function.");
return new ResponseModel(
"I received your new user data, check it in data section",
HttpStatus.OK,
newUser);
ResponseModel response = new ResponseModel();
try{
ExampleModel newModel = exampleService.addNewExampleModelToDB(newUser.getUsername());
response.setMessage("Saved successfully");
response.setStatus(HttpStatus.OK);
response.setData(newModel);
return response;
}catch (Exception e){
return new ResponseModel(
"Error occur on save new example model to DB, model: " + newUser
+ " Error info is: " + e,
HttpStatus.OK,
null);
}
}
/**
......@@ -100,10 +139,24 @@ public class ExampleController {
@DeleteMapping("/logout/{userId}")
public ResponseModel logout(@PathVariable long userId){
logger.warn("You reached the logout() function.");
return new ResponseModel(
"I received your logout request",
HttpStatus.OK,
null);
ResponseModel response = new ResponseModel();
try{
response.setStatus(HttpStatus.OK);
if(exampleService.removeExampleModelWithId(userId)){
response.setMessage("Successfully Delete ExampleModel with ID: " + userId);
}else{
response.setMessage("Unable to Delete ExampleModel with ID: " + userId);
}
return response;
}catch (Exception e){
return new ResponseModel(
"Error occur on delete ExampleModel with by: " + userId
+ " Error info is: " + e,
HttpStatus.OK,
null);
}
}
}
......
/**
* This class this a data model example
* This class this a data model example.
* Model mains data class, it may or may not be saved to DB
*/
package vt.CS5934.SwitchRoom.models;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
/**
* '@Data' tell spring this class can be map to JSON object if needed
* '@Entity' declare this class is a DB table
* '@Table(name=<table_name>)' declared which table stores its data
*/
@Data
@Entity
@Table(name = "example_records_table")
@NoArgsConstructor
public class ExampleModel {
Long userId;
String username;
/**
* '@Id' declare that userId object is the primary id in this table
* '@Column' you can set the table column name in the DB
*/
@Id
@Column(name="user_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
@Column(name="username",unique=true)
private String username;
public ExampleModel(long userId, String name) {
public ExampleModel(String name) {
this.username = name;
this.userId = userId;
}
@Override
public String toString() {
return "ExampleModel{" +
"userId=" + userId +
", username='" + username + '\'' +
'}';
}
}
/*
Change logs:
Date | Author | Description
2022-10-12 | Fangzheng Zhang | create class and init
Date | Author | Description
2022-10-12 | Fangzheng Zhang | create class and init
2022-10-15 | Fangzheng Zhang | Added DB table and colum info
*/
\ No newline at end of file
/**
* This is a repository interface.
* The real class object will be build by SpringBoot to make sure only
* one connection to DB is allowed.
* You can build you query in this class then use it later.
*/
package vt.CS5934.SwitchRoom.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import vt.CS5934.SwitchRoom.models.ExampleModel;
import java.util.List;
/**
* The interface have to extend JpaRepository, and the type of the class should be
* < The_model_class, Integer>. In this example, the model class is ExampleModel
*/
public interface ExampleRepository extends JpaRepository<ExampleModel, Integer> {
/**
* The function name is the SQL query:
* findByIdAndName(long inputId, String inputName) == "SELETE * FROM table WHERE Id==inputId" AND name == inputName;
* This is an example of how to declare a SQL command, those will be use in service class
* @param userId the id in table you are looking for
* @return ExampleModel object
*/
ExampleModel findByUserId(long userId);
List<ExampleModel> findAll();
void deleteByUserId(long userId);
}
/*
Change logs:
Date | Author | Description
2022-10-15 | Fangzheng Zhang | Set up example repository for example mode table
*/
\ No newline at end of file
/**
* This class will hold the business logics of certain service
* This class is a example service.
*/
package vt.CS5934.SwitchRoom.services;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vt.CS5934.SwitchRoom.models.ExampleModel;
import vt.CS5934.SwitchRoom.repositories.ExampleRepository;
import javax.transaction.Transactional;
import java.util.List;
@Service
public class ExampleService {
/**
* You can use logger.[trace,debug,info,warn,error]("messages") to log into file
*/
private final Logger logger = LoggerFactory.getLogger(ExampleService.class);
/**
* Autowired is a Spring feature that it will create or looking for the existing object in memory.
* It usually uses on Repository class, Service class, or some globe object in the class.
*/
@Autowired
ExampleRepository exampleRepository;
public ExampleModel addNewExampleModelToDB(String username){
logger.info("Reached addNewExampleModelToDB()");
ExampleModel newModel = new ExampleModel(username);
exampleRepository.save(newModel);
return newModel;
}
public List<ExampleModel> getAllExampleModelsFromDB(){
logger.info("Reached getAllExampleModelsFromDB()");
return exampleRepository.findAll();
}
public ExampleModel getExampleModelWithIDFromDB(long id){
logger.info("Reached getExampleModelWithIDFromDB()");
return exampleRepository.findByUserId(id);
}
@Transactional
public boolean removeExampleModelWithId(long id){
logger.info("Reached removeExampleModelWithId()");
exampleRepository.deleteByUserId(id);
return true;
}
}
/*
Change logs:
Date | Author | Description
2022-10-15 | Fangzheng Zhang | Set up example service class
*/
\ No newline at end of file
# Server Configuration
server.port=8081
# MySQL Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/switch_room_db
spring.datasource.username=root
spring.datasource.password=mypassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57InnoDBDialect
\ No newline at end of file
{
"name": "FrontendFolder",
"lockfileVersion": 2,
"requires": true,
"packages": {}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment